Nullish 병합 및 선택적 연결 연산자

11285 단어 javascript
ECMAScript 2020은 많은 흥미로운 기능을 출시했으며 이 게시물에서는 제가 정말 좋아하는 두 가지 새로운 기능인 nullish coalescing operator와 optional chaining operator에 대해 이야기하고 싶습니다.

Nullish 병합 연산자

Quoting from the MDN 문서, 그것은

a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.



이중 물음표??로 표시됩니다. 다음은 예입니다.

undefined ?? 'Web design'; // Web design
null ?? 'Mansion'; // Mansion


이 예에서는 왼쪽이 null이거나 정의되지 않았기 때문에 오른쪽 값이 반환됩니다. 그러나 왼쪽 피연산자에 값이 있는 경우(다음 예제와 같이) 왼쪽 값이 반환됩니다.

'JavaScript Data Structures' ?? 'Web design'; // JavaScript Data Structures


||와 어떻게 다릅니까? 운영자

Unlike the OR operator, the nullish coalescing operator only looks for null or undefined values. If the value is a falsey value (besides null and undefined), the nullish coalescing operator will return the falsey value.

Here are the falsey values in JavaScript.

  • false
  • null
  • undefined
  • 0
  • ''
  • NaN
0 ?? 15; // 0
false ?? true; // false
'' ?? 'banana'; // ""

So when do you use the null coalescing operator over the OR operator? Here is a simple guideline on what to use. If you want to filter out falsey values, then you should probably use the OR operator. But if falsey values are valid default values to you, then you should probably use the nullish coalescing operator.

nullish 병합 연산자 연결

It is cool that you can actually chain the nullish coalescing operator, so this is completely valid.

null ?? undefined ?? 0 ?? 'nice'; // 0
null ?? '' ?? 'great'; // ''

You cannot, however, combine it with && or || operators. This will throw a Syntax error.

null || undefined ?? 'not working'

But if you wrap the || expression with a parethesis, it will work.

(null || undefined) ?? 'working';

선택적 연결

This is my favorite new feature in ECMAScript 2020. Have you ever encountered a code like this?

const person = {
  address: {},
};

if (person.address && person.address.position && person.address.position.latitude) {
  // do something
}

Before accessing the latitude property, you first have to do a series of checks to make sure it actually exists, otherwise you will get an error Cannot read property 'latitude' of undefined . I frequently encounter code like this, and it can sometimes be pretty annoying.

Here is where optional chaining shines. We can check if the property exists by just using ?. after the property of an object. Let's refactor the code above.

if (person.address?.position?.latitude) {
  // do something
}

Now it is much shorter and cleaner. The optional chaining operator will check for us if the property exists. If the property doesn't exist it will just return undefined and not throw an error.

You can also use optional chaining with arrays and functions. Suppose you have an array of objects like this.

const persons = [
  {
    name: 'Peter',
  },
  {
    name: 'Jessica',
  },
];

If you try to access 3rd person name (which doesn't exist), it will throw an error.

persons[2].name; // Cannot read property 'name' of undefined

But if you use the optional chaining operator, it will just return undefined.

persons[2]?.name; // undefined

The same with functions (returns undefined if it doesn't exist)

persons[2]?.name.toLowerCase(); // undefined

nullish 병합 연산자와 선택적 연결 결합

Because the optional chaining operator returns undefined if a property doesn't exit, we could use it together with the nullish coalescing operator to set default values.

const person = {
  address: {},
};

console.log(person?.address?.position ?? 'No address defined.'); // No address defined

결론

JavaScript has immensely improved since ECMAScript 2015 and a lot of new features are being added to the language every year. It is no longer just a language you use for simple animations in the browser 😉

We have seen how to use the nullish coalescing and optional chaining operator. In summary, you can use the nullish coalescing operator if you want your default values to include falsey values. And if you are not sure whether an object has a certain property before accessing it, you can use the optional chaining operator to avoid a long series of check and Cannot read property error.

Thanks for reading! If this has helped you, kindly please share 😎

좋은 웹페이지 즐겨찾기