간결한 함수의 경우 return문을 따로 명시하지 않아도 처리 / multi-line은 중괄호와 return문 반드시 명시
const add = (a, b) => a + b;
console.log(add(1, 3)); // 4
const score = 85;
const grade = score > 70 ? '합격' : '불합격';
console.log(grade); // '합격'
falsy 값 : false, 0, "", null, undefined, NaN
||는 좌변의 피연산자가 truthy 값일 경우, 그 값이 바로 결과값으로 반환된다. 우변은 평가되지 않는다.
function getUsername(user) {
return user.name || '신원미상'; //좌변이 falsy한 값이면 우변을 반환
}
console.log(getUsername({ name: '르탄이' })); //르탄이
console.log(getUsername({})); //신원미상
&&는 좌변이 truthy일 때만 우변을 평가한다.
let loggedIn = true;
let username = '르탄이';
loggedIn && console.log('환영합니다! ' + username); //환영합니다! 르탄이
loggedIn = false;
loggedIn && console.log('환영합니다! ' + username); //아무것도 출력되지 않음
객체의 속성에 접근할 때 해당 경로에 속성이 존재하지 않아도 에러를 발생시키지 않고, 대신 undefined를 반환. 메소드 호출에도 사용 가능.
const user = {
profile1: {
name: "르탄이",
details: {
age: 30,
location: "서울시 강남구"
}
}
};
console.log(user.profile?.details.age); // 출력: undefined
const result = user.profile1.getDetails?.(); // user.profile.getDetails가 존재하지 않으면 undefined 반환
논리합 연산자와 유사하지만 null 혹은 undefined인 경우에만 해당. 즉, 좌변이 null 혹은 undefined인 경우 우변을 평가.
let userLocation = null;
console.log(userLocation ?? 'Unknown location'); // 출력: Unknown location
userLocation = 'Seoul';
console.log(userLocation ?? 'Unknown location'); // 출력: Seoul
// 사용자 입력이 0인 경우에도 0을 유효한 값으로 취급
const temperature = 0;
console.log(temperature ?? 25); // 출력: 0