본문 바로가기
카테고리 없음

[JS] truthy, falsy

by 상똥 2024. 12. 18.

[1. 원시타입과 참조타입]

자바스크립트에서의 변수의 종류에 따라 문법이 달라진다.

원시변수와 참조변수에 따라 값의 복사 방식이 달라지고 (결국엔 모두 call by value지만) truthy와 falsy가 달라진다

 

1. 원시변수

- 개념 : 실제 데이터값을 저장하는타입

- 종류 : ES6 기준 원시형 변수는 아래와 같다

string, number, boolean, bigint, undefined, symbol

 

2. 참조변수

- 개념 : 메모리 번지를 통해 객체 값을 참조하는 타입

- 종류 : Object

 

[2. truthy, falsy]

명시적 형변환을 위해 !!를 사용하여 확인해 보겠다 

1. 원시타입의 truthy, falsy

- 값에 따라 결과가 달라진다

- false

const a = '';
const b = 0;
const c = false;
const d = null;
const e = undefined;

console.log(!!a);   // false
console.log(!!b);   // false
console.log(!!c);   // false
console.log(!!d);   // false
console.log(!!e);   // false

- true

const a = 'value';
const b = 1;
const c = true;

console.log(!!a);   // true
console.log(!!b);   // true
console.log(!!c);   // true

 

2. 참조타입의 truthy, falsy

- 참조타입은 무조건 true

const a = new String('');
const b = new Number(0);
const c = new Boolean(false);
const d = new Object();
const e = {};
const f = [];

console.log(!!a);   // true
console.log(!!b);   // true
console.log(!!c);   // true
console.log(!!d);   // true
console.log(!!e);   // true
console.log(!!f);   // true