[Javascript] undefined와 null의 차이

undefined와 null의 차이를 알아보자


환경

  • Javascript


undefined와 null

undefined

  • 변수가 값을 할당받지 않았을 때 사용되는 원시 값(primitive value)입니다.
  • 함수의 반환이 명시적으로 없으면 undefined를 반환합니다.
  • 원시 자료형 중 하나
// test default
let test;
console.log('variable test is ' + test);

// if statement
if (test === undefined) {
  console.log('variable test is ' + test);
}

// if statement
if (undefined) {
  console.log('undefined is considered as true');
} else {
  console.log('undefined is considered as false');
}

// type test in if statement
// return type of typeof function is string
if (typeof(test) === 'undefined') {
  console.log('variable test value is ' + test + ' and type is ' + typeof(test));
}

// function return
function testReturnNothing() {
  let c;
}
console.log('testReturnNothing returns ' + testReturnNothing());

// check which is not defined
if (typeof(notDefinedVariable) === 'undefined') {
  console.log('variable notDefinedVariable is not defined');
}
variable test is undefined
variable test is undefined
undefined is considered as false
variable test value is undefined and type is undefined
testReturnNothing returns undefined
variable notDefinedVariable is not defined


null

  • 의도적으로 객체나 변수가 비어있음을 나타내는 원시 값입니다.
  • API에서는 대개 객체를 기대했지만, 어떤 적합한 객체도 존재하지 않을 때 반환합니다.
  • 불리언(Boolean) 자료형에서는 거짓을 의미합니다.
// test default
let test = null;
console.log('variable test is ' + test);

// if statement
if (test === null) {
  console.log('variable test is ' + test);
}

// if statement
if (null) {
  console.log('null is considered as true');
} else {
  console.log('null is considered as false');
}

// type test in if statement
// return type of typeof function is string
// its return type is not 'null' it is 'object'
if (typeof(test) === 'object') {
  console.log('variable test value is ' + test + ' and type is ' + typeof(test));
}

// function return
function testReturnNull() {
  return null;
}
console.log('testReturnNull returns ' + testReturnNull());
variable test is null
variable test is null
null is considered as false
variable test value is null and type is object
testReturnNull returns null


비교

undefined

  • 아직 할당되지 않았음을 의미하는 값

null

  • 의도적으로 비어있음을 나타내는 값

기타

  • ==를 사용시 둘은 같으며 ===를 사용시 둘은 다릅니다.
  • ===의 경우에 type까지 같이 비교하기 때문에 그렇습니다. 각각의 type은 아래처럼 다릅니다.
typeof(null)         // object
typeof(undefined)    // undefined

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

!null                // true
!undefined           // true


참고자료