-
[Javascript] ES12 ES2021?Front-end/Javascript 2020. 12. 8. 00:08반응형
Preface
Taran의 codeburst 포스팅 공유를 위한 번역 겸... 겸사겸사 쓰게 되었다.
잠깐의 미국에서 외국인 노동자 생활을 했으나, 전문가들처럼 번역이 매끄럽지 않을 수 있음에 양해를 부탁드립니다. 🙏
++ 직역이 어색한 경우, 그대로 영어 단어로 썼습니다.
codeburst.io/exciting-features-of-javascript-es2021-es12-1de8adf6550b
JavaScript ES2021 Exciting Features
Looking at the top new features of ECMAScript 2021 (ES12)
codeburst.io
Javascript 그리고 ES{{n}}
ES{{n}}을 보고 풉 했다면, 그렇다 당신도... Geeky 한 사람이거나 Nerd일 가능성이 높다.
개인적인 생각으론 Javscript의 기능 추가들로 인해서 "웹 프론트" 포지션이 핫해지기 시작한듯하다.
매년, Javascript는 새로운 기능들을 추가한다. 올해 ES2020(ES11)이 출시되었고, ES2021(ES12)가 2021 중순에 출시될 예정이다.
매년 Javascript에 추가되는 새로운 기능들은 4 단계 프로세스를 거치고, 물론 4 단계가 마지막이다. 이 포스팅에서는, 이미 4 단계에 와서 Google Chrome V8 엔진에 추가된 기능에 대해 다루어보고자 한다.
추가될 새 기능들
- String.prototype.replaceAll
- Promise.any
- Logical Operators and Assignment Expressions
- Numeric Separators
- Intl.ListFormat
- dateStyle and timeStyle options for Intl.DateTimeFormat
String.prototype.replaceAll
Javascript에서 replace() 메서드는 문자열에서 패턴에 맞는 첫 번째 인스턴스(매칭)만 대체한다. 문자열 내에서 패턴에 매칭 하는 모든 항목을 바꾸려면 global 정규표현식을 사용하는 방법뿐이다. 너무나도 당연하게 regex를 써왔지만, 지금 생각해보니 왜 없었나 싶기도 하다.
그래서 es2021에서 제안하는 replaceAll() 메서드는 패턴의 모든 매칭들이 교체되어 새 문자열을 반환한다. 인풋으로 들어가는 패턴은 string(문자열) 또는 정규식 일 수 있고, replace 인자는 각 매칭이 실행되는 string 또는 funciton일 수 있다.
-- 예시 --
let str = 'I use linux, I love linux' str = str.replaceAll('linux', 'windows') console.log(str) /**** Output ****/ // I use windows, I love widnows
Promise.any
두 번째로, Promise 배열 첫 번째로 resolve가 되자마자, 값을 반환하고 끝내는 Promise.any()도 도입된다.(Example 1a). 만약에 모든 promise가 거절되면, 합쳐진 에러 메세지를 표시한다. (Example 1b)
Promise List Item 중 하나가 resolve 되거나 reject 되면 끝나기 때문에, Promise.race()와는 차이점이 있다.
Example 1a: resolve promise보다 빨리 reject 되어도, Promise.any()가 첫 번째로 resolved promise를 리턴하는 경우
Promise.any([ new Promise((resolve, reject) => setTimeout(reject, 200, 'Third')), new Promise((resolve, reject) => setTimeout(resolve, 1000, 'Second')), new Promise((resolve, reject) => setTimeout(resolve, 2000, 'First')), ]) .then(value => console.log(`Result: ${value}`)) .catch (err => console.log(err)) /**** Output ****/ // Result: Second
Example 1b: 모든 promised가 reject 됐을 때, 합쳐진 error가 나온 경우
Promise.any([ Promise.reject('Error 1'), Promise.reject('Error 2'), Promise.reject('Error 3') ]) .then(value => console.log(`Result: ${value}`)) .catch (err => console.log(err)) /**** Output ****/ // AggregateError: All promises were rejected
Logical Operators and Assignment Expressions
아래 예시처럼 Javascript에는 우리가 흔히 써왔던 많은 할당 연산자(Assignment operator)와 논리 연산자(Logical Operator)가 있다.
// Assignment Operator Example let num = 5 num+=10 console.log(num) // 15 // Logical Operator Example let num1 = 6 let num2 = 3 console.log(num1 === 6 && num2 === 2) // false console.log(num1 === 6 || num2 === 2) // true
아래 예제에서 확인할 수 있듯이, 이제 우리는 할당 연산자와 논리 연산자를 합칠 수 있다.
Logical Assignment Operator with && operator
&& 연산자와 선언을 함께 할 수 있다!
왼쪽의(LHS)의 값이 어떤 값을 갖고 있을 경우(not undefined)에 오른쪽(RHS-Right Hand Side)의 값이 왼쪽 값에 할당된다.
// Logical Assignment Operator with && operator let num1 = 5 let num2 = 10 num1 &&= num2 console.log(num1) // 10 // "num1 &&= num2"는 아래처럼 사용할 수도 있다. // 1. num1 && (num1 = num2) // 2. if (num1) num1 = num2
Logical Assignment Operator with || operator
왼쪽의(LHS)의 값이 어떤 값을 갖고 있을 경우(not undefined)에 오른쪽(RHS-Right Hand Side)의 값이 왼쪽 값에 할당된다.
// Logical Assignment Operator with || operator let num1 let num2 = 10 num1 ||= num2 console.log(num1) // 10 // "num1 ||= num2"는 아래처럼 사용할 수도 있다. // 1. num1 || (num1 = num2) // 2. if (!num1) num1 = num2
Logical Assignment Operator with ?? operator
ES2020은 Nullish Coalescing 연산자를 도입했으며, 이 연산자는 할당 연산자와도 결합될 수 있다.
왼쪽의(LHS)의 값이 어떤 값을 갖고 있을 경우(not undefined)에 오른쪽(RHS-Right Hand Side)의 값이 왼쪽 값에 할당된다.
// Logical Assignment Operator with ?? operator let num1 let num2 = 10 num1 ??= num2 console.log(num1) // 10 num1 = false num1 ??= num2 console.log(num1) // false // "num1 ??= num2"는 아래처럼 사용할 수도 있다. // num1 ?? (num1 = num2)
Numeric Seprators
숫자 구분 기능으로 숫자 그룹을 구분하기 위해 _(밑줄)을 사용하여 숫자 값을 더 쉽게 읽을 수 있다.
let number = 100_000 console.log(number) /**** Output ****/ // 100000
Intl.ListFormat
ListFormat Object는 두 개의 매개 변수를 사용하며, 모두 Option(선택사항)이다. 첫 번째 매개 변수는 언어(locale-장소)이고, 두 번째 매개 변수는 style, type이라는 두 가지 속성이 있는 옵션 Object이다
new Intl.ListFormat([locales[, options]])
Intl.ListFormat은 배열을 인수로 받고 언어에 따라 다른 방식으로 형식을 지정하는 format() 메서드가 있다.
즉, 배열을 ListFormat에서 지정해준 것에 따라서 어떻게 보여줄 것인가에 대한 세팅이다.
아래 예시는 다른 locale과 option의 조합 예시이다.
const arr = ['Pen', 'Pencil', 'Paper'] let obj = new Intl.ListFormat('en', { style: 'short', type: 'conjunction' }) console.log(obj.format(arr)) /**** Output ****/ // Pen, Pencil, & Paper obj = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' }) console.log(obj.format(arr)) /**** Output ****/ // Pen, Pencil, and Paper obj = new Intl.ListFormat('en', { style: 'narrow', type: 'conjunction' }) console.log(obj.format(arr)) /**** Output ****/ // Pen, Pencil, Paper // 이탈리아어 tag obj = new Intl.ListFormat('it', { style: 'short', type: 'conjunction' }) console.log(obj.format(arr)) /**** Output ****/ // Pen, Pencil e Paper // 독일어 tag obj = new Intl.ListFormat('de', { style: 'long', type: 'conjunction' }) console.log(obj.format(arr)) /**** Output ****/ // Pen, Pencil und Paper
dateStyle and timeStyle options for Intl.DateTimeFormat
Intl.DateTimeFormat Object는 언어에 맞는 시간 및 날짜 포맷을 사용하는 object(객체)의 constructor(생성자)이다.
MDN spec을 다시 확인해봐야겠지만, moment 라이브러리 대신 잘 사용할 수 있을 것 같다.
각기 다른 옵션과 언어(지역)를 사용한 예시들이다.
// Time only with short format let o = new Intl.DateTimeFormat('en' , { timeStyle: 'short' }) console.log(o.format(Date.now())) // 11:27 PM // Time only with medium format o = new Intl.DateTimeFormat('en' , { timeStyle: 'medium'}) console.log(o.format(Date.now())) // 11:27:57 PM // Time only with long format o = new Intl.DateTimeFormat('en' , { timeStyle: 'long' }) console.log(o.format(Date.now())) // 11:27:57 PM GMT+11 // Date only with short format o = new Intl.DateTimeFormat('en' , { dateStyle: 'short'}) console.log(o.format(Date.now())) // 10/6/20 // Date only with medium format o = new Intl.DateTimeFormat('en' , { dateStyle: 'medium'}) console.log(o.format(Date.now())) // Oct 6, 2020 // Date only with long format o = new Intl.DateTimeFormat('en' , { dateStyle: 'long'}) console.log(o.format(Date.now())) // October 6, 2020
아래 예시처럼 dateStyle과 timeStyle 옵션도 다른 언어 태그와 함께 쓰인다.
let abc // English language abc = new Intl.DateTimeFormat('en' , { timeStyle: 'short', dateStyle: 'long'}) console.log(abc.format(Date.now())) // October 6, 2020 at 11:40 PM // Italian language abc = new Intl.DateTimeFormat('it' , { timeStyle: 'short', dateStyle: 'long'}) console.log(abc.format(Date.now())) // 6 ottobre 2020 23:40 // German language abc = new Intl.DateTimeFormat('de' , { timeStyle: 'short', dateStyle: 'long'}) console.log(abc.format(Date.now())) // 6. Oktober 2020 um 23:40
마무리
사실 아주 awesome 한 기능들인지는 잘 모르겠다.
하지만,, stackoverflow에 "이거 js에서는 왜 안돼요?" 하는 질문 속 기능이라든지 moment처럼 많이 쓰이는 기능을 내제화 하는 것도 꽤 괜찮은 아이디어로 보인다.
아직 최종적으로 브라우저 업데이트가 된 것이 아니기에, 신나서 replaceAll과 같은 기능들로 코드를 바꿨다가는 중얼거리면서 롤백을 하고 있을 것이다. 크롬에서는 버전 업데이트를 사용할 수는 있지만, 많은 사용자가 있거나 사용자가 다양한 브라우저를 사용한다면 업데이트하는 것을 지양하자.
2021년 상반기가 지나야 잘 쓸 수 있을 것 같다. 하지만 나 , 이 글을 보는 분 그리고 우리 모두 망각의 동물이기에 잘 기억하자.
참고
codeburst: codeburst.io/exciting-features-of-javascript-es2021-es12-1de8adf6550b
반응형'Front-end > Javascript' 카테고리의 다른 글
[Group Study, 모던 자바스크립트 Deep Dive] - 11 원시 값과 객체의 비교 (0) 2022.10.26 [Group Study, 모던 자바스크립트 Deep Dive] - 10 객체 리터럴 (0) 2022.10.25 [Javascript] 쓰로틀링, 디바운싱(throttling, debouncing)? (0) 2020.07.26 [Javascript] 프로토타입(Prototype)? (0) 2020.07.19 [Javascript] call, apply, bind? (0) 2020.06.16