JavaScript: undefined와 null

MARCOIN·2022년 5월 18일

JavaScript에는 '없음'을 나타내는 값이 undefined와 null 두 가지가 있다.
두 값의 의미는 같은 것 같지만 미세하게 다르고, 사용하는 목적이 다르다.


1. undefined

undefined는 그 자체가 값으로 '비어있음'을 의미하기는 하지만 하나의 값으로 동작

  • 값을 대입하지 않은 변수, 즉 데이터 영역의 메모리 주소를 지정하지 않은 식별자에 접근할 때
  • 객체 내부의 존재하지 않는 프로퍼티에 접근하고자 할 때
  • return문이 없거나 호출되지 않는 함수의 실행 결과
let temp
console.value(temp)
//출력: undefined

function myName(name){
	console.log(`My Name is ${name}`)
}
myName()
//출력: My Name is undefined

let a;
console.log(a); 
//출력: undefined
console.log(typeof a);
//출력: undefined

2. null

null은 사용자가 명시적으로 '없음'을 표현하기 위해 대입한 값
(본래의 의미에 따라 사용자가 없음을 표현하기 위해 명시적으로 undefined를 대입하는 것은 지양해야함)

  • typeof null은 object (자바스크립트 자체의 버그라고 함)
var n = null
console.log(typeof n)
//출력: object

console.log(n == undefined)
//출력: true
console.log(n == null)
//출력: false

console.log(n === undefined)
//출력: false
console.log(n === null)
//출력: true
profile
공부하는 기획자 👀

0개의 댓글