Javascript

Javascript - Truthy and Falsy

Starters 2020. 9. 4. 20:07
function print(person){
  // if(person === undefined || person === null){
  //   return;
  // } // 이런걸 null checking이라함

  // 위에랑 같은 뜻
  if(!person){
    return;
  }
  console.log(person.name);
}

const person = null;

print();

// falsy한 값들 5가지 !하면 true 값이 나온다.
console.log(!undefined);
console.log(!null);
console.log(!'');
console.log(!0);
console.log(!NaN);


// 이외 나머지 값들은 truthy한 값들이다.
console.log(!3);
console.log(!'hello');
console.log(![]);
console.log(!{});

const value = null;

const truthy = !!value; // 이렇게 쓰면 true값으로 받을 수 있다.
console.log(truthy);

Falsy한 값 5가지 알아두는 것이 가장 중요!

코드를 짧게 쓸 수 있다.