JS

Javascript ES11 문법정리

Kir93 2023. 11. 24. 17:35
728x90
반응형

ES11이라고도 알려진 ECMAScript 2020은 JavaScript 언어에 몇 가지 새로운 기능과 개선 사항을 도입했습니다.

개인적으로 정말 좋아하는 기능들이 생긴 버전이라 기억에 남고 지금도 자주 사용하는 기능들이 많은 버전입니다.

1. Optional Chaining Operator (?.)

선택적 연결 연산자(?.)는 각 수준의 존재를 명시적으로 확인할 필요 없이 객체의 중첩 속성에 액세스 하는 간결한 방법을 제공합니다.

널('null' 또는 '정의되지 않음') 값이 발견되면 평가가 중단됩니다.

// 이전
if (object && object.property && object.property.nestedProperty) {
    const value = object.property.nestedProperty;
} else {
    // not data
}

// ES11
const value = object?.property?.nestedProperty;

 

2. Nullish Coalescing Operator (??)

null 병합 연산자(??)는 변수가 null 또는 undefine인 경우 기본값을 선택하는 방법을 제공합니다.

거짓 값(0, '', false, null, undefine 및 NaN이 아닌 null 값을 구체적으로 확인한다는 점에서 논리적 OR(||) 연산자와 다릅니다. )

// 이전
const someValue = suppliedValue !== null && suppliedValue !== undefined ? suppliedValue : defaultValue;

// ES11
const someValue = suppliedValue ?? defaultValue;

3. Dynamic Import

ES11에서는 동적 가져오기 지원을 도입하여 요청 시 모듈을 비동기식으로 로드할 수 있게 되었습니다.

import() 함수는 모듈의 네임스페이스 객체를 확인하는 프라미스를 반환하여 런타임 조건에 따라 모듈을 가져오는 보다 유연한 방법을 제공합니다.

// 이전
import * as module from './module.js';

// ES11
const module = import('./module.js');

4. BigInt

ES11 이전에는 JavaScript에 매우 큰 정수를 처리하기 위한 내장 유형이 없었습니다. 

이 제한 사항을 해결하기 위해 개발자는 라이브러리를 사용하거나 큰 숫자와 관련된 계산을 처리하기 위한 대체 라이브러리를 찾아야 했습니다.

하지만 ES11에 'BigInt'가 도입되면서 JavaScript는 이제 임의 길이의 정수를 지원하므로 개발자는 언어 내에서 직접 매우 큰 숫자로 작업할 수 있습니다.

const bigNumber = 123456789012345678901234567890n;

5. Promise.allSettled

이전 ECMAScript 버전에서는 'Promise.all' 메서드를 사용하여 개발자가 여러 Promise를 처리할 수 있었지만, Promise가 거부되면 단락 되어 결과에 관계없이 모든 Promise를 처리하려는 경우를 처리하기가 어려워졌습니다.
하지만 ES11은 Promise.allSettled를 도입하여 개발자가 여러 약속을 처리하고 이행 여부에 관계없이 각 약속의 결과나 이유를 개별적으로 검색할 수 있도록 했습니다.

// 이전
const promises = [
  fetch('url1').then(response => response.json()),
  fetch('url2').then(response => response.json()),
  fetch('url3').then(response => response.json())
];

Promise.all(promises)
  .then(results => {
    // All success
  })
  .catch(error => {
    // Even one fails
  });
  
// ES11
const promises = [
  fetch('url1').then(response => response.json()),
  fetch('url2').then(response => response.json()),
  fetch('url3').then(response => response.json())
];

Promise.allSettled(promises)
  .then(results => {
    results.forEach(result => {
      if (result.status === 'fulfilled') {
        console.log('Success:', result.value);
      } else if (result.status === 'rejected') {
        console.log('Failure:', result.reason);
      }
    });
  });

6. String.prototype.matchAll

ES11 이전에는 문자열 내에서 정규식 일치를 처리하면 특히 그룹 및 여러 일치 항목 캡처와 관련하여 제한된 정보가 반환되었습니다.

하지만 ES11에서는 'String.prototype.matchAll'을 도입하여 개발자가 그룹 캡처, 복잡한 정규식 처리 및 문자열 내의 여러 일치 항목 처리를 단순화하는 등 포괄적인 정보가 포함된 모든 일치 항목의 반복자를 얻을 수 있도록 했습니다.

// 이전
const regex = /t(e)(st(\d?))/g;
const str = 'test1test2';

let match;
while ((match = regex.exec(str)) !== null) {
  const fullMatch = match[0];
  const group1 = match[1];
  const group2 = match[2];
}

// ES11
const regex = /t(e)(st(\d?))/g;
const str = 'test1test2';

const matches = [...str.matchAll(regex)];

matches.forEach(match => {
  console.log(`Full match: ${match[0]}, Capturing groups: ${match.slice(1).join(', ')}`);
});

 

반응형