ES2018 guide

ECMAScript is the standard on which JavaScript is based, and is often abbreviated as ES. Explore everything about ECMAScript and the features added in ES2018 (aka ES9)

ES2018 is the latest version of this versionECMAScriptstandard.

What new things does it introduce?

Residual/spread attribute

ES6Introduced a conceptRest elementWhen working withArray deconstruction:

const numbers = [1, 2, 3, 4, 5]
[first, second, ...others] = numbers

withSpread element:

const numbers = [1, 2, 3, 4, 5]
const sum = (a, b, c, d, e) => a + b + c + d + e
const sumOfNumbers = sum(...numbers)

ES2018 introduces the same content, but the objects are the same.

Rest attributes:

const { first, second, ...others } = { first: 1, second: 2, third: 3, fourth: 4, fifth: 5 }

first // 1 second // 2 others // { third: 3, fourth: 4, fifth: 5 }

Spread attributeAllows the creation of new objects by combining the properties of objects passed afterwardsSpread operator:

const items = { first, second, ...others }
items //{ first: 1, second: 2, third: 3, fourth: 4, fifth: 5 }

Asynchronous iteration

New structurefor-await-ofAllows you to use asynchronous iterable objects as loop iterations:

for await (const line of readLines(filePath)) {
  console.log(line)
}

Because of this useawait, You can only use it internallyasyncFunction, like normalawait(LookAsync/await)

Promise.prototype.finally()

After fulfilling the promise, successfully callthen()Methods, one by one.

If a failure occurs during this period, thenthen()Method is skipped,catch()The method is executed.

finally()Allows you to run certain code regardless of whether the promise is successfully executed:

fetch('file.json')
  .then(data => data.json())
  .catch(error => console.error(error))
  .finally(() => console.log('finished'))

Improvements in regular expressions

RegExp post-assertion: match according to the string before it

This is a look ahead: you use?=Match a string followed by a specific substring:

/Roger(?=Waters)/

/Roger(?= Waters)/.test(‘Roger is my dog’) //false /Roger(?= Waters)/.test(‘Roger is my dog and Roger Waters is a famous musician’) //true

?!Perform the inverse operation, if the string isIs notFollowed by a specific substring:

/Roger(?!Waters)/

/Roger(?! Waters)/.test(‘Roger is my dog’) //true /Roger(?! Waters)/.test(‘Roger Waters is a famous musician’) //false

Forerunner use?=Symbolic. They are already available.

Look backwards, A new feature, use?<=.

/(?<=Roger) Waters/

/(?<=Roger) Waters/.test(‘Pink Waters is my dog’) //false /(?<=Roger) Waters/.test(‘Roger is my dog and Roger Waters is a famous musician’) //true

Looking backwards uses negative?<!:

/(?<!Roger) Waters/

/(?<!Roger) Waters/.test(‘Pink Waters is my dog’) //true /(?<!Roger) Waters/.test(‘Roger is my dog and Roger Waters is a famous musician’) //false

Unicode attribute escape\p{…}with\P{…}

In regular expression mode, you can use\dMatches any number,\sMatches any character that is not a space,\wMatch any alphanumeric character, and so on.

This new feature extends this concept to all introduced Unicode characters\p{}And its negation\P{}.

anyUnicodeCharacters have a set of attributes. E.gScriptDecide on the type of languageASCIIIs a Boolean value, which is correct for ASCII characters, and so on. You can put this attribute in graphical brackets, and the regular expression will check if the attribute is true:

/^\p{ASCII}+$/u.test('abc')   //✅
/^\p{ASCII}+$/u.test('[email protected]')  //✅
/^\p{ASCII}+$/u.test('ABC🙃') //❌

ASCII_Hex_DigitIs another boolean attribute to check if the string contains only valid hexadecimal digits:

/^\p{ASCII_Hex_Digit}+$/u.test('0123456789ABCDEF') //✅
/^\p{ASCII_Hex_Digit}+$/u.test('h')                //❌

There are many other boolean attributes that you can check by adding their names in graphical brackets, includingUppercase,Lowercase,White_Space,Alphabetic,EmojiAnd more:

/^\p{Lowercase}$/u.test('h') //✅
/^\p{Uppercase}$/u.test('H') //✅

/^\p{Emoji}+$/u.test('H')   //❌
/^\p{Emoji}+$/u.test('🙃🙃') //✅

In addition to these binary attributes, you can also check any unicode character attribute to match a specific value. In this example, I check whether the string is written in Greek or Latin letters:

/^\p{Script=Greek}+$/u.test('ελληνικά') //✅
/^\p{Script=Latin}+$/u.test('hey') //✅

Read more about all the attributes that can be usedDirectly on the proposal.

Named capture group

In ES2018Capture teamYou can assign a name instead of just assigning a slot in the result array:

const re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
const result = re.exec('2015-01-02')

// result.groups.year === ‘2015’; // result.groups.month === ‘01’; // result.groups.day === ‘02’;

ThissSigns of regular expressions

ThissLogo, abbreviationSingle line,resulting in.To match newline characters. Without it, the dot will match regular characters, but not new lines:

/hi.welcome/.test('hi\nwelcome') // false
/hi.welcome/s.test('hi\nwelcome') // true

Download mine for freeJavaScript beginner's manual


More js tutorials: