🟡
Programming
JavaScript ES6+ Cheat Sheet
Arrow functions, destructuring, spread, async/await, modules — modern JS in one sheet.
Back to Notes Library
JavaScript ES6+ Cheat Sheet
let, const, var
javascript
var x = 1; // function-scoped, hoisted (avoid)
let y = 2; // block-scoped, reassignable
const z = 3; // block-scoped, not reassignable
const arr = [1, 2, 3]; // const does not mean immutable
arr.push(4); // this is allowed!Arrow Functions
javascript
// Traditional
function add(a, b) { return a + b; }
// Arrow
const add = (a, b) => a + b;
const square = x => x * x;
const greet = () => "Hello!";
// Multi-line
const complex = (x) => {
const doubled = x * 2;
return doubled + 1;
};Template Literals
javascript
const name = "Alice";
const age = 30;
// Old way
const msg = "Name: " + name + ", Age: " + age;
// Template literal
const msg2 = `Name: ${name}, Age: ${age}`;
// Multi-line string
const html = `
<div>
<h1>${name}</h1>
</div>
`;Destructuring
javascript
// Array destructuring
const [a, b, c] = [1, 2, 3];
const [first, , third] = [1, 2, 3]; // skip element
const [x = 0, y = 0] = [10]; // default values
// Object destructuring
const { name, age } = person;
const { name: fullName, age = 25 } = person; // rename + default
const { address: { city } } = person; // nested
// In function params
function greet({ name, age = 0 }) {
return `${name} is ${age}`;
}Spread & Rest
javascript
// Spread — expand into elements
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1,2,3,4,5]
const obj2 = { ...obj1, key: "val" }; // shallow copy + override
// Rest — collect remaining args
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
const { a, b, ...rest } = { a: 1, b: 2, c: 3, d: 4 };
// rest = { c: 3, d: 4 }Default Parameters
javascript
function greet(name = "World", greeting = "Hello") {
return `${greeting}, ${name}!`;
}
greet(); // "Hello, World!"
greet("Alice"); // "Hello, Alice!"
greet("Alice", "Hi"); // "Hi, Alice!"Classes
javascript
class Animal {
#name; // private field (ES2022)
constructor(name) {
this.#name = name;
}
speak() {
return `${this.#name} makes a noise.`;
}
get name() { return this.#name; }
set name(val) { this.#name = val; }
static create(name) {
return new Animal(name);
}
}
class Dog extends Animal {
constructor(name) {
super(name);
}
speak() {
return `${this.name} barks.`;
}
}Promises
javascript
// Creating a promise
const promise = new Promise((resolve, reject) => {
if (success) resolve(data);
else reject(new Error("Failed"));
});
// Consuming
promise
.then(data => console.log(data))
.catch(err => console.error(err))
.finally(() => console.log("done"));
// Promise combinators
Promise.all([p1, p2, p3]) // all must resolve
Promise.allSettled([p1, p2]) // wait for all
Promise.race([p1, p2]) // first to settle
Promise.any([p1, p2]) // first to resolveAsync/Await
javascript
async function fetchUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) throw new Error("Not found");
const user = await response.json();
return user;
} catch (error) {
console.error("Error:", error.message);
throw error;
}
}
// Parallel requests
async function loadAll() {
const [users, posts] = await Promise.all([
fetch("/api/users").then(r => r.json()),
fetch("/api/posts").then(r => r.json()),
]);
}Modules
javascript
// Named exports
export const PI = 3.14;
export function add(a, b) { return a + b; }
export class Calculator { }
// Default export (one per file)
export default function main() { }
// Import
import { PI, add } from './math.js';
import { add as sum } from './math.js'; // alias
import * as Math from './math.js'; // namespace
import main from './app.js'; // defaultArray Methods
javascript
const nums = [1, 2, 3, 4, 5];
nums.map(x => x * 2) // [2,4,6,8,10]
nums.filter(x => x > 2) // [3,4,5]
nums.reduce((acc, x) => acc + x, 0) // 15
nums.find(x => x > 3) // 4
nums.findIndex(x => x > 3) // 3
nums.some(x => x > 4) // true
nums.every(x => x > 0) // true
nums.includes(3) // true
nums.flat() // flatten 1 level
nums.flatMap(x => [x, x * 2]) // map + flatten
[...new Set(nums)] // remove duplicatesOptional Chaining & Nullish Coalescing
javascript
// Optional chaining ?.
const city = user?.address?.city; // undefined if null
const len = arr?.length ?? 0; // 0 if null/undefined
// Nullish coalescing ??
const name = user.name ?? "Anonymous"; // only for null/undefined
const count = 0 ?? 10; // 0 (not 10!)
const count2 = 0 || 10; // 10 (falsy check)
// Logical assignment
x ??= "default"; // assign if null/undefined
x ||= "default"; // assign if falsy
x &&= transform(x); // assign if truthy10K+ Members Growing Daily
Get Free AI Notes Daily
Join AiTechWorlds on Telegram and get daily AI tips, prompt engineering templates, coding resources, and exclusive content — 100% free!
📚 Free Study Notes🤖 AI Tips Daily⚡ Prompt Templates💻 Coding Resources
Join Free Channel
No spam. Leave anytime.