본문 바로가기
개발 언어/자바스크립트 33가지 개념

[JavaScript 33가지 개념] 05. == vs === vs typeof

by 우주다람쥐 2021. 5. 27.
반응형

 

코딩을 하다보면 조건문을 많이 사용하게 된다.

조건문에서 특히 Equality 문법을 사용하게 되는데, 해당 문법에 대해 자세히 알아보자.

 

1. ===

=== 는 엄격한 Equality 연산자이다.

=== 는 데이터의 값과 타입이 모두 같아야 true를 반환해준다.

 

console.log(0 === 0); // true
console.log('hello!' === 'hello!'); // true
console.log(null === null); // true
console.log(undefined === undefined); // true

console.log(0 === 5); // false
console.log(0 === '0'); // false
console.log(0 === 'hello!'); // false
console.log(null === undefined); // false

const obj = {};
const obj2 = obj;
console.log(obj === obj); // true
console.log(obj === obj2); // true (같은 객체를 참조하기 때문에)
console.log(obj === {}); // false (객체는 참조로 비교되기 때문에)

 

2. ==

== 는 좀느슨한  Equality 연산자이다.

=== 는 데이터의 타입이 달라도 강제 변환을 통해 true 값을 내려준다.

 

console.log(1 == 1) // true
console.log(1 == '1') // true (string이 number로 변환 되었기 때문에)
console.log('1' == 1) // true (string이 number로 변환 되었기 때문에)
console.log(0 == false) // true (boolean이 number로 변환 되었기 때문에)
console.log(0 == null) // false (값이 없는 것은 구체적인 값과 같지 않은 것으로 간주되기 때문에)
console.log({} == {}) // false (객체는 참조로 비교되기 때문에)
console.log(0 == undefined) // false (값이 없는 것은 구체적인 값과 같지 않은 것으로 간주되기 때문에)
console.log(null == undefined) // true (둘 다 값이 없음을 나타 내기 때문에)
console.log(undefined == null) // true (둘 다 값이 없음을 나타 내기 때문에)
console.log("hello!" == false) // false
console.log("" == false) // true
console.log([] == false) // true

 

예시를 보면 알겠지만 혼동스러운 부분이 많다.

그렇기 때문에 == 를 사용하는 것을 권장하지 않는다.

 

3. typeof

typeof는 javascript 값의 type을 리턴해주는 연산자이다.

typeof로 리턴 받을 수 있는 type은 아래와 같다.

 

- Undefined

- String

- Number

- Boolean

- Object

- Function

- Symbol

- bigint

// undefined
console.log(typeof undefined);

// string
console.log(typeof '');
console.log(typeof 'bla');
console.log(typeof `template literal`);
console.log(typeof '1');

// number
console.log(typeof 37);
console.log(typeof 3.14);
console.log(typeof NaN);

// boolean
console.log(typeof true);
console.log(typeof !!(0));

// object
console.log(typeof { a: 1 });
console.log(typeof [1, 2, 4]);
console.log(typeof new Date());
console.log(typeof null);

// function
console.log(typeof function() {});
console.log(typeof class C {});
console.log(typeof Math.sin);

// symbol
console.log(typeof Symbol());
console.log(typeof Symbol('foo'));

// bigint
console.log(typeof 42n);

 

예시를 보면 알겠지만 NaN, array, date, null 등 세분화해서 알려주지 못 하는 값도 있다.

typeof 라는 연산자가 유용하긴 하지만 상황에 맞게 사용하지 않으면 의도치 않은 에러를 발생시킬 수 있다.

 

아래의 연산자를 혼용해서 쓰면 다양한 예외 처리를 할 수 있다.

 

- Number.isNaN

NaN 유무를 판별해주는 연산자이다.

// NaN
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN(1)); // false
console.log(Number.isNaN('abc')); // false

 

- Array.isArray

array 유무를 판별해주는 연산자이다.

// array
console.log(Array.isArray([]));  // true
console.log(Array.isArray([1,5,8]));  // true
console.log(Array.isArray(1));  // false

 

 

참고 자료

- https://tomeraberba.ch/html/post/checking-for-the-absence-of-a-value-in-javascript.html

 

Tomer Aberbach | Checking for the Absence of a Value in JavaScript

A thorough overview of the right way to check for the absence of a value in JavaScript.

tomeraberba.ch

- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

 

typeof - JavaScript | MDN

The typeof operator returns a string indicating the type of the unevaluated operand.

developer.mozilla.org

 

반응형

댓글