New Features
Template Literals
Template literals provide an easy way to create strings, especially when you need to include variables or multiline text. They use backticks (`) instead of single or double quotes.
Features
- String Interpolation: Embed variables or expressions inside ${}.
- Multiline Strings: No need for escape characters.
- Readable and concise syntax.
Example:
let name = "Alice"; let age = 25; // String Interpolation let message = `Hello, my name is ${name} and I am ${age} years old.`; console.log(message); // Output: Hello, my name is Alice and I am 25 years old. // Multiline Strings let paragraph = ` This is a multiline string. It spans multiple lines. `; console.log(paragraph);
Modules (Import and Export)
Modules let you split your JavaScript code into separate files, making it easier to manage and reuse. You can export variables, functions, or classes from one file and import them into another.
Exporting
You can export in two ways:
- Named Export: Export specific variables or functions.
- Default Export: Export a single value as the default.
Example
File: math.js
// Named Export export const add = (a, b) => a + b; export const subtract = (a, b) => a - b; // Default Export export default function multiply(a, b) { return a * b; }
File: main.js
import multiply, { add, subtract } from './math.js'; console.log(add(2, 3)); // 5 console.log(subtract(5, 2)); // 3 console.log(multiply(4, 3)); // 12
WeakRefs
A WeakRef (Weak Reference) allows you to reference an object without preventing it from being garbage-collected. It's useful for caching or cases where memory management is critical.
Example
let obj = { name: "Alice" }; let weakRef = new WeakRef(obj); console.log(weakRef.deref()?.name); // "Alice" obj = null; // The object is now eligible for garbage collection. console.log(weakRef.deref()); // undefined
FinalizationRegistry
The FinalizationRegistry allows you to run a cleanup function after an object is garbage-collected. It's useful for cleaning up resources like file handles or database connections.
Example
let registry = new FinalizationRegistry((value) => { console.log(`Object with value "${value}" has been garbage-collected.`); }); let obj = { name: "Alice" }; registry.register(obj, "Alice's data"); obj = null; // The object is eligible for garbage collection.
ES2020 Features
Nullish Coalescing Operator (??)
This operator helps you provide a default value when a variable is null or undefined.
Example
let username = null; let defaultName = username ?? "Guest"; console.log(defaultName); // "Guest" let value = 0; let result = value ?? 42; console.log(result); // 0 (because 0 is not null or undefined)
Optional Chaining (?.)
Optional chaining allows you to access deeply nested properties without worrying about whether intermediate objects exist. If a property doesn't exist, it returns undefined instead of throwing an error.
Example
let user = { profile: { name: "Alice" } }; console.log(user.profile?.name); // "Alice" console.log(user.address?.city); // undefined (no error)
Dynamic Imports
Dynamic imports allow you to load JavaScript modules on demand, making your application more efficient.
Example
if (someCondition) { import("./module.js").then((module) => { module.doSomething(); }); }
BigInt
BigInt is a new data type for working with very large numbers beyond the safe integer limit of Number.
Example
let bigNumber = 123456789012345678901234567890n; let anotherBigNumber = BigInt(1234567890); console.log(bigNumber + anotherBigNumber);
Promise.allSettled
This method waits for all promises to either resolve or reject and gives the result for each one.
Example
let promises = [ Promise.resolve("Success"), Promise.reject("Error"), Promise.resolve("Another Success"), ]; Promise.allSettled(promises).then((results) => { console.log(results); // Output: // [ // { status: "fulfilled", value: "Success" }, // { status: "rejected", reason: "Error" }, // { status: "fulfilled", value: "Another Success" } // ] });
GlobalThis
globalThis provides a universal way to access the global object across different environments (browser, Node.js, etc.).
Example
console.log(globalThis); // Window object in browsers, global object in Node.js
String Matching with .matchAll()
The matchAll method returns all matches for a string, along with detailed information.
Example
let text = "cat bat rat"; let regex = /[a-z]at/g; for (let match of text.matchAll(regex)) { console.log(match); } // Output: ["cat"], ["bat"], ["rat"]
ES2021 Features
Logical Assignment Operators
These combine logical operations (||, &&, ??) with assignment.
Example
let x = 0; x ||= 42; // Assign 42 only if x is falsy console.log(x); // 42 let y = null; y ??= "default"; console.log(y); // "default"
Replace All in Strings
The replaceAll method replaces all occurrences of a substring.
Example
let text = "apple apple orange"; let result = text.replaceAll("apple", "banana"); console.log(result); // "banana banana orange"
Numeric Separators
You can use underscores (_) to make large numbers more readable.
Example
let bigNumber = 1_000_000; // Same as 1000000 console.log(bigNumber); // 1000000
ES2022 Features
Class Fields
Define properties directly in the class body.
Example
class Person { name = "Default Name"; // Public field #age = 30; // Private field getAge() { return this.#age; } } let p = new Person(); console.log(p.name); // "Default Name" console.log(p.getAge()); // 30
at() Method for Indexing
The at() method lets you access elements in arrays or strings using positive or negative indices.
Example
let arr = [10, 20, 30]; console.log(arr.at(0)); // 10 console.log(arr.at(-1)); // 30 let str = "hello"; console.log(str.at(-1)); // "o"
ES2023 Features
Array findLast and findLastIndex
These methods find the last element or its index in an array that satisfies a condition.
Example
let arr = [1, 2, 3, 4, 5]; console.log(arr.findLast((num) => num % 2 === 0)); // 4 console.log(arr.findLastIndex((num) => num % 2 === 0)); // 3
Hashbang Syntax (#!)
Allows scripts to specify the interpreter in the first line (for Node.js or other environments).
Example
#!/usr/bin/env node console.log("Hello, world!");