Front-End(Web)/Javascript

[Javascript] 변수(Variable) & 자료형(Type)

ttaeng_99 2020. 11. 24. 01:56
반응형

Wecode 2주차(Javascript) 미션 겸, 변수 및 자료형 복습을 위함.


💛 변수(Variable)

 

1. 변수(Variable) 란?

프로그래밍 언어에서, 메모리의 위치를 가진 이름값을 의미한다. (자료를 담고 있다는 개념)

변수를 선언하는 방법은 var, let, const 3가지가 있다.

var a = 1;
let b = 2;
const c = 3;

 

 

2. 변수 선언방법: var, let, const

- var

  • ES5까지 사용되던 변수 선언방법. 수정가능.
  • Functional Scope. 전역변수처럼 반영되어 아래와 같은 성질로 인해 정교성이 떨어진다.
  • 한 Scope 내에서도 같은 이름의 변수를 재선언할 수 있다.
  • 함수처럼 Hoisting 되어, 변수 선언 전에도 이미 변수가 존재하는 것으로 인식됨.
function () {
    console.log(a); // undefined(초기값 상태)
    var a = 1;
    console.log(a); // 1
}

* Hoisting: 함수 등을 선언하면 JS 맨 상단으로 올라가서 전역에서 사용이 가능도록 하는 현상.

 

- let

  • ES6 신규제공된 변수 선언방법. 수정가능.
  • Block Scope. 지역변수 개념으로 Scope({}) 내에서만 유효함.
  • 한 Scope 내에선 같은 이름의 변수를 재선언할 수 없음.
function f() {
    {
      let x;
      {
          // 새로운 블록 안에 새로운 x의 스코프가 생김
          const x = "sneaky";
          x = "foo"; // 위에 이미 const로 x를 선언했으므로 다시 값을 대입하면 Error
      }
      // 이전 블록 범위로 돌아왔기 때문에 'let x'에 해당하는 메모리에 값을 대입
      x = "bar";
      let x = "inner"; // SyntaxError: Identifier 'x' has already been declared
    }
}

 

- const

  • ES6 신규제공된 변수 선언방법. 수정불가.
  • Block Scope. 마찬가지로 지역변수 개념.
const a = 10;
a = 20; // Uncaught TypeError: Assignment to constant variable

/* [주의!] 하지만, 객체나 배열의 내부는 변경할 수 있다. */
const a = {};
a.num = 10;
console.log(a); // {num: 10}

const b = [];
b.push(20);
console.log(b); // [20]

💛 자료형(Type)

 

3. 자료형(Type) 이란?

변수로 선언한 자료의 형태 혹은 성질. 기본적으로, 기본형과 참조형으로 분류하며 종류는 아래와 같다.

  • 기본형(Primitive Type): Number, String, Boolean, null, undefined
  • 참조형(Reference Type): Object, Array, Function, RegExp(정규식) - 기본형의 집합으로 메모리의 위치값을 참고

 

4.  자료형(Type) 종류

- Number: 숫자형

const count = 17; 		// 17(integer)
const size = 17.1; 		// 17.1(decimal)

const inf = 1 / 0;		// Infinity
const negInf = -1 / 0;		// NegativeInfinity
const nAn = "not" / 2;		// NaN(숫자가 아님)

 

- String: 문자형

const char = 'c';			// c
const tae = 'taeng';			// taeng
const greeting = 'hello' + tae		// hello taeng
const greeting2 = `hi ${tae}`;		// hi taeng - template literals

* Template literals 사용시에는, `따옴표` 및 내부에는 ${변수}임을 반드시 숙지!

 

- Boolean: true/false형

const tru = true;			// true
const fal = 3 < 1;			// false

* false에는 0, null, undefined, NaN, ' ' 등이 해당된다.

 

- null(없는 값) / undefined(있으나 선언하지 않은 값, 초기값)

let x;

console.log(x);			// undefined
console.log(y);			// null

 

- Object: 객체타입 (key로 위치확인: obj['key']  or obj.key)

const obj = { name: 'taeng', age: 28 };

console.log(obj.name);			// taeng

obj.age = 29				// 28 -> 29 (내부요소는 수정가능)

 

- Array: 배열타입 (index로 위치확인: arr[1])

const list = [];
const list2 = [1, 2, 3, 4, 5];

console.log(list2[1]);			// 2

 

- Function: 함수 타입 (변수에 지정할수도 있고, 함수이름 자체도 Hoisting되서 사용가능)

function Plus(x,y) { return x+y; };
const myFunc = function Alert() { return 'Function in Variable'; };

Plus(2,3);				// 5
console.log(myFunc)			// Function in Variable

 

5. 자료형(Type) 확인 및 변경

- 확인: typeof 로 기본형, instanceof 로 참조형을 확인할 수 있다.

let num = 1;
typeof num;			// number

let str = 'hi';
typeof str;			// string

let arr = [];
typeof arr;			// object
arr instanceof			// array

 

- 변경: 함수, 메서드 등 사용하면 된다.

// Boolean(), Number(), String(), Object() 함수 사용하기
Boolean(x)
Number(x)
String(x)
Object(x)

// 메서드 사용하기
x.toString() 
x.toFixed() 
x.toExponential() 
x.toPrecision()

// parseInt(), parseFloat() 숫자형태 변형(전역함수)
parseInt(x)
parseFloat(x)

 

6. Javascript의 Dynamic Typing(동적 자료형 설정)

변수타입을 선언하지 않으면 상황에 따라 number-string 판단함.

let text = "hello";
console.log(text.charAt(0));		// 첫글자 h만 출력

text = 1;
text = "7" + 5; 			//5를 string으로 변환 → 75!
text = "8" / "2"; 			//8, 2를 number로 변환 → 4!
console.log(text.charAt(0));		// string이 아니므로 Error!

Hoisting의 정확한 개념, Template literal 명칭 등 개념을 본질적으로 공부하는 좋은 기회였다. 

반응형