nullish, null vs undefined, falsy

강연주·2024년 11월 6일

📚 TIL

목록 보기
86/186

nullish한 값이란?

Nullish values in JavaScript are null and undefined. These values fall under falsy values but are more specifically referred to as null values. All nullish values are falsy, but not all falsy values (for example, 0) are nullish.

JS에서는 null과 undefined가 nullish한 값이다.
모든 nullish한 값들은 falsy하지만, 모든 falsy한 값들이 nulllish한 것은 아니다!

So, the nullish operator is related to null and undefined values while other logical operators are related to truthy and falsy values in general.

일반적으로 null 병합 연산자는 null, undefined 값과 연관돼 있고,
다른 연산자들은 truthy하거나 falsy한 값과 관련이 있다.

https://www.freecodecamp.org/news/what-is-the-nullish-coalescing-operator-in-javascript-and-how-is-it-useful/


null 병합연산자 (??)

자바스크립트에서 nullish 값은 null과 undefined 두 가지.
이 값들은 자바스크립트에서 "존재하지 않음" 또는 "정의되지 않음"을 나타내며,
종종 null 병합 연산자 (??)와 함께 사용된다.

🖥️javascript

let value = null;
console.log(value ?? "기본값"); // "기본값" 출력

value = undefined;
console.log(value ?? "기본값"); // "기본값" 출력

value = 0;
console.log(value ?? "기본값"); // 0 출력, 0은 nullish 값이 아님

?? 연산자는 value가 null 또는 undefined일 때만 오른쪽 값을 반환하고,
0, false, '' 등 다른 falsy 값은 그대로 반환한다.

https://ko.javascript.info/nullish-coalescing-operator


null vs undefined

자바스크립트에서 null과 undefined는 둘 다 값이 없음을 나타내지만, 의미와 용도에서 차이가 있다.

🌫️ undefined

  • 정의되지 않음을 의미
  • 변수가 선언되었지만, 초기화되지 않았을 때 자동으로 할당되는 값
  • 함수가 명시적으로 반환 값을 지정하지 않으면 undefined를 반환
  • 객체의 프로퍼티를 찾을 수 없을 때도 undefined 반환
🖥️ javascript

let a;
console.log(a); // undefined

function test() {}
console.log(test()); // undefined

const obj = {};
console.log(obj.someProperty); // undefined

☁️ null

  • 의도적으로 값이 비어 있음을 나타냄
  • 개발자가 어떤 변수에 "비어 있는 상태"나 "값이 없음"을 명시적으로 할당할 때 사용
  • typeof null의 결과는 "object"로 나오는데,
    이는 JS 초기 설계의 역사적 오류지만 지금까지 유지되고 있다.
🖥️ javascript

let b = null;
console.log(b); // null


falsy한 값들?

자바스크립트에서 falsy 값은 논리적으로 false로 평가되는 값들을 의미한다.

  • false : 불리언 false 값 자체
  • 0 : 숫자 0
  • -0 : 음의 0 (자바스크립트에서 -0도 존재한다)
  • 0n : BigInt 형식에서 0
  • "" 또는 '' 또는 `` (빈 문자열)
  • null
  • undefined
    (nullish한 값들은 다 falsy하지만, 모든 falsy한 값들이 nullish는 아니라고 했다!)
  • NaN : 숫자가 아닌 값

이 값들은 모두 조건문에서 false로 평가되므로,
if문에서 직접 사용하거나 논리 연산자와 함께 사용할 때 주의가 필요하다.

🖥️ javascript

if (!0) {
  console.log("0은 falsy 값입니다."); // 출력됨
}

if (!"") {
  console.log("빈 문자열은 falsy 값입니다."); // 출력됨
}

if (!null) {
  console.log("null은 falsy 값입니다."); // 출력됨
}
profile
아무튼, 개발자

0개의 댓글