[JavaScript] undefined와 null

C____JIN·2022년 11월 27일
0

JavaScript

목록 보기
2/5
post-thumbnail

undefined와 null

JavsScript에는 '없음'을 undifinednull 두가지로 나타낼 수 있다.

undefined

let foo;
foo		// undefined

const obj = {};
obj.prop;	// undefined

값이 대입되지 않은 변수 혹은 속성을 사용하려고 하면 undefined를 반환한다.

null

let foo = null;
foo 	// null

const obj = {prop: null};
obj.prop 	// null

null은 객체가 없음을 나타낸다.

typeof 연산

typeof null 	// 'object'
typeof undefined 	//	'undefined'

Null Check

== 연산자는 비교하는 두 타입을 일치시킨 후 값만 비교하고,
=== 연산자는 비교하는 두 타입과 값을 모두 비교한다.

null === undefined; // false
null == undefined;  // true

null == 1       // false
null == 'hello' // false
null == false   // false

undefined == 1       // false
undefined == 'hello' // false
undefined == false   // false

위의 코드를 보면,
==를 사용해서 undefinednull에 대해서 Null Check를 할 수 있는 것을 알 수 있다.

추가로 . . !

let a = null;
let b;
let c = '123;

if(a){
  // 실행 안됨
}

if(b) {
  // 실행 안됨
}

if(c) {
  // 실행 됨
}

if에서 조건으로 작용할 때, 값이 nullundefined라면 false로 작동한다.

profile
개발 블로그🌐 개발일지💻

0개의 댓글