New in ES2021 Examples | Dev Driven 開発・デザインチーム New in ES2021 Examples | 働くひとと組織の健康を創る iCARE

BLOG

New in ES2021 Examples

HirosawaTsuyoshi
2021/06/30
+3

What's this?

ES2021 was officially released on June 21, 2021.
In line with this, iCARE Corporation held an internal study session.
The materials used in the meeting are now available.

This article was written by @watsuyo_2, a front-end engineer at iCARE Corporation.

2021/6/21に ES2021 が正式リリースとなりました。
それに伴い、株式会社iCARE では社内勉強会を行いました。
その際、使用した資料を公開します。

※ この記事は株式会社iCAREのフロントエンドエンジニアである @watsuyo_2執筆しました。

Logical Assignment Operators

tc39/proposal-logical-assignment

||(Or Or Equals)

type User = {
  id: number
}

const user = {} as User

const updateId = () => {
  // same result
  // if (!user.id) user.id = 4

  // same result
  // user.id = user.id || 4

  // same result
  user.id ||= 4
}

updateId()

const getUser = () => {
  return  user
}

console.log(getUser())

// {
//   "id": 4
// } 

&&(And And Equals)

type User = {
  id: number
}

const user = {
    id: 1
}

const updateUserId = () => {
  // same result
  // if (user.id) user.id = 4

  // same result
  // user.id = user.id && 4

  // same result
  user.id &&= 4
}

updateUserId()

const getUser = () => {
  return  user
}

console.log(getUser())

// {
//   "id": 4
// } 

??(QQ Equals)

type User = {
  id: number
  name?: string
}

const user: User = {
    id: 1,
}

const updateUserName = () => {
    // same result
    // if (user.name) user.name = 'taro'

    // same result
    // user.name = user.name ?? 'taro'

    // same result
    user.name ??= 'taro'
}

updateUserName()

const getUser = () => {
  return  user
}

console.log(getUser())

Numeric Separators

tc39/proposal-numeric-separator

const price = 1_000
const tickets = 10_000
const fee = 1.086_4

console.log(price * ticket * fee)
// 10_864_000

Promise.any and AggregateError

tc39/proposal-promise-any

const errorPromise = new Promise((resolve, reject) => {
  reject("Always fails");
});

const slowPromise = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, "slow");
});

const fastPromise = new Promise((resolve, reject) => {
  setTimeout(resolve, 10, "fast");
});

Promise.any([errorPromise, slowPromise, fastPromise]).then((value) => {
  console.log(value);
})
// "fast"

String.prototype.replaceAll

tc39/proposal-string-replaceall

console.log('0120-1234-5678'.replaceAll('-', ' '))
// "0120 1234 5678"

WeakRefs and FinalizationRegistry Objects

coming soon...
tc39/proposal-weakrefs

+3