Javascript
[JavaScript] truthy and falsy와 단축 평가 논리 계산
mickey7
2023. 10. 16. 11:27
falsy한 값들에는 undefined, null, '', 0, NaN 등이 있고,
truthy한 값들은 falsy한 값들을 제외한 부분이라고 생각하면 됩니다.
출처:
https://developer.mozilla.org/ko/docs/Glossary/Truthy
https://developer.mozilla.org/ko/docs/Glossary/Falsy
(1) && 연산자로 코드 단축시키기
파라미터에 인수값 없을 때
const car = {
name: 'porsche'
};
function getName(car) {
return car && car.name;
}
const name = getName();
console.log(name); // 출력값 : undefined
파라미터에 인수값 있을 때
const car = {
name: 'porsche'
};
function getName(car) {
return car && car.name;
}
const name = getName(car);
console.log(name); // 출력값 : porsche
요약하자면 ,
A && B 연산자를 사용하게 될 때에는 A 가 Truthy 한 값이라면, B 가 결과값이 됩니다. 반면, A 가 Falsy 한 값이라면 결과는 A 가 됩니다.
더 많은 예시를 보면
console.log(true && 'hello'); // hello
console.log(false && 'hello'); // false
console.log('hello' && 'bye'); // bye
console.log(null && 'hello'); // null
console.log(undefined && 'hello'); // undefined
console.log('' && 'hello'); // ''
console.log(0 && 'hello'); // 0
console.log(1 && 'hello'); // hello
console.log(1 && 1); // 1
출처 : https://learnjs.vlpt.us/useful/03-short-circuiting.html
(2) || 연산자로 코드 단축시키기
const namelessCar = {
name: ''
};
function getName(car) {
const name = car && car.name;
if (!name) {
return '이름이 없는 차입니다';
}
return name;
}
const name = getName(namelessCar);
console.log(name); // 출력값 : 이름이 없는 차입니다.
위 코드는 || 연산자를 사용하면 다음과 같이 단축시킬 수 있습니다.
const namelessCar = {
name: ''
};
function getName(car) {
const name = car && car.name;
return name || '이름이 없는 차입니다.';
}
const name = getName(namelessCar);
console.log(name); // 출력값 : 이름이 없는 차입니다.
A || B 는 만약 A 가 Truthy 할경우 결과는 A 가 됩니다. 반면, A 가 Falsy 하다면 결과는 B 가 됩니다.