코딩일상

[JavaScript 33가지 지식] == vs === vs type of 본문

개발 공부/JavaScript 33가지 필수지식

[JavaScript 33가지 지식] == vs === vs type of

solutionMan 2022. 12. 1. 11:44
반응형

비교연산자

==동등비교(loose equlity)연산자

===일치비교(strict equlity)연산자

'==' 연산자를 이용하여 서로 다른 유형의 두 변수의 [값] 비교

'==='는 엄격한 비교를 하는 것으로 알려져 있다 ([값 & 자료형] -> true).

'0'=='' //false
0 =='' //ture
0 =='0' //true
0 == false // true
0 === false // false

console.log(typeof 0); 	//  "number"
console.log(typeof false); // "boolean"

2 == "2" //  true
2 === "2" // false

주의 해야할점

NaN === NaN //false

//Number.isNaN 함수는 지정한 값이 NaN인지 확인하고 그 결과를 불리언값으로 반환
Number.isNaN(NaN)//true
Number.isNaN(10)//false
Number.isNaN(1+ undefined)//false

0 == -0 //true
0 === -0 //true

Object.is(-0,+0) //false
Object.is(NaN,NaN) //true

typeof

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

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

 

- Undefined

- String

- Number

- Boolean

- Object

- Function

- Symbol

- bigint


console.log(typeof undefined);// undefined


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


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


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


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


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


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


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

 

예시를 보면 알겠지만 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

 


목차

 

[JavaScript 33가지 지식] 시리즈 소개 및 목차

소개 아래 깃허브 오픈레포지토리를 기준으로 자바스크립트 개발자로써 필수로 알아야하는 33가지 개념을 정리해나아가보려합니다. GitHub - leonardomso/33-js-concepts: 📜 33 JavaScript concepts every develope

coding-daily.tistory.com

 

반응형
Comments