지난 포스팅에서는 2016 ~ 2019에 나온 새로운 메서드들에 대해서 알아봤다.
이어서 2020 ~ 2021에 나온 메서드, 새로운 개념에 대해 한번 알아보자
BigInt
는 Number
원시 값이 안정적으로 나타낼 수 있는 최대치인 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
BigInt
와 Number
차이점BigInt
는 내장 Math
객체의 메서드와 함께 사용할 수 없다.Number
와 혼합해 사용할 수 없다.BigInt
에서 Number
로 변환시 정확성을 잃을 수 있으니 주의하자use strict
의 존재유무와 상관없이 무조건 엄격모드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.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
또는 undefined
일때, 오른쪽 피연산자를 반환하고, 그렇지 않으면 왼쪽 피연산자를 반환하는 논리 연산자 이다.(||)
와는 대조 된다.||
의 바로 아래이고, 삼항 연산자
의 바로 위다.const foo = null ?? 'default string';
console.log(foo); // "default string"
const baz = 0 ?? 42;
console.log(baz); // 0
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 * as stuff from './test.mjs';
// 아래의 코드와 동일한 역할을 수행한다
export { stuff };
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
를 사용 할 수 있다.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.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'
const x = 100_000;
console.log(x); // 100000
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'
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"
이렇게 각 메서드들에 대해서 정리를 하면서 내가 자주 쓰는 메서드들도 있었고, 이번에 정리를 하면서 새롭게 알게된 메서스드들도 많이 있었던거 같습니다. 다 이해하기 보다는 어느 시점에 어떤 메서드와 개념이 나오는지에 대해서 감만 잡았고, 이런게 있었다라는 정도만 해서 넘어가면 될거 같습니다.
정확하지 않은 정보가 있을 수 있습니다. 댓글을 통해 피드백 주시면 적극적으로 반영하겠습니다🥲