1. String.prototype.matchall

RegExp.prototype.exec()와 매우 유사하게 동작한다.

  • RegExp.prototype.exec()
    • 정규표현식과 첫번째로 일치하는 하위 문자열의 정보를 반환
    • index 속성은 텍스트와 일치하는 첫번째 문자위치
const regExp = /javascript/g;
const text = 'javascript1 is a very good javascript2';
let matches;

while ((matches = regExp.exec(text)) !== null) {
  console.log(matches);
}

  • String.prototype.matchall()
    • 모든 하위 문자열의 정보를 포함하고 있는 iterator를 반환한다.
const result2 = Array.from(text.matchAll(regExp));

console.log(result2);

 

2. Dynamic import

ES11 이전에 modules를 import하기 위해서는 아래와 같이 사용했다.

import * as TestModule from "./test-module.js";

하지만 위와 같이 사용하면 문제점이 있다.

  • 모든 모듈들이 처음 로드될 때 전부다 import가 된다면 프로그램 상에서 효율을 떨어뜨릴 수 있다.
  • 게다가 모듈 이름을 프로그램이 동작할 동안 동적으로 변경하지 못한다.

위 문제를 해결하기 위해 Dynamic import가 등장

const baseModulePath = "./baseModules";
const btnImportModule = document.getElementById("btnImportModule");
let userList = [];

btnImportModule.addEventListener("click", async e => {
  const userModule = await import(`${baseModulePath}/users.js`);
  
  userList = userModule.getUsers();
});

btnImportModule 버튼을 클릭하면 user.js 모듈이 동적으로 로드되고 getUsers() 메서드가 userList 리스트에 추가될 수 있다. 그리고 모듈명을 변수 형식으로 설정하면 모듈명을 동적으로 변경할 수도 있다.

 

import() 구문은 Promise 객체를 반환하기 때문에 async/awaitthen/catch 를 사용해서 비동기 처리를 해야 한다.

 

 

3. BigInt

Number 원시값이 표현할 수 있는 최대치인 2^53 - 1보다 큰 값을 표현하고 싶을 때 사용한다.

BigInt를 사용하려면 정수 리터럴 뒤에 n을 붙이거나, BigInt() 생성자 함수의 인자로 생성할 숫자를 전달합니다.

주의해야 할 점은 BigInt는 Math객체의 메서드와 함께 사용할 수 없고, 연산에서 Number 타입의 원시값과 같이 연산할 수 없습니다.

// 정수 리터럴 방식
const bigInt1 = 9007199254740999n
// 생성자 함수 방식
const bigInt2 = BigInt(9007199254740998)

console.log(bigInt1 > bigInt2) // true
console.log(bigInt1 > bigInt2 + 2n) // false

 

4. Promise.allSettled

Promise.allSettled 메서드는 인자로 받은 배열이나 iterable 객체를 통해 열거된 Promise 객체들이 모두 실행됐을 때 resolve하는 Promise 객체를 반환한다. 

Promise.allSettled 메서드는 Promise.all 메서드와 유사하지만, Promise.all 메서드는 열거된 Promise 객체들 중 하나라도 reject 되면 자신도 reject하지만 Promise.allSettled 메서드는 이행 여부와 상관없이 전부 다 실행되면 resolve한다는 차이가 있습니다.

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

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

 

5. globalThis

globalThis는 어떠한 javascript 실행환경이라도 동일하게 전역객체를 반환한다.

기존의 javascript 환경에서는 실행환경에 따라서 접근하는 방법이 달랐다.

  • 브라우저 환경 -> window, sef, frames를 사용해서 접근,
  • node.js 환경   -> global 를 사용해서 접근,
  • web worker 환경 -> self를 통해 접근

=> 코드가 다양한 실행환경에서 작동하려면 별도의 예외 처리를 해줘야 했는데, 이제 globalThis를 이용하면 별도의 예외 처리를 하지 않고도 손쉽게 전역객체에 접근할 수 있다.

 

6. Optional Chaining (?.)

왼쪽 피연산자 값이 null이나 undefined일 경우 실행을 멈추고 undefined를 반환하는 연산자.

Optional Chaining 연산자를 사용하면, 존재하지 않을 수도 있는 값에 대해 예외 처리를 해야 할 때 손쉽게 처리할 수 있다.

const person1 = {
    name: 'jin',
    job: {
        title: 'singer',
    }
}
const person2 = {
    name: 'jhope'
}

function printJob(person){
    console.log(person.job.title)
}

printJob(person1) # singer
printJob(person2) # Uncaught TypeError: Cannot read properties of undefined (reading 'title')

Optional chaining 연산자 사용 !

function printJob(person){
    console.log(person?.job?.title) # undefined
}

 

7. Nullish coalescing operator ( ?? )

왼쪽 피연산자 값이 null 이나 undefined인 경우에 오른쪽 피연산자를 반환하고 그렇지 않으면 왼쪽 피연산자를 반환하는 연산자이다.

변수에 기본값을 할당할 때 유용해 보인다.

주로 기본값을 할당할 때 || 연산자( A가 false이면 B가 출력됨 )를 사용하는데 0, '' , NaN 같은 falsy 값들을 null이나 undefined를 할당한 것과 동일하게 처리할 수 있기 때문에 예기치 못한 결과가 발생할 수 있다. 

nullish coalescing 연산자를 사용하면 정확하게 null 이나 undefined인 경우에만 기본값을 할당해주기 때문에 좀 더 안전하게 코드작성가능합니다.


const data = {
  title: 'foo',
  count: 0
}

const description3 = data.count || 100    -> 100
// 0을 할당했지만 0을 falsy한 값으로 취급했기 때문에 null이나 undefined를 할당한 것과 동일하게 처리

const description1 = data.count ?? 100    -> 0
// data.count가 정확하게 null이나 undefined일 경우에만 100이 됩니다. 
// 예시에선 0이라는 값이 할당됐기 때문에 0이 출력된다

const description2 =
  data.count == undefined && data.count == null ? 100 : data.count  -> 0
// 위와 동일한 동작을 함

 

 

참고, 출처:

https://segmentfault.com/a/1190000040438879/en

https://john015.netlify.app/what-is-new-in-es-11

https://zerq.tistory.com/92

https://intrepidgeeks.com/tutorial/regular-expression-correlation-method

'엘리스 ai 트랙 > FE' 카테고리의 다른 글

this [모던 js 딥다이브]  (0) 2022.09.22
CI와 CD  (0) 2022.03.31
http 1.1 과 http 2 의 차이점  (0) 2022.03.31
HTTP  (0) 2022.03.13
기본값+rest+spread  (0) 2022.03.07

+ Recent posts