💡 단축평가란 ? 논리 연산자를 사용하여 조건문을 처리할 때, 전체 표현식을 평가하지 않고 최소한의 평가로 결과를 도출하는 방식
논리합 연산자 ||는 좌변의 피연산자가 falsy 값 (false, 0, "", null, undefined, NaN)일 때만 우변의 피연산자를 평가.
좌변의 피연산자가 truthy 값일 경우, 그 값이 바로 결과값으로 반환되며, 우변은 평가되지 않음.
let y; // y는 undefined
let z = y || 20; // y가 존재하지 않는 경우 z를 20으로 할당
console.log(z); // 20
코드 1.
const getUserName = (user) => {
if (!user.name) {
return "신원미상";
}
return user.name;
};
코드 2. (좀 더 간소화)
const getUserName = (user) => {
return user.name || "신원미상";
};
코드 3. (최최종)
const getUserName = (user) => user.name || "신원미상";
논리곱 연산자 &&는 좌변이 truthy일 때만 우변을 평가.
조건에 따라 특정 코드를 실행하고자 할 때 유용.
// 사용자가 로그인 상태이면 환영 메시지를 출력
let loggedIn = true;
let username = '훈이';
loggedIn && console.log('환영합니다! ' + username); // 환영합니다! 훈이
loggedIn = false;
loggedIn && console.log('환영합니다! ' + username); // 아무것도 출력되지 않음
좌변이 null이나 undefined일 경우에만 우변을 평가.
null 또는 undefined가 아닌 falsy 값들을 유효한 값으로 처리하고 싶을 때 사용.
논리합 연산자의 다른 버전 ..?
let userLocation = null;
console.log(userLocation ?? 'Unknown location');
userLocation = 'Seoul';
console.log(userLocation ?? 'Unknown location'); // 출력: Seoul
// 사용자 입력이 0인 경우에도 0을 유효한 값으로 취급
const temperature = 0;
console.log(temperature ?? 25); // 출력: 0
truthy한 값이냐 아니냐 vs null이나 undefined이냐 아니냐
function displayPreferences(preferences) {
// `||` 연산자 사용 예
const textLength = preferences.textLength || 50; // textLength가 0일 경우 50이 할당됨
console.log(`Text Length: ${textLength}`);
// `??` 연산자 사용 예
const itemsPerPage = preferences.itemsPerPage ?? 10; // itemsPerPage가 null 또는 undefined일 때만 10이 할당됨
console.log(`Items Per Page: ${itemsPerPage}`);
}
// 테스트 케이스
const userPreferences = {
textLength: 0, // 0이 유효한 값이지만 || 연산자로 인해 50이 출력됨
itemsPerPage: null // null 값에 대해 ?? 연산자로 인해 10이 출력됨
};
displayPreferences(userPreferences);