📜  esversion 9 - Javascript (1)

📅  最后修改于: 2023-12-03 15:14:54.446000             🧑  作者: Mango

Introduction to esversion 9 - Javascript

esversion 9, also known as ECMAScript 2018, is a major update to the Javascript language specification. It includes several new features and improvements that can help developers write cleaner and more efficient code.

New Features
Async Iteration

Async iteration allows us to iterate over asynchronous data sources such as streams or websockets. This is achieved by using the for-await-of loop instead of the traditional for-of loop. Here is an example:

async function *stream() {
  yield Promise.resolve(1);
  yield Promise.resolve(2);
  yield Promise.resolve(3);
}

async function main() {
  for await (let data of stream()) {
    console.log(data);
  }
}

main();

This will output:

1
2
3
Promise.prototype.finally()

The finally() method is now available on the Promise prototype. It allows us to execute some code regardless of whether the promise is resolved or rejected.

Promise.resolve("Success!")
  .then(result => console.log(result))
  .catch(error => console.error(error))
  .finally(() => console.log("Done."));

This will output:

Success!
Done.
Rest/Spread Properties for Objects

Rest and spread properties for objects allow us to easily copy and merge objects. Here is an example:

const person = { name: "John", age: 30 }
const employee = { ...person, id: 123 }

console.log(employee);

This will output:

{ name: "John", age: 30, id: 123 }
RegExp Improvements

ES2018 introduces several improvements to Regular Expressions including the s flag which allows the . character to match newline characters.

const regex = /hello.world/s;
console.log(regex.test("hello\nworld"));

This will output true.

Conclusion

Overall, esversion 9 brings a lot of useful new features to Javascript that can help us write more clean and efficient code. It's important to stay up to date with the latest changes in the language to take full advantage of these improvements.