728x90

ES6와 비교하여 ECAM Script 2020(ES11)에서 새로 생긴 문법은 다음과같다.

  1. BigInt
  2. Import
  3. Promise.allSettled( )
  4. globalThis
  5. Nullish Coalescing Operator
  6. Optional Chaing Operator

BigInt

ES6에서 int 의 범위는 +/- 2^53 - 1(=9007199254740991) 이었다.

※ 9007199254740992까지 출력이 가능하지만 9007199254740992나 9007199254740993이나 9007199254740992로 출력되기때문에 reliable 하지않아 제외.

ES11에서 새로운 Number표현법인 BigInt가 도입됨에 따라 숫자의 max min의 제한이 사라지게 되었다.

사용법은 숫자뒤에 n을 붙이거나 BigInt로 숫자또는 숫자문자열을 감싸면 된다.

Number에서 사용할 수 있던 연산자(+,-,*./,||,&&...)를 똑같이 사용할 수 있다.

See the Pen ES11 - BigInt by zakelstorm (@zakelstorm) on CodePen.

BigInt가 가지는 Number와의 차이점은 다음과 같다.

  • Math object의 함수와 사용될 수 없다.

    • Cannot convert a BigInt value to a number
  • Nubmer와 연산에 함께 사용될 수 없다. 사용하기위해서는 Number를 BigInt로 (또는 BigInt를 Number로) 캐스팅 해야한다.

    • Cannot mix BigInt and other types, use explicit conversions

Import

ES11부터 import는 promise를 return 한다. 따라서 async/await 로 함수 내부 코드의 동기 처리가 가능하다.

const helpModule = './helper.js';
import(helpModule).then((module)=>{
  module.doStuff1();
  module.doStuff2();
})

(aysnc function importCheck(){
  const helpModule = './helper.js'
  const module = await import(helpModule);
  module.doStuff1();
  module.doStuff2();
}) 

Promise.allSettled( )

promise.all 의 단점을 보완하기 위해 만들어진 Promise 함수.
기존 promise.all은 단 하나의 request라도 error 발생 시 그 뒤의 request를 기다리지 않고 다음 catch phrase를 시행하는 문제가 있었다.
이로 인해 어떤 request가 성공하고 실패했는지 알 수 없었고 마지막 request의 response를 기다린 후 시행되어야 할 코드를 만들기 어려웠다.(가능은 하다...)
promise.allSettled는 모든 request가 response를 받을때까지 기다린 후 다음 then phrase를 시행하도록한다.

이때 response에 error가 있더라도 then으로 가게되어 catch구문이 사실상 필요가 없게된다.

See the Pen ES11 - Promise.allSettled( ) by zakelstorm (@zakelstorm) on CodePen.


globalThis

window ,self, global 의 기능을 하는 변수이다.

Window {parent: Window, postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, …}

다른 점은 window는 browser에서 사용.

selfwebworker에서 사용.

global은 node.js에서 사용.한다는 점이다.

이러한 각각의 환경에대한 특수성 때문에 이를 한 변수로 통일하고자 globalThis라는 변수를 ES11부터 사용할 수 있게 되었다.


Optional Chaining Operator (?.)

ES6까지는 undefined variable object의 key값 참조 시 발생하던 에러 때문에 Ternary Operator 또는 if 구문으로 예외상황에 대해 항상 준비해야했다.

ES11부터 이 예외상황에 대한 준비를 보다 간소하게 하기위해 operator를 만들었는데 이를 Optional Chaning Operator라고 한다.

Optional Chaning Operator가 존재함에 따라 variable object의 key값을 참조시 해당 변수가 undefined 라면 false를 return하게 된다.

const person1={ // nested Object
    name:'Ellie`,
    job:{
        title:`S/W Engineer`,
        manager:{
            name:'Bob',
        }
    }
}

const person2={
    name:'Bob',
};

function printManager(person){
    console.log(person.job.manager.name);
}
console.log(person1); //OK
console.log(person2); //ERROR. resolve with ternary Optional or if phrase

function printManagerES11(person){
    console.log(person.job?.manager?.name);
}

Nullish Coalescing Operator (??)

ES6 까지는 Boolean의 false, Object의 null,undefined, String의 '', Number의 0 은 모두 false로 인식되었다. 여기서 DB에서 참조했을 뿐인데 empty string이나 0 nubmer를 false로 규정하는 문제때문에 이 경우 true를 return 하도록 예외상황을 구분하는 코드를 작성해야했다.

ES11 부터는 이를 간소화 하고자 operator를 만들었는데 이를 Nullish Coalescing Operator라고 한다.

Nullish Coalescing Operator은

empty string과 0 number의 경우 true를 return 하도록 하고,

false,null,undefined의 경우에만 false를 returng하도록 한다.

//Logical OR operator  
// false: false, '' , 0, null , undefined  
const name='Ellie';  
const userName = name || 'Guest';  
console.log(userName);

const name = null;  
const userName = name || 'Guest';  
console.log(userName);

//문제가 생기게되는데 문자열이 비어있는 경우에도('') 아무런 이름쓰고싶지않은데 Guest 출력  
// false의 조건을 좀더 까다롭게 해주자 오직 false null undefined만 false로 인식

cosnt name = '';  
const userName = name ?? 'Guest';  
console.log(userName); //''

const num = 0;  
const message = num ?? 'undefined';  
console.log(message); //0

'Javascript' 카테고리의 다른 글

prototype  (0) 2021.02.14
var vs let (const)  (0) 2021.01.13
비동기 처리 - async/await  (0) 2020.12.27
비동기 처리 - Promise  (0) 2020.12.20
동기/비동기 처리 - Callback, Callback 지옥  (0) 2020.12.20

+ Recent posts