본문으둜 κ±΄λ„ˆλ›°κΈ°

[Easy] πŸ“„ null & undefined

두 κ°€μ§€ 차이점 비ꡐ​

  • undefined:
    • λ³€μˆ˜κ°€ μ„ μ–Έλ˜μ—ˆμ§€λ§Œ 아직 값이 ν• λ‹Ήλ˜μ§€ μ•Šμ•˜μŒμ„ λ‚˜νƒ€λƒ…λ‹ˆλ‹€.
    • μ΄ˆκΈ°ν™”λ˜μ§€ μ•Šμ€ λ³€μˆ˜μ˜ κΈ°λ³Έκ°’μž…λ‹ˆλ‹€.
    • ν•¨μˆ˜κ°€ λͺ…μ‹œμ μœΌλ‘œ 값을 λ°˜ν™˜ν•˜μ§€ μ•ŠμœΌλ©΄ 기본적으둜 undefinedλ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
  • null:
    • 빈 κ°’ λ˜λŠ” 값이 μ—†μŒμ„ λ‚˜νƒ€λƒ…λ‹ˆλ‹€.
    • 일반적으둜 λͺ…μ‹œμ μœΌλ‘œ null을 ν• λ‹Ήν•΄μ•Ό ν•©λ‹ˆλ‹€.
    • λ³€μˆ˜κ°€ μ˜λ„μ μœΌλ‘œ μ–΄λ–€ κ°μ²΄λ‚˜ 값도 가리킀지 μ•ŠμŒμ„ λ‚˜νƒ€λ‚΄λŠ” 데 μ‚¬μš©λ©λ‹ˆλ‹€.

μ˜ˆμ‹œβ€‹

let x;
console.log(x); // 좜λ ₯: undefined

function foo() {}
console.log(foo()); // 좜λ ₯: undefined

let y = null;
console.log(y); // 좜λ ₯: null

let obj = { x: 5 };
obj.x = null;
console.log(obj.x); // 좜λ ₯: null

typeofλ₯Ό μ΄μš©ν•œ 검증​

console.log(typeof undefined); // 좜λ ₯: "undefined"
console.log(typeof null); // 좜λ ₯: "object"

console.log(null == undefined); // 좜λ ₯: true
console.log(null === undefined); // 좜λ ₯: false