자바스크립트는 느슨한 타입 (loosely typed) 언어, 혹은 동적 (dynamic) 언어이기 때문에
변수의 타입을 미리 선언할 필요가 없음!!
타입은 프로그램이 처리되는 과정에서 자동으로 파악되기 때문에 같은 변수에 여러 타입의 값을 넣을 수 있음
let a = 42; // a는 Number
a = "bar"; // a는 이제 String
a = true; // a는 이제 Boolean
최신 ECMAScript
표준에 의하면 자바스크립트 자료형은 7개로 구분할 수 있음
Boolean
Null
Undefined
Number
String
Symbol
Boolean
true
false
값 const a = true;
const b = false;
console.log(a, typeof a); // true 'boolean'
console.log(b, typeof b); // false 'boolean'
Null
const a = null;
Undefined
let b;
null
undefined
는 falsy한 값이다Number
const a = 12;
console.log(a, typeof a); // 12 'number'
const b = 12.7;
console.log(b, typeof b); // 12.7 'number'
const c = NaN;
console.log(c, typeof c); // NaN 'number'
NaN
- 숫자가 아님 ( Not-A-Number
) const a = Number('78'); // 문자 78을 숫자로 형변환
console.log(a, typeof a); // 78 'number'
// 숫자로 형변환 했지만 숫자형태 아니기 때문에 숫자로서 읽을 수 없음
const b = Number('wow');
console.log(b, typeof b); // NaN 'number'
String
''
또는 ""
로 감싸준다 const a = 'apple';
const a = 'Hello' + ' World';
console.log(a); // Hello World
const a = 'Hello';
console.log(a + ' World'); // Hello World
const fruit = 'melon';
const food = 'pizza';
console.log('I like ' + fruit + ' and ' + food);
이러한 불편함을 줄이기 위해 ES6
부터 생긴 기능이 있음 → 템플릿 리터럴
따옴표 ( ''
""
) 대신 백틱 ( `
)을 사용하고,
표현식을 ${expression}
으로 표현!
const fruit = 'melon';
const food = 'pizza';
console.log(`I like ${fruit} and ${food}`);
Symbol
ES6
에서 추가된 기능Symbol()
함수를 호출 const a = ('tomato');
const b = ('tomato');
console.log(a === b); // true ( Symbol이 아닌 경우 두 값은 같음 )
const a = Symbol('tomato');
const b = Symbol('tomato');
console.log(a === b); // false ( 다른 값 )
string
이 같을 시, 동일한 symbol
을 만드려면 .for
const a = Symbol.for('orange');
const b = Symbol.for('orange');
console.log(a === b); // true
symbol
을 출력할때는 .description
을 붙여야 함 console.log(`a is ${a}`); // TypeError
console.log(`a is ${a.description}`); // a is orange
📝 출처