avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • Resume
  • Archives
  • Categories
  • Photos
  • Music



{{ date }}

{{ time }}

avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • 主页
  • Resume
  • Archives
  • Categories
  • Photos
  • Music

ES6+ Features

  2023-06-07        
字数统计: 3.4k字   |   阅读时长: 21min

ES6+ Features

ES6 (ECMAScript 2015) introduced significant enhancements to JavaScript, and subsequent versions have continued to add powerful features. This guide explores the key features from ES6 and beyond that have transformed modern JavaScript development.

Overview of ECMAScript Evolution

  • ES6/ES2015: Major update with many new features
  • ES7/ES2016: Smaller update (Array.prototype.includes, Exponentiation Operator)
  • ES8/ES2017: Async/await, Object methods
  • ES9/ES2018: Rest/spread for objects, Promise.finally, async iteration
  • ES10/ES2019: Array.prototype.flat, Object.fromEntries
  • ES11/ES2020: Optional chaining, Nullish coalescing, BigInt
  • ES12/ES2021: String.prototype.replaceAll, Promise.any, Logical assignment
  • ES13/ES2022: Top-level await, Class fields, Error cause

ES6 (ES2015) Features

Let and Const Declarations

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// var - function-scoped, can be redeclared
var x = 1;
var x = 2; // Valid

// let - block-scoped, can be reassigned
let y = 1;
y = 2; // Valid
// let y = 2; // Error: y has already been declared

// const - block-scoped, cannot be reassigned
const z = 1;
// z = 2; // Error: Assignment to constant variable

// Block scoping
if (true) {
let blockScoped = 'only available in this block';
const alsoBlockScoped = 'same here';
}
// console.log(blockScoped); // Error: blockScoped is not defined

// const with objects/arrays
const person = { name: 'John' };
person.name = 'Jane'; // Valid - the object properties can be changed
// person = {}; // Error - reassigning the binding is not allowed

const numbers = [1, 2, 3];
numbers.push(4); // Valid - you can modify array contents
// numbers = []; // Error - reassigning the binding is not allowed

Arrow Functions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Traditional function expression
const add = function(a, b) {
return a + b;
};

// Arrow function
const addArrow = (a, b) => a + b;

// Arrow function with single parameter (parentheses optional)
const square = x => x * x;

// Arrow function with multiple statements
const calculate = (a, b) => {
const result = a * b;
return result + 10;
};

// Empty parameter list requires parentheses
const getRandomNumber = () => Math.random();

// Arrow functions do not have their own this
const object = {
data: [1, 2, 3],
processData() {
// Arrow function inherits this from outer scope
this.data.forEach(item => {
console.log(item, this.data); // this refers to object
});
}
};

Template Literals

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const name = 'Alice';
const age = 28;

// String concatenation (old way)
const message1 = 'My name is ' + name + ' and I am ' + age + ' years old.';

// Template literals
const message2 = `My name is ${name} and I am ${age} years old.`;

// Multi-line strings
const multiLine = `This is a string
that spans multiple
lines without escape characters.`;

// Tagged templates
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
const value = values[i] || '';
return `${result}${str}<span class="highlight">${value}</span>`;
}, '');
}

const username = 'Admin';
const highlightedText = highlight`Hello ${username}, welcome back!`;
// "<span class="highlight">Hello </span>Admin<span class="highlight">, welcome back!</span>"

Destructuring Assignment

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Object destructuring
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
address: {
city: 'New York',
country: 'USA'
}
};

// Basic destructuring
const { firstName, lastName } = person;
console.log(firstName, lastName); // "John" "Doe"

// Destructuring with new variable names
const { firstName: first, lastName: last } = person;
console.log(first, last); // "John" "Doe"

// Nested destructuring
const { address: { city, country } } = person;
console.log(city, country); // "New York" "USA"

// Default values
const { zipCode = '10001' } = person;
console.log(zipCode); // "10001" (default value since it doesn't exist)

// Rest pattern
const { firstName: fName, ...rest } = person;
console.log(rest); // { lastName: "Doe", age: 30, address: { city: "New York", country: "USA" } }

// Array destructuring
const numbers = [1, 2, 3, 4, 5];

// Basic array destructuring
const [first, second, ...remaining] = numbers;
console.log(first, second, remaining); // 1 2 [3, 4, 5]

// Skipping elements
const [a, , c] = numbers;
console.log(a, c); // 1 3

// Default values
const [x, y, z = 10] = [1, 2];
console.log(x, y, z); // 1 2 10

// Swapping variables
let a1 = 'first';
let b1 = 'second';
[a1, b1] = [b1, a1];
console.log(a1, b1); // "second" "first"

// Function parameter destructuring
function printPersonInfo({ firstName, lastName, age = 'unknown' }) {
console.log(`${firstName} ${lastName}, ${age} years old`);
}
printPersonInfo(person); // "John Doe, 30 years old"

Default Parameters

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Basic default parameters
function greet(name = 'Guest') {
return `Hello, ${name}!`;
}
console.log(greet()); // "Hello, Guest!"
console.log(greet('Alice')); // "Hello, Alice!"

// Default parameters with expressions
function calculateTax(amount, taxRate = amount * 0.1) {
return amount + taxRate;
}
console.log(calculateTax(100)); // 110
console.log(calculateTax(100, 20)); // 120

// Default parameters based on other parameters
function createUser(name, role = 'user', id = `${name}-${role}-${Date.now()}`) {
return { name, role, id };
}
console.log(createUser('john')); // { name: 'john', role: 'user', id: 'john-user-1623456789' }

Rest and Spread Operators

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Rest operator in function parameters
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // 15

// Rest with other parameters
function multiply(multiplier, ...numbers) {
return numbers.map(num => num * multiplier);
}
console.log(multiply(2, 1, 2, 3)); // [2, 4, 6]

// Spread operator with arrays
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const combined = [...array1, ...array2];
console.log(combined); // [1, 2, 3, 4, 5, 6]

// Spread to copy arrays
const original = [1, 2, 3];
const copy = [...original];
original.push(4);
console.log(original); // [1, 2, 3, 4]
console.log(copy); // [1, 2, 3]

// Spread with objects (ES9+)
const defaults = { theme: 'light', fontSize: 16 };
const userPrefs = { fontSize: 20, showSidebar: true };
const mergedPrefs = { ...defaults, ...userPrefs };
console.log(mergedPrefs); // { theme: 'light', fontSize: 20, showSidebar: true }

Enhanced Object Literals

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Property shorthand
const name = 'John';
const age = 30;
const person = { name, age };
console.log(person); // { name: 'John', age: 30 }

// Method shorthand
const calculator = {
add(a, b) {
return a + b;
},
subtract(a, b) {
return a - b;
}
};
console.log(calculator.add(5, 3)); // 8

// Computed property names
const propertyName = 'status';
const value = 'active';
const user = {
[propertyName]: value,
[`user_${Date.now()}`]: true
};
console.log(user); // { status: 'active', user_1623456789: true }

Classes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Class declaration
class Person {
// Constructor
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

// Method
getFullName() {
return `${this.firstName} ${this.lastName}`;
}

// Static method
static createAnonymous() {
return new Person('Anonymous', 'User');
}
}

const person1 = new Person('John', 'Doe');
console.log(person1.getFullName()); // "John Doe"

const anonymous = Person.createAnonymous();
console.log(anonymous.getFullName()); // "Anonymous User"

// Inheritance
class Employee extends Person {
constructor(firstName, lastName, position) {
// Call parent constructor
super(firstName, lastName);
this.position = position;
}

// Override parent method
getFullName() {
return `${super.getFullName()} (${this.position})`;
}
}

const employee = new Employee('Jane', 'Smith', 'Developer');
console.log(employee.getFullName()); // "Jane Smith (Developer)"

Modules

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Exporting (in math.js)
export const PI = 3.14159;

export function add(a, b) {
return a + b;
}

export function subtract(a, b) {
return a - b;
}

const privateFunction = () => {
console.log('This is private');
};

export default class Calculator {
multiply(a, b) {
return a * b;
}
}

// Importing (in app.js)
import Calculator, { PI, add } from './math.js';
import * as math from './math.js';

console.log(PI); // 3.14159
console.log(add(2, 3)); // 5

const calc = new Calculator();
console.log(calc.multiply(4, 5)); // 20

console.log(math.subtract(10, 4)); // 6

Promises

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Creating a promise
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = { id: 1, name: 'Product' };
const success = true;

if (success) {
resolve(data);
} else {
reject(new Error('Failed to fetch data'));
}
}, 1000);
});
};

// Using a promise
fetchData()
.then(data => {
console.log('Success:', data);
return { ...data, processed: true };
})
.then(processedData => {
console.log('Processed:', processedData);
})
.catch(error => {
console.error('Error:', error.message);
})
.finally(() => {
console.log('Operation completed');
});

// Promise.all - wait for all promises to resolve
Promise.all([
fetchData(),
fetchData() // Another promise
])
.then(results => {
console.log('All results:', results);
})
.catch(error => {
console.error('At least one promise failed:', error);
});

// Promise.race - resolve when first promise resolves/rejects
Promise.race([
fetchData(),
new Promise((_, reject) => setTimeout(() => reject(new Error('Timeout')), 2000))
])
.then(result => {
console.log('First to complete:', result);
})
.catch(error => {
console.error('First to fail:', error);
});

Iterators and Generators

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Iterators
const array = [1, 2, 3];
const iterator = array[Symbol.iterator]();

console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
console.log(iterator.next()); // { value: undefined, done: true }

// Custom iterable
const customIterable = {
data: [10, 20, 30],

[Symbol.iterator]() {
let index = 0;
const data = this.data;

return {
next() {
if (index < data.length) {
return { value: data[index++], done: false };
} else {
return { value: undefined, done: true };
}
}
};
}
};

for (const item of customIterable) {
console.log(item); // 10, 20, 30
}

// Generators
function* numberGenerator() {
yield 1;
yield 2;
yield 3;
}

const numGen = numberGenerator();
console.log(numGen.next()); // { value: 1, done: false }
console.log(numGen.next()); // { value: 2, done: false }
console.log(numGen.next()); // { value: 3, done: false }
console.log(numGen.next()); // { value: undefined, done: true }

// Generator with data received via next()
function* conversation() {
const name = yield 'What is your name?';
const hobby = yield `Hello, ${name}! What is your hobby?`;
yield `${name} likes ${hobby}. That's great!`;
}

const convo = conversation();
console.log(convo.next().value); // "What is your name?"
console.log(convo.next('John').value); // "Hello, John! What is your hobby?"
console.log(convo.next('coding').value); // "John likes coding. That's great!"

Map and Set

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Map - key-value pairs (any type of keys)
const userMap = new Map();

// Adding entries
userMap.set('name', 'John');
userMap.set(42, 'answer');
userMap.set(true, 'boolean key');

// Object as key
const userObj = { id: 1 };
userMap.set(userObj, 'object as key');

// Getting values
console.log(userMap.get('name')); // "John"
console.log(userMap.get(userObj)); // "object as key"

// Checking if key exists
console.log(userMap.has(true)); // true
console.log(userMap.has('missing')); // false

// Size and deletion
console.log(userMap.size); // 4
userMap.delete(42);
console.log(userMap.size); // 3

// Iteration
for (const [key, value] of userMap) {
console.log(key, value);
}

// Set - collection of unique values
const uniqueNumbers = new Set([1, 2, 3, 3, 4, 4, 5]);
console.log(uniqueNumbers); // Set(5) { 1, 2, 3, 4, 5 }

// Adding values
uniqueNumbers.add(6);
uniqueNumbers.add(1); // Ignored as 1 already exists

// Checking if value exists
console.log(uniqueNumbers.has(3)); // true

// Size and deletion
console.log(uniqueNumbers.size); // 6
uniqueNumbers.delete(4);
console.log(uniqueNumbers.size); // 5

// Iteration
for (const num of uniqueNumbers) {
console.log(num);
}

// Converting Set to Array
const uniqueArray = [...uniqueNumbers];
console.log(uniqueArray); // [1, 2, 3, 5, 6]

// Using Set to remove duplicates from array
const numbers = [1, 2, 2, 3, 4, 4, 5];
const unique = [...new Set(numbers)];
console.log(unique); // [1, 2, 3, 4, 5]

Symbol

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Creating symbols
const sym1 = Symbol();
const sym2 = Symbol('description');
const sym3 = Symbol('description'); // sym2 !== sym3

// Symbols as object keys
const obj = {
[sym1]: 'value for sym1',
regularProp: 'regular value'
};

console.log(obj[sym1]); // "value for sym1"

// Symbols are not enumerable with for...in
for (const key in obj) {
console.log(key); // Only "regularProp"
}

// Getting symbols
console.log(Object.getOwnPropertySymbols(obj)); // [Symbol()]

// Well-known symbols
class CustomIterable {
constructor(items) {
this.items = items;
}

// Implement iteration protocol
[Symbol.iterator]() {
let index = 0;
const items = this.items;

return {
next() {
if (index < items.length) {
return { value: items[index++], done: false };
}
return { value: undefined, done: true };
}
};
}
}

const customList = new CustomIterable(['a', 'b', 'c']);
for (const item of customList) {
console.log(item); // "a", "b", "c"
}

Post-ES6 Features

Async/Await (ES2017)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Async function declaration
async function fetchUser(id) {
try {
const response = await fetch(`https://api.example.com/users/${id}`);
if (!response.ok) {
throw new Error('Failed to fetch user');
}
const user = await response.json();
return user;
} catch (error) {
console.error('Error fetching user:', error);
throw error;
}
}

// Using an async function
fetchUser(1)
.then(user => console.log('User:', user))
.catch(error => console.error('Failed:', error));

// Async arrow functions
const fetchProduct = async (id) => {
const response = await fetch(`https://api.example.com/products/${id}`);
return response.json();
};

// Async with array methods
const fetchMultipleUsers = async (ids) => {
// Sequential execution
const users = [];
for (const id of ids) {
const user = await fetchUser(id);
users.push(user);
}
return users;

// Parallel execution
// return Promise.all(ids.map(id => fetchUser(id)));
};

// Async with class methods
class UserAPI {
async getUser(id) {
// Implementation...
}

static async getAllUsers() {
// Implementation...
}
}

Object Methods (ES2017)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
const person = {
name: 'John',
age: 30,
city: 'New York'
};

// Object.values
console.log(Object.values(person)); // ["John", 30, "New York"]

// Object.entries
console.log(Object.entries(person));
// [["name", "John"], ["age", 30], ["city", "New York"]]

// Using Object.entries with destructuring
for (const [key, value] of Object.entries(person)) {
console.log(`${key}: ${value}`);
}

// Object.fromEntries (ES2019)
const entries = [
['name', 'Alice'],
['age', 25],
['city', 'London']
];

const personObj = Object.fromEntries(entries);
console.log(personObj); // { name: "Alice", age: 25, city: "London" }

// Object.fromEntries with Map
const map = new Map([
['name', 'Bob'],
['age', 40]
]);

const obj = Object.fromEntries(map);
console.log(obj); // { name: "Bob", age: 40 }

Rest/Spread for Objects (ES2018)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Rest with object destructuring
const { name, ...rest } = { name: 'John', age: 30, city: 'New York' };
console.log(name); // "John"
console.log(rest); // { age: 30, city: "New York" }

// Spread with objects
const defaults = { theme: 'light', fontSize: 16 };
const userSettings = { fontSize: 20, showSidebar: true };

// Merging objects (later properties override earlier ones)
const settings = { ...defaults, ...userSettings };
console.log(settings);
// { theme: "light", fontSize: 20, showSidebar: true }

// Conditional spread
const hasPermission = true;
const userWithPerms = {
name: 'Jane',
...(hasPermission && { role: 'admin' })
};
console.log(userWithPerms); // { name: "Jane", role: "admin" }

Optional Chaining (ES2020)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const user = {
name: 'John',
address: {
street: '123 Main St',
city: 'New York'
},
getFullName() {
return `${this.name} Doe`;
}
};

// Without optional chaining
let cityOld;
if (user && user.address && user.address.city) {
cityOld = user.address.city;
}

// With optional chaining
const city = user?.address?.city;
console.log(city); // "New York"

const zipCode = user?.address?.zipCode;
console.log(zipCode); // undefined

// Optional chaining with function calls
const fullName = user?.getFullName?.();
console.log(fullName); // "John Doe"

// Optional chaining with array elements
const users = [{ name: 'John' }];
console.log(users?.[0]?.name); // "John"
console.log(users?.[1]?.name); // undefined

Nullish Coalescing (ES2020)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Logical OR - returns right side when left is falsy
// Falsy values: false, 0, "", null, undefined, NaN
const name1 = "" || "Default Name";
console.log(name1); // "Default Name" (problem if empty string is valid)

const count1 = 0 || 10;
console.log(count1); // 10 (problem if 0 is valid)

// Nullish coalescing - only falls back when left is null or undefined
const name2 = "" ?? "Default Name";
console.log(name2); // "" (empty string is respected as a valid value)

const count2 = 0 ?? 10;
console.log(count2); // 0 (zero is respected as a valid value)

const nullValue = null ?? "Default";
console.log(nullValue); // "Default"

const undefinedValue = undefined ?? "Default";
console.log(undefinedValue); // "Default"

// Combining with optional chaining
const user = null;
console.log(user?.name ?? "Guest"); // "Guest"

Logical Assignment (ES2021)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Logical OR assignment (||=)
let user1 = { name: 'John' };
user1.name ||= 'Guest';
console.log(user1.name); // "John"

user1.role ||= 'User';
console.log(user1.role); // "User"

// Logical AND assignment (&&=)
let user2 = { name: 'Admin', verified: true };
user2.verified &&= false;
console.log(user2.verified); // false

// Nullish coalescing assignment (??=)
let user3 = { name: 'Jane' };
user3.name ??= 'Guest';
console.log(user3.name); // "Jane"

user3.role ??= 'User';
console.log(user3.role); // "User"

// Empty string example
let user4 = { name: '' };
user4.name ||= 'Guest'; // Assigns 'Guest' because empty string is falsy
user4.name ??= 'Default'; // Doesn't assign because empty string is not null/undefined
console.log(user4.name); // "Guest"

BigInt (ES2020)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Creating BigInt values
const bigInt1 = 9007199254740991n; // Append 'n' to create a BigInt literal
const bigInt2 = BigInt(9007199254740991); // Or use the BigInt() function

// Operations with BigInt
const sum = bigInt1 + BigInt(1000);
console.log(sum); // 9007199254741991n

// BigInt can represent integers of arbitrary size
const reallyBig = 9007199254740991n * 9007199254740991n;
console.log(reallyBig); // 81129638414606663681390495662081n

// Cannot mix BigInt and regular numbers
// const invalid = bigInt1 + 1; // TypeError

// Comparisons work
console.log(10n === BigInt(10)); // true
console.log(10n == 10); // true (type coercion)

// BigInt with conditionals
if (bigInt1 > 1000n) {
console.log('Really big!');
}

Private Class Fields (ES2022)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class BankAccount {
// Public field
owner;

// Private field (with # prefix)
#balance;

// Private static field
static #interestRate = 0.01;

constructor(owner, initialBalance) {
this.owner = owner;
this.#balance = initialBalance;
}

// Public method
deposit(amount) {
this.#balance += amount;
return this.#balance;
}

// Public method accessing private field
getBalance() {
return this.#balance;
}

// Private method
#calculateInterest() {
return this.#balance * BankAccount.#interestRate;
}

// Public method using private method
addInterest() {
const interest = this.#calculateInterest();
this.#balance += interest;
return interest;
}
}

const account = new BankAccount('John', 1000);
console.log(account.owner); // "John"
console.log(account.getBalance()); // 1000

account.deposit(500);
console.log(account.getBalance()); // 1500

console.log(account.addInterest()); // 15 (interest amount)

// Cannot access private fields directly
// console.log(account.#balance); // SyntaxError
// account.#calculateInterest(); // SyntaxError

Top-level Await (ES2022)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Before ES2022, await could only be used inside async functions
async function getData() {
const response = await fetch('https://api.example.com/data');
return response.json();
}

// With ES2022, await can be used at the top level in modules
// Note: This only works in ES modules, not CommonJS
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);

// Useful for conditional imports
let mathModule;
if (data.useAdvancedMath) {
mathModule = await import('./advanced-math.js');
} else {
mathModule = await import('./basic-math.js');
}

// Or for initializing an app
const config = await fetch('/api/config').then(r => r.json());
const db = await initDatabase(config);
startApp(db);

Learning Resources

  • MDN Web Docs - JavaScript
  • Exploring ES6
  • ES6 Features
  • What’s New in ES2022
  • JavaScript Info - Modern JavaScript
  • Babel - JavaScript compiler that allows you to use newer syntax
  • Web Development
  • JavaScript
  • ES6
  • ECMAScript
  • Modern JavaScript

扫一扫,分享到微信

微信分享二维码
Browser APIs & DOM Manipulation
JavaScript Advanced Concepts
目录
  1. 1. ES6+ Features
    1. 1.1. Overview of ECMAScript Evolution
    2. 1.2. ES6 (ES2015) Features
      1. 1.2.1. Let and Const Declarations
      2. 1.2.2. Arrow Functions
      3. 1.2.3. Template Literals
      4. 1.2.4. Destructuring Assignment
      5. 1.2.5. Default Parameters
      6. 1.2.6. Rest and Spread Operators
      7. 1.2.7. Enhanced Object Literals
      8. 1.2.8. Classes
      9. 1.2.9. Modules
      10. 1.2.10. Promises
      11. 1.2.11. Iterators and Generators
      12. 1.2.12. Map and Set
      13. 1.2.13. Symbol
    3. 1.3. Post-ES6 Features
      1. 1.3.1. Async/Await (ES2017)
      2. 1.3.2. Object Methods (ES2017)
      3. 1.3.3. Rest/Spread for Objects (ES2018)
      4. 1.3.4. Optional Chaining (ES2020)
      5. 1.3.5. Nullish Coalescing (ES2020)
      6. 1.3.6. Logical Assignment (ES2021)
      7. 1.3.7. BigInt (ES2020)
      8. 1.3.8. Private Class Fields (ES2022)
      9. 1.3.9. Top-level Await (ES2022)
    4. 1.4. Learning Resources

150 篇 | 131.7k
次 | 人
这里自动载入天数这里自动载入时分秒
2022-2025 loong loong | 新南威尔士龙龙号