The updated content of ECMAScript organized by ChatGPT over the years

ECMAScript 1:

  • Release time: June 1997
  • What’s new: The first ECMAScript standard, including basic syntax, data types, control flow, and basic objects.

ECMAScript 2:

  • Release time: June 1998
  • What’s new: Fixed some bugs in the first standard.

ECMAScript 3:

  • Release time: December 1999

  • What’s new: A major upgrade to the language, adding regular expressions, error handling, and stronger object-oriented programming support.

  • Example:

    • Regular expression:
     var pattern = /hello\s+(world|everyone)/; var result = pattern.exec("hello world"); console.log(result[1]); // "world"
    • Error handling:
     try { // some code that might throw an error } catch (e) { console.error("An error occurred:", e.message); }
    • Object-Oriented Programming:
     function Person(name, age) { this.name = name; this.age = age; } Person.prototype.sayHello = function() { console.log("Hello, my name is " + this.name); }; var john = new Person("John", 30); john.sayHello(); // "Hello, my name is John"

ECMAScript 4:

  • Release time: not released
  • Update content: This version of the specification is obsolete and has not been officially released.

ECMAScript 5:

  • Release time: December 2009

  • What’s new: Some new features have been introduced, such as strict mode, JSON object, Object.getPrototypeOf() and Object.keys(), etc.

  • Example:

    • Strict mode:
     "use strict"; // some strict code here
    • JSON object:
     var jsonStr = '{"name": "John", "age": 30}'; var obj = JSON.parse(jsonStr); console.log(obj.name); // "John"
    • Object. getPrototypeOf():
     var obj = {}; var proto = Object.getPrototypeOf(obj); console.log(proto === Object.prototype); // true
    • Object. keys():
     var obj = {name: "John", age: 30}; var keys = Object.keys(obj); console.log(keys); // ["name", "age"]
  • Strict Mode: Strict mode has been added to write JavaScript code more disciplinedly.

  • The bind method of the function: allows the this keyword in the specified function to be bound to the specified object.

  • Array methods: Added some new methods of Array objects, such as map, filter, reduce, etc.

  • JSON object: Incorporate the JSON object into the ECMAScript specification and specify the string format in JSON format.

ECMAScript 5.1:

  • Release time: June 2011
  • What’s new: Fixed some bugs in ECMAScript 5.

Here are some ECMAScript 5.1 examples:

 // 严格模式示例"use strict"; function strictFunc() { // 在严格模式下,使用未声明的变量会报错undeclaredVar = 10; } strictFunc(); // bind方法示例var person = { firstName: "John", lastName: "Doe" }; function greeting() { console.log("Hello, " + this.firstName + " " + this.lastName); } var greetPerson = greeting.bind(person); greetPerson(); // Array方法示例var numbers = [1, 2, 3, 4, 5]; var doubledNumbers = numbers.map(function(num) { return num * 2; }); console.log(doubledNumbers); // [2, 4, 6, 8, 10] // JSON示例var person = { firstName: "John", lastName: "Doe", age: 30 }; var jsonString = JSON.stringify(person); console.log(jsonString); // {"firstName":"John","lastName":"Doe","age":30}

ECMAScript 6:

  • Release time: June 2015
  • What’s new: Many important new features have been introduced, such as arrow functions, template strings, destructuring assignments, classes and modules, and more.

ECMAScript 6 (ES6) is the next-generation standard for the JavaScript language, also known as ECMAScript 2015. It was released in June 2015, introducing many new language features and syntax improvements. Here are some important features and examples of ECMAScript 6:

  1. let and const declarations (published June 2015):
  • let and const declarations replace var declarations.
  • The let declaration is used to declare local variables, and the const declaration is used to declare constants.
  • Example:
 let x = 1; // 局部变量const PI = 3.14; // 常量
  1. Arrow functions (released June 2015):
  • Arrow functions are a shorter function syntax.
  • They use the => symbol to separate parameters and function body.
  • Example:
 // 传统函数function add(x, y) { return x + y; } // 箭头函数let add = (x, y) => x + y;
  1. Template literals (published June 2015):
  • Template literals allow interpolation of variables within strings.
  • Use backticks (`) instead of quotation marks.
  • Example:
 let name = 'John'; console.log(`Hello, ${name}!`);
  1. Destructuring assignment (released June 2015):
  • Destructuring assignment allows extracting values ​​from arrays or objects and assigning them to variables.
  • Example:
 // 数组解构赋值let [x, y] = [1, 2]; // 对象解构赋值let { name, age } = { name: 'John', age: 30 };
  1. Classes and Inheritance (published June 2015):
  • A class is a structure for declaring objects.
  • Inheritance allows classes to inherit properties and methods from other classes.
  • Example:
 class Person { constructor(name, age) { this.name = name; this.age = age; } sayHello() { console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); } } class Student extends Person { constructor(name, age, grade) { super(name, age); this.grade = grade; } study() { console.log(`${this.name} is studying hard!`); } } let john = new Student('John', 18, '12th'); john.sayHello(); // 输出:Hello, my name is John and I am 18 years old. john.study(); // 输出:John is studying hard!
  1. Promises (released June 2015):
  • Promises are a way to handle asynchronous operations.
  • They allow you to execute other code after the operation completes.
  • Example:
 let promise = new Promise((resolve, reject) => { setTimeout(() => { resolve('Success!'); }, 1000); }); promise.then((result) => { console.log(result); // 输出:Success! })

ECMAScript 2017 (ES8)

Time: June 2017

update content:

  1. Object.entries() and Object.values()

Two new static methods Object.entries() and Object.values() have been added, which can return the key-value pairs and value collections of the object respectively.

Example:

 const obj = { foo: 'bar', baz: 42 }; console.log(Object.entries(obj)); // [['foo', 'bar'], ['baz', 42]] console.log(Object.values(obj)); // ['bar', 42]
  1. String padding methods padStart() and padEnd()

Added string padding methods padStart() and padEnd(), which can add specified characters at the beginning or end of the string to make the string reach the specified length.

Example:

 const str = 'foo'; console.log(str.padStart(6, 'x')); // 'xxxxfo' console.log(str.padEnd(6, 'x')); // 'fooxxx'
  1. Commas are allowed at the end of function parameter lists

In function parameter lists, a comma is allowed after the last parameter, which helps maintain code consistency when adding or removing parameters.

Example:

 function myFunction(a, b, c,) { // ... }
  1. Shared memory and atomic operations API

Added APIs for shared memory and atomic operations that support the development of multithreaded JavaScript applications.

Example:

 const buffer = new SharedArrayBuffer(16); const view = new Int32Array(buffer); function updateView() { Atomics.store(view, 0, 123); } function getView() { return Atomics.load(view, 0); }

ECMAScript 2018 (ES9)

Time: June 2018

update content:

  1. asynchronous iteration

Added asynchronous iterators and for-await-of loops, which make it easier to traverse asynchronous data streams.

Example:

 async function* asyncGenerator() { yield 1; yield 2; yield 3; } (async function() { for await (let num of asyncGenerator()) { console.log(num); } })();
  1. Promise.prototype.finally()

Added the Promise.prototype.finally() method, which is used to specify the callback function that will be executed when the Promise state becomes resolved or rejected.

Example:

 function myFetch() { return fetch('https://example.com/data') .then(response => response.json()) .finally(() => { console.log('cleanup'); }); }
  1. Rest/Spread properties

The Rest/Spread property supports the spread operator (…) of objects and arrays for easy copying and merging of data.

Example:

 const obj1 = { a: 1, b: 2 }; const obj2 = { ...obj1, c: 3 }; const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; const arr3 = [...arr1, ...arr2];

ECMAScript 2019 (ES10)

Time: June 2019

update content:

  1. Object.fromEntries(): This method converts a list of key-value pairs into an object. This is useful when converting a Map to an object.

Example:

 const entries = new Map([['foo', 'bar'], ['baz', 42]]); const obj = Object.fromEntries(entries); console.log(obj); // {foo: "bar", baz: 42}
  1. String.trimStart() and String.trimEnd(): These two methods can be used to remove blank characters at the beginning and end of a string, respectively.

Example:

 const str = " hello world "; console.log(str.trimStart()); // "hello world " console.log(str.trimEnd()); // " hello world"
  1. Array.prototype.flat() and Array.prototype.flatMap(): These two methods can be used to “flatten” nested arrays.

Example:

 const arr = [1, 2, [3, 4, [5, 6]]]; console.log(arr.flat()); // [1, 2, 3, 4, [5, 6]] console.log(arr.flat(2)); // [1, 2, 3, 4, 5, 6] const arr2 = [1, 2, 3]; console.log(arr2.flatMap(x => [x * 2])); // [2, 4, 6]
  1. Optional Catch Binding: Parameters in catch statements can now be omitted, for example:

Example:

 try { // code here } catch { // handle error here }
  1. Object.getOwnPropertyDescriptors(): This method returns all property descriptors of the object, including information such as their values, enumerability, configurability, and writability.

Example:

 const obj = { foo: 'bar' }; console.log(Object.getOwnPropertyDescriptors(obj)); // { foo: { value: 'bar', writable: true, enumerable: true, configurable: true } }
  1. BigInt: Larger integers can now be represented using the BigInt type.

Example:

 const x = 9007199254740991n; const y = 9007199254740992n; console.log(x + y); // 18014398509481983n
  1. Other improvements: There are some other improvements, for example, the Array.prototype.sort() method now uses the TimSort algorithm, and the Function.prototype.toString() method now returns the complete function source code, etc.

ECMAScript 2020 (ES11)

Time: June 2020

ECMAScript 2020 is the latest version of the JavaScript language, also known as ES11 or ES2020. It was released in June 2020 with some new features and improvements, here are some important updates:

  1. Promise.allSettled() method: The Promise.allSettled() method returns a Promise that will fulfill when all passed Promises have fulfilled, regardless of whether they were successful or not.

Example:

 const promises = [ Promise.resolve('resolved'), Promise.reject('rejected'), Promise.resolve('resolved again') ]; Promise.allSettled(promises) .then(results => console.log(results));

Output result:

 [ {status: "fulfilled", value: "resolved"}, {status: "rejected", reason: "rejected"}, {status: "fulfilled", value: "resolved again"} ]
  1. Optional chaining operator: Optional chaining operators allow you to safely access deeply nested objects without verifying the existence of each preceding reference.

Example:

 const user = { name: 'John', address: { street: '123 Main St', city: 'Anytown', state: 'CA', zip: '12345' } }; console.log(user?.address?.street); // 123 Main St console.log(user?.phone?.number); // undefined
  1. Nullish coalescing operator: The null coalescing operator (??) is a new operator for handling null or undefined values. Returns the right operand if the left operand is null or undefined, otherwise returns the left

  2. the operand of .

    Example:

     const someValue = null; const anotherValue = 'Hello'; console.log(someValue ?? 'Default Value'); // Default Value console.log(anotherValue ?? 'Default Value'); // Hello
    1. New methods for iterable objects: This version also introduces some new iterable object methods, such as new methods for BigInt, String, Array and other objects.

    Example:

     // BigInt新方法const bigNum = 123456789n; console.log(bigNum.toLocaleString('en-US')); // 123,456,789 // String新方法const str = 'Hello World'; console.log(str.startsWith('Hello')); // true console.log(str.endsWith('World')); // true console.log(str.trimEnd()); // 'Hello World' // Array新方法const arr = [1, 2, 3]; console.log(arr.copyWithin(1, 0)); // [1, 1, 2] console.log(arr.flat()); // [1, 1, 2]

ECMAScript 2021 (ES12)

Time: June 2021

ECMAScript 2021 is the latest version of the JavaScript language, also known as ES12 or ES2021. It was released in June 2021 and contains some new features and improvements, here are some important updates:

  1. Promise.any() method: The Promise.any() method receives an array of multiple Promise objects and returns the result of the fastest resolved Promise.

Example:

 const promises = [ new Promise((resolve) => setTimeout(resolve, 5000, 'first')), new Promise((resolve) => setTimeout(resolve, 2000, 'second')), new Promise((resolve, reject) => setTimeout(reject, 3000, 'rejected')) ]; Promise.any(promises) .then(result => console.log(result)); // 'second'
  1. WeakRefs: WeakRefs is a new garbage collection mechanism that stores objects in weak references without affecting memory management.

Example:

 let obj = {a: 1}; const weakRef = new WeakRef(obj); obj = null; setTimeout(() => { if (weakRef.deref() === undefined) { console.log('Object is garbage collected'); } }, 5000);
  1. Numeric separators: Numeric separators allow the use of underscores in numeric literals to separate numbers to improve code readability.

Example:

 const bigNumber = 1_000_000_000; const binaryNumber = 0b1010_0001; const hexNumber = 0xFF_00_FF;
  1. String.prototype.replaceAll() method: The String.prototype.replaceAll() method can replace all occurrences of substrings in a string.

Example:

 const str = 'Hello World'; console.log(str.replaceAll('l', 'X')); // 'HeXXo WorXd'

These are some of the important updates and examples for ECMAScript 2021. There are other improvements and updates in this release, more information can be found in the official documentation.

This article is transferred from https://fugary.com/?p=450
This site is only for collection, and the copyright belongs to the original author.