기본적으로 Primitive types에는 Nubmer
, String
, Boolean
, undefined
, null
, syombol
이 있다.
여기서는 기본적인 지식을 갖고 있다고 가정하고 코드로 간단히 설명하도록 하겠다.
const num = 10;
console.log(typeof(num)); // Number
const NAN = NaN;
console.log(typeof(NAN)); // Number --> str/num도 NaN을 return한다. 나도 사실 잘 모르겠다..ㅎ
const str = "Hello";
console.log(typeof(str)); // String
const boolean = true;
console.log(typeof(boolean)); // Boolean
const Undefined = undefined;
console.log(typeof(Undefined)); // undefined
const Null = null;
console.log(typeof(Null)); // object --> 이는 js의 초창기 오류임. null은 object가 아님에 유의할 것.
const Sym = Symbol();
console.log(typeof(Sym)); // Symbol
여기서 하나 짚고 넘어갈 것은 undefined
와 null
은 다르다는 것이다.
undefined
는 그냥 값이 아직 할당되지 않은 것 뿐이고, null
은 의도적으로 값이 할당되지 않은 것을 명시한 것이다.
간단한 코드를 보고 이해해보자.
let hello; // 아직 값을 할당하지 않음
console.log(hello); // undefined
console.log(hello === undefined); // true
hello = null; // hello라는 변수에 null이라는 값을 할당 함
console.log(hello); // null
console.log(hello === null); // true
console.log(hello === undefined); // false
console.log(null == undefined); // true --> == 에 의해 강제로 자료형이 변환되어 true가 나온 것이지 null과 undefined가 같은 것은 아님
console.log(null === undefined); // false
undefined
는 아직 값이 할당되지 않았고 메모리 공간을 초기화하면서 자연스럽게 할당된 값이고(의도하지 않음),
null
은 해당 변수에는 값이 없으며 이는 개발자가 의도적으로 값이 없음을 할당한 것이다.
Reference