JavaScript & TypeScript

[javaScript] 조건문에 숫자, 문자열, 객체 넣었을 때 (Truthy/Falsy)

devkmee 2024. 1. 24. 23:01

 

 

 

 

  1. Truthy (참 값)
    • true (boolean)
    • 빈 문자열을 제외한 문자열
    • 0이 아닌 숫자
    • 객체, 배열
  2. Falsy (거짓 값):
    • false (boolean)
    • 0
    • 빈 문자열 ( '' , "" )
    • null
    • undefined
    • NaN (Not-a-Number = 숫자가 아님)
  3. 응용
const testObj = { a: 'abc' };
const testArr = [];

const testFn = () => {
  //문자열
  let abc = testObj?.a ? testObj?.a : ''; //삼항연산자로 a 프로퍼티 값을 비교 및 변수 초기화. 문자열 'abc'가 할당
  if (abc) console.log('success text !!', abc); //if문으로 문자열 'abc' 값 비교.

  const txt = '';
  if (txt) console.log('no print'); //공백 비교.
  abc = testObj?.c || ''; //옵셔널 체이닝 연산자로 없는 프로퍼티에 접근해서 논리연산자로 undefinede 비교 후 공백 할당
  if (abc) console.log('no print');

  //숫자
  let num = 0;
  if (num) console.log('no print');
  num++;
  if (num) console.log('success num !!', num);

  //객체, 배열
  if (testObj) console.log('success obj : ', testObj);
  if (testArr) console.log('success arr : ', testArr); //비어있어도 truthy!

  //null
  const nu = null;
  if (!nu) console.log('null: ', nu);
  //undefined
  const unde = testObj?.b;
  if (!unde) console.log('undefined : ', typeof unde);
};