전체 방문자
오늘
어제
  • 전체 글
    • HTML
    • CSS
    • Javascript
    • React
    • Typescript
    • Next.js
    • Webpack
    • Vue.js
    • Git & GitHub
    • Error
    • Study
    • 개발 일지✨

블로그 메뉴

  • 💡
  • ⚙️
hELLO · Designed By 정상우.
하루

Home

Truthy / Falsy
Javascript

Truthy / Falsy

2022. 2. 1. 21:34

이것은 자바스크립트 문법까지는 아니지만 알아둬야 하는 개념이다.

 

Truthy

: true 같은거

console.log(3);
console.log('hello');
console.log(['array?']);
console.log([]);
console.log({ value: 1 });

 

Falsy

: false 같은거

console.log(undefined);
console.log(null);
console.log(0);
console.log('');
console.log(NaN);

*NaN: Not A Number

NaN은 보통 문자열을 숫자로 변환하는 자바스크립트 기본함수 parseInt 라는 함수를 사용하게 될 때 볼 수 있다.

 

예시

  • print 함수가 파라미터가 비어진채로 실행됐을 때
function print(person) {
  console.log(person.name);
}

const person = {
  name: 'John'
};

print();

> 에러

TypeError: Cannot read property 'name' of undefined

 

  • print에 null 값이 파라미터로 전달되었을 때
function print(person) {
  if (person === undefined) {
    console.log('person이 없네요');
    return;
  }
  console.log(person.name);
}

const person = null;
print(person);

> 에러

TypeError: Cannot read property 'name' of null

 

이렇게 person이 undefined 이거나, null 인 Falsy한 값을 받았을 때의 상황을 대비하려면 다음과 같이 코드를 작성해준다.

function print(person) {
  if (person === undefined || person === null) {
    console.log('person이 없네요');
    return;
  }
  console.log(person.name);
}

const person = null;
print(person);

이를 축약해서 이렇게 작성할 수도 있다.

function print(person) {
  if (!person) {
    console.log('person이 없네요');
    return;
  }
  console.log(person.name);
}

const person = null;
print(person);

 

 

if 문에서 적용

value 가 Truthy한 값이기 때문에 콘솔에 메시지가 출력된다.

반면, value 가 null, undefined, 0, "", NaN 중 하나라면 나타나지 않을 것이다.

이렇게 Truthy한 값과 Falsy한 값을 잘 알아놓으면 조건문을 작성할 때 편할 것이다.

const value = { a: 1 };
if (value) {
  console.log('value 가 Truthy 하네요.');
}

 

    'Javascript' 카테고리의 다른 글
    • 함수의 기본 파라미터
    • 단축 평가 논리 계산법
    • 삼항 연산자
    • 프로토타입과 클래스

    티스토리툴바