본문 바로가기
JavaScript

[Javascript] ES11 의 유용한 문법

by 쁘니쁘나 2021. 8. 6.

✨ Javascript ES11의 유용한 문법

ECMAScript 2020 버전인 ES11 중에 내가 이해한 것들 두 가지만 정리를 우선 해보려 한다.

Optional Chaining과 Nullish Coalescing Operator에 대해 알아보자.

 

✨ Optional Chaining

{
  const person1 = {
    name: "Wendy",
    job: {
      title: "S/W Engineer",
      manager: {
        name: "Bob",
      },
    },
  };
  const person2 = {
    name: "Bob",
  };

  // Bad Code
  {
    function printManager(person) {
      console.log(person.job.manager.name);
    }
    printManager(person1); // Bob
    printManager(person2); // Error
  }

  // Bad Code
  {
    function printManager(person) {
      console.log(
        person.job
          ? person.job.manager
            ? person.job.manager.name
            : undefined
          : undefined
      );
    }
    printManager(person1); // Bob
    printManager(person2); // undefined
  }

  // Bad Code
  {
    function printManager(person) {
      console.log(person.job && person.job.manager && person.job.manager.name);
    }
    printManager(person1); // Bob
    printManager(person2); // undefined
  }

  // ✨ Optional Chaining
  {
    function printManager(person) {
      console.log(person.job?.manager?.name);
    }
    printManager(person1); // Bob
    printManager(person2); // undefined
  }
}

 

위의 코드는 Optional Chaining의 예를 보여준 것이다.

Bad Code라고 적혀있는 곳은 Optional Chaining을 사용하기 전 우리가 사용해오던 방식들이다.

 

하지만 ✨ Optional Chaining이라고 된 맨 마지막 부분을 보면, ?와 . 을 사용해서 간결하게 나타낸 것을 볼 수 있다.

 

person.job? 👉🏻 person객체에 job이 있니? 있으면 그다음 진행, 없으면 undefined 출력.

person.job?.manager? 👉🏻 person 객체에 job이 있으며, job 객체에 manager 가 있니? 있으면 그다음 진행, 없으면 undefined 출력.

person.job?.manager?.name 👉🏻 person 객체에 job이 있고, job 객체 내부에 manager가 있으며 manager 객체 내부에 name이 있으면 Bob 반환, 없으면 undefined 출력.

 

이렇게 Optional Chaining 문법을 사용하면 얼마나 코드가 간편해지는지 알 수 있다.

 

 

✨ Nullish Coalesching Operator

Nullish Coalesching Operator를 들어가기전에 javascript 에서 false는 어떤 것이 있는지 알아야 한다.

javascript 에서 false는 아래의 5가지를 false로 본다.

 

false, 0, '', null, undefined

 

 

그럼 이제 코드를 보며 이해해보자.

 

{
  const name = "Wendy";
  const userName = name || "Guest";
  console.log(userName); // Wendy
}

{
  const name = null;
  const userName = name || "Guest";
  console.log(userName); // Guest
}

 

위의 코드에서는 Nullish Coalescing Operator 를 사용하지 않아도 문제가 없다.

그냥 위에서 처럼 || 을 사용하여 앞이 true면 해당 값을 출력하고, 아니라면 뒤의 Guest를 출력하면 된다.

 

  // Bad Code
  {
    const name = "";
    const userName = name || "Guest";
    console.log(userName); // Guest

    const num = 0;
    const message = num || "Guest";
    console.log(message); // Guest
  }

 

문제는 위의 코드에서 시작된다.

위의 코드처럼 "" or 0 이 들어가 있다면 javascript에서는 false로 보기 때문에 빈 값이 출력되지 않고, Guest가 출력되게 된다.

 

만약 "" 빈 값을 출력하고 싶거나, 0을 출력해야 한다면 아래의 코드처럼 Nullish Coalescing Operator를 사용해야 한다.

 

  // ✨ Nullish Coalescing Operator
  {
    const name = "";
    const userName = name ?? "Guest";
    console.log(userName); // 

    const num = 0;
    const message = num ?? "undefined";
    console.log(message); // 0
  }

 

위와 같이 Nullish Coalescing Operator는?? 물음표 두 개로 나타내는 문법이다.

 

Nullish Coalescing Operator를 사용하면 위와 같이 "" 빈 값이나 0을 출력하고 싶을 때 javascript 에서 false로 인식하지 않고 "", 0 이 그대로 출력되게 된다.

 

 

 

 

 

 

댓글