[JS] 단축평가 (||, &&, ?., ??)

논리합연산자 ( || )

논리합 연산자를 활용해 기본값을 설정할 수 있다.

if-else 혹은 삼항연산자 등을 활용하는 경우를 훨씬 간단하게 표현할 수 있다는 것!

const person = {
  age: 30,
};

const getUserName = (user) => {
  return user.name || "신원미상";
};

const getUserName2 = (user) => {
  if(!user.name) return "신원미상";
  else return user.name;
};

 

 

논리곱연산자 ( && )

특정 조건이 성립할 때 수행할 내용을 지정해줄 수 있다.

const loggedIn = true;
const userName = "르탄이";

loggedIn && console.log(`환영합니다. ${userName}님`);

 

 

Optional chaining

존재하지 않을수도 있는 값이나 메서드에 접근할 때 사용할 수 있다.

 

const user = {
  name: 'Kim',
  details: {
    age: 30,
  },
};

console.log(user.profile?.details.age);

.를 사용한 경우 user.profile이 존재하지 않아 undefined를 참조할 수 없다는 오류가 나는데, ?.를 사용하는 경우 해당 값이 존재하지 않으므로 undefined를 반환한다.

 

const user = { name: 'Kim', age: 30 };

user.printHello?.();

존재하지 않을수도 있는 메서드에 접근할 때 오류를 방지하기 위해서는 호출부분 앞에 ?.를 붙여주면 된다.

마찬가지로 undefined를 반환한다.

 

const result = user.printHello?.();
console.log(result);  // undefined

 

 

null 병합 연산자 ( ?? )

좌항이 null 일 때만 우항을 평가하고 싶은 경우

let userLocation = null;

console.log(userLocation ? userLocation : "없는위치");  // 없는위치

이렇게도 가능하지만 ??를 사용하는 경우 굳이 동일한 값인 userLocation을 두번 쓸 필요가 없어진다.

 

let userLocation = null;
console.log(userLocation ?? "없는위치");  // 없는위치

userLocation이 null이 아닌 경우 해당 값을, null인 경우 없는위치를 반환

 

논리합연산자와의 차이

null 병합 연산자는 좌변이 null, undefined일때만 우변을 평가하고 나머지 falsy한 값들에 대해서는 평가하지 않는다.