ES6 이후의 이야기 (2)

ChangHyeon Bae·2023년 1월 20일
0

JavaScript

목록 보기
7/8
post-thumbnail

지난 포스팅에서는 2016 ~ 2019에 나온 새로운 메서드들에 대해서 알아봤다.
이어서 2020 ~ 2021에 나온 메서드, 새로운 개념에 대해 한번 알아보자

⭐️ ES2020

💡 BigInt

  • BigIntNumber 원시 값이 안정적으로 나타낼 수 있는 최대치인 2^53 - 1 보다 큰 정수를 표현할 수 있는 내장 객체이다.
  • BigInt는 정수 리터럴의 뒤에 n 을 붙이거나 (10n) 함수 BigInt()를 호출해 생성 할 수 있다.
const theBiggestInt = 9007199254740991n;

const alsoHuge = BigInt(9007199254740991);
// ↪ 9007199254740991n

const hugeString = BigInt("9007199254740991");
// ↪ 9007199254740991n

const hugeHex = BigInt("0x1fffffffffffff");
// ↪ 9007199254740991n

const hugeBin = BigInt("0b11111111111111111111111111111111111111111111111111111");
// ↪ 9007199254740991n
  • BigIntNumber 차이점
    - BigInt는 내장 Math객체의 메서드와 함께 사용할 수 없다.
    - 연산에서 Number와 혼합해 사용할 수 없다.
    • 따라서, 먼저 같은 자료형으로 변환해야 한다.
    • BigInt에서 Number로 변환시 정확성을 잃을 수 있으니 주의하자

💡 Dynamic import

  • ES 2020부터는 필요할 때 모듈을 동적으로 가져올 수 있다.
  • 가져오는 모듈은 use strict의 존재유무와 상관없이 무조건 엄격모드
  • HTML 안에 작성한 스크립트에서는 import 사용이 안된다.
    import defaultExport from "module-name";
    import * as name from "module-name";
    import { export1 } from "module-name";
    import { export1 as alias1 } from "module-name";
    import { export1 , export2 } from "module-name";
    import { foo , bar } from "module-name/path/to/specific/un-exported/file";
    import { export1 , export2 as alias2 , [...] } from "module-name";
    import defaultExport, { export1 [ , [...] ] } from "module-name";
    import defaultExport, * as name from "module-name";
    import "module-name";
    var promise = import("module-name");

💡 옵셔널 체이닝

  • optional chaining 연산자 (?.) 는 체인의 각 참조가 유효한지 명시적으로 검증하지 않고, 연결된 객체 체인 내에 깊숙이 위치한 속성 값을 읽을 수 있다.
  • . 체이닝 연산자와 유사하게 작동하지만, 참조가 null 또는 undefined 인 경우에 에러가 발생하는 대신에 표현식의 리턴값은 undefined로 단락된다.
  • 함수 호출에서 사용될 때, 만약 주어진 함수가 존재하지 않는다면, undefined를 리턴한다.
  • 선언된지 않은 루트 객체에 사용할 수 없지만, 정의되지 않은 루트객체와는 함께 사용할 수 있다.
const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

const dogName = adventurer.dog?.name;
console.log(dogName); // undefined

console.log(adventurer.someNonExistentMethod?.()); // undefined

💡 Promise.allSettled()

  • 주어진 모든 프로미스를 이행하거나 거부한 후, 각 프로미스에 대한 결과를 나타내는 객체 배열을 반환한다.
  • 일반적으로 서로의 성공여부에 관련없는 여러 비동기 작업을 수행해야 하거나, 항상 각 프로미스의 실행 결과를 알고 싶을 때 사용한다.
  • 하지만, Promise.all()이 반환하는 프로미스는 서로 연관된 작업을 수행 하거나, 하나라도 거부 당했을 때 즉시 거부하고싶을 때 적합하다.
const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'));
const promises = [promise1, promise2];

Promise.allSettled(promises).
  then((results) => results.forEach((result) => console.log(result.status))); 
// "fulfilled"
// "rejected"

// Promise.prototye.then()
Promise.allSettled([
  Promise.resolve(33),
  new Promise(resolve => setTimeout(() => resolve(66), 0)),
  99,
  Promise.reject(new Error('an error'))
])
.then(values => console.log(values));

// [
//   {status: "fulfilled", value: 33},
//   {status: "fulfilled", value: 66},
//   {status: "fulfilled", value: 99},
//   {status: "rejected",  reason: Error: an error}
// ]

💡 Null coalescing operator(null 병합 연산자)

  • 널 병합 연산자 (??)는 왼쪽 피연산자가 null 또는 undefined일때, 오른쪽 피연산자를 반환하고, 그렇지 않으면 왼쪽 피연산자를 반환하는 논리 연산자 이다.
  • 논리연산자 OR (||)와는 대조 된다.
  • 널 병합 연산자는 연산자 우선 순위가 다섯번째로, ||의 바로 아래이고, 삼항 연산자의 바로 위다.
const foo = null ?? 'default string';
console.log(foo); // "default string"

const baz = 0 ?? 42;
console.log(baz); // 0

💡 String.prototype.matchAll()

  • 지정된 정규식에 대해 문자열과 일치하는 모든 결과의 iterator 를 반환하는 메서드이다. (캡처링 그룹 포함)
const regexp = /t(e)(st(\d?))/g;
const str = 'test1test2';

const array = [...str.matchAll(regexp)];

console.log(array[0]);
// Expected output: Array ["test1", "e", "st1", "1"]

console.log(array[1]);
// Expected output: Array ["test2", "e", "st2", "2"]

💡 모듈 네임스페이스 export 문법

  • 아래와 같이 선언할 수 있다.
export * as stuff from './test.mjs';

// 아래의 코드와 동일한 역할을 수행한다
export { stuff };

💡 import.meta

  • import.meta 객체는 URL등 모듈에 대한 정보를 노출한다.

<script type="module" src="my-module.js">
console.log(import.meta);
{
  url: "file:///home/user/my-module.js"
}

아래와 같은 응용이 가능합니다.

<script type="module">
  import "./index.mjs?someURLInfo=5";
</script>
// index.mjs1
new URL(import.meta.url).searchParams.get('someURLInfo')' //5

💡 globalThis

  • ES2020 전에는 전역 객체에 접근하는 표준화된 방식이 없었다.
  • 브라우저에서는 window, nodw 에서는 global, 웹 워커의 경우 self등을 사용해 전역 객체에 접근했다.
  • ES2020부터는 어떤 환경에서든 항상 전역 객체를 참조하는 globalThis를 사용 할 수 있다.

⭐️ ES2021

💡 String.prototype.replaceAll()

  • 기존의 replace()메서드는 문자열의 패턴을 다른것으로 바꿀 수 있는 메서드였지만, 정규식을 쓰지 않으면 일치하는 첫 번째 항목만 변경이 가능했습니다.
  • replaceAll() 메서드는 단순 문자열 패턴을 대체할 때도 일치하는 모든 문자열을 교체합니다.
const str = "I like my dog, my dog is very cute."
const newStr = str.replaceAll('dog', 'cat');

console.log(newStr); // I like my cat, my cat is very cute

💡 Promise.any()

  • 주어진 Promise 중 하나라도 성공하면 실행을 완료하지만, 그렇지 않다면 모든 Promise가 실패할 때까지 계속됩니다.
  • Promise.race()는 하나라도 성공 혹은 실패할 시에 종료되는 것과 차이가 있습니다.
const promise1 = Promise.reject(0);
const promise2 = new Promise((resolve, reject) => setTimeout(resolve, 100, 'quick'));
const promise3 = new Promise((resolve, reject) => setTimeout(resolve, 500, 'slow'));

const promise4 = new Promise((resolve, reject) => setTimeout(reject, 100, 'quick'));
const promise5 = new Promise((resolve, reject) => setTimeout(reject, 500, 'slow'));

const promises1 = [promise1, promise2, promise3]
const promises2 = [promise1, promise4, promise5];

Promise.any(promises1).then((value) => console.log(value)).catch(err => console.log(err)); // 'quick'


Promise.any(promises2).then((value) => console.log(value)).catch(err => console.log(err)); // AggregateError: All promises were rejected

💡 논리 연산자와 할당 표현식

  • 논리 연산자와 할당 표현식을 결합할 수 있습니다.
const a = { duration: 50, title: ''};

a.duration ??= 10;
console.log(a.duration);// 50

a.speed ??= 25;
console.log(a.speed);// 25

a.duration &&= 60;
console.log(a.duration);// 60

a.title ||= 'Logical or Assignment'
console.log(a.title);// 'Logical or Assignment'

💡 숫자 구분 기호

  • ES2021에는 숫자 구분 기호가 도입되었습니다.
  • 큰 자릿수 숫자를 구분하는데에 언더바를 사용하여 쉽게 표시할 수 있게 되었습니다.
const x = 100_000;
console.log(x); // 100000

💡 WeakRef

  • WeakRef를 통해 특정 객체에 일반 참조가 없으면 약한 참조가 남아있어도 가비지 콜렉터가 해당 객체를 메모리에서 제거한다고 합니다.

💡 Intl.ListFormat

  • 각종 언어 별로 목록 서식을 활성화하는 객체의 생성자 입니다.
const list = ['Apple', 'Orange', 'Banana'];

console.log(new Intl.ListFormat('ko', {style:'long', type: 'conjunction'}).format(list));// 'Apple, Orange 및 Banana'

console.log(new Intl.ListFormat('ko', {style:'long', type: 'disjunction'}).format(list)); // 'Apple, Orange 또는 Banana'

console.log(new Intl.ListFormat('en', {style:'long', type: 'conjunction'}).format(list)); // 'Apple, Orange, and Banana'

console.log(new Intl.ListFormat('en', {style:'long', type: 'disjunction'}).format(list)); // 'Apple, Orange, or Banana'

💡 Intl.DateTimeFormat, dateStyle 및 timeStyle

new Intl.DateTimeFormat("ko", {dateStyle: "short"}).format(Date.now());
// '21. 6. 21.'
new Intl.DateTimeFormat("ko", {dateStyle: "medium"}).format(Date.now());
// '2021. 6. 21.'
new Intl.DateTimeFormat("ko", {dateStyle: "long"}).format(Date.now());
// "2021년 6월 21일"

new Intl.DateTimeFormat("en", {dateStyle: "short"}).format(Date.now());
// '6/21/21'
new Intl.DateTimeFormat("en", {dateStyle: "medium"}).format(Date.now());
// 'Jun 21, 2021'
new Intl.DateTimeFormat("en", {dateStyle: "long"}).format(Date.now());
// "June 21, 2021"
new Intl.DateTimeFormat("en", {timeStyle:"short"}).format(Date.now());
// 1:11 PM
new Intl.DateTimeFormat("en", {timeStyle:"medium"}).format(Date.now());
// 1:11:50 PM
new Intl.DateTimeFormat("en", {timeStyle:"long"}).format(Date.now());
// "1:11:50 PM GMT+9"

new Intl.DateTimeFormat("ko", {timeStyle:"short"}).format(Date.now());
// 오후 1:12
new Intl.DateTimeFormat("ko", {timeStyle:"medium"}).format(Date.now());
// 오후 1:12:24
new Intl.DateTimeFormat("ko", {timeStyle:"long"}).format(Date.now());
// "오후 1시 12분 24초 GMT+9"

🚀 느낀점

이렇게 각 메서드들에 대해서 정리를 하면서 내가 자주 쓰는 메서드들도 있었고, 이번에 정리를 하면서 새롭게 알게된 메서스드들도 많이 있었던거 같습니다. 다 이해하기 보다는 어느 시점에 어떤 메서드와 개념이 나오는지에 대해서 감만 잡았고, 이런게 있었다라는 정도만 해서 넘어가면 될거 같습니다.

🔗 참고

정확하지 않은 정보가 있을 수 있습니다. 댓글을 통해 피드백 주시면 적극적으로 반영하겠습니다🥲

profile
모든 결과는 내가 하기 나름이다 🔥

0개의 댓글