Quick answer: modern JavaScript is ES5 plus a yearly release since 2015. ES6 (ES2015) brought let/const, arrow functions, classes, modules, promises and destructuring. Later versions added async/await (ES2017), object spread (ES2018), optional chaining ?. and nullish coalescing ?? (ES2020), private class fields and top-level await (ES2022), non-mutating array methods (ES2023), Object.groupBy (ES2024), and Set methods and iterator helpers (ES2025). This cheat sheet covers all of them with short examples.
Bookmark this page as a quick reference for everyday JavaScript, whether you write front-end code, Node.js or React.
JavaScript versions at a glance
| Version | Year | Headline features |
|---|---|---|
| ES6 / ES2015 | 2015 | let/const, arrow functions, classes, modules, promises, template literals, destructuring, Map/Set |
| ES2016 | 2016 | Array.prototype.includes, exponent operator ** |
| ES2017 | 2017 | async/await, Object.entries/values, padStart/padEnd |
| ES2018 | 2018 | Object rest/spread, Promise.finally, async iteration, regex named groups |
| ES2019 | 2019 | flat/flatMap, Object.fromEntries, optional catch binding |
| ES2020 | 2020 | ?., ??, BigInt, Promise.allSettled, dynamic import(), globalThis |
| ES2021 | 2021 | replaceAll, Promise.any, logical assignment ??=, numeric separators |
| ES2022 | 2022 | Class fields, private #members, top-level await, .at(), Object.hasOwn |
| ES2023 | 2023 | toSorted, toReversed, with, findLast |
| ES2024 | 2024 | Object.groupBy, Promise.withResolvers |
| ES2025 | 2025 | Set methods, iterator helpers, Promise.try, JSON modules, RegExp.escape |
Basics
Variables
const name = 'Asha'; // cannot be reassigned (use by default)
let count = 0; // can be reassigned, block-scoped
var old = true; // function-scoped, avoid in modern code
Data types
typeof 'text' // 'string'
typeof 42 // 'number'
typeof 10n // 'bigint'
typeof true // 'boolean'
typeof undefined // 'undefined'
typeof null // 'object' (a historical quirk)
typeof Symbol() // 'symbol'
typeof {} // 'object'
typeof [] // 'object' → use Array.isArray([])
typeof (() => {}) // 'function'
Equality and conversions
0 == '0' // true (loose: converts types)
0 === '0' // false (strict: always prefer ===)
Number('42') // 42
String(42) // '42'
parseInt('42px', 10) // 42
Boolean('') // false. Falsy values: false, 0, -0, 0n, '', null, undefined, NaN
Conditionals and loops
if (age >= 18) { /* ... */ } else if (age > 12) { /* ... */ } else { /* ... */ }
const label = score > 50 ? 'pass' : 'fail';
switch (role) {
case 'admin': grantAll(); break;
case 'editor': grantEdit(); break;
default: grantRead();
}
for (let i = 0; i < 3; i++) {}
for (const item of ['a', 'b']) {} // values of an iterable
for (const key in { a: 1, b: 2 }) {} // keys of an object
while (running) {}
ES6 (ES2015)
Arrow functions
const add = (a, b) => a + b;
const square = n => n * n;
const makeUser = (name) => ({ name, active: true }); // wrap object literals in ()
// Arrow functions don't have their own `this`; they use the surrounding one.
Template literals
const greeting = `Hello, ${name}! You have ${count + 1} messages.`;
const html = `
<li>${item.title}</li>
`;
Destructuring
const { id, title = 'Untitled', author: { name } } = post; // objects, defaults, nested
const [first, , third, ...rest] = [1, 2, 3, 4, 5]; // arrays, skip, rest
[a, b] = [b, a]; // swap
function show({ name, age = 0 }) { /* ... */ } // in parameters
Default, rest and spread
function greet(name = 'guest') {}
function sum(...nums) { return nums.reduce((t, n) => t + n, 0); }
const merged = [...arr1, ...arr2];
Math.max(...[3, 9, 4]); // 9
Enhanced object literals
const age = 30;
const user = {
age, // shorthand property
greet() { return 'hi' },// method shorthand
['key_' + age]: true, // computed key
};
Classes
class Animal {
constructor(name) { this.name = name; }
speak() { return `${this.name} makes a sound`; }
static create(name) { return new Animal(name); }
get label() { return this.name.toUpperCase(); }
}
class Dog extends Animal {
speak() { return `${super.speak()} (woof)`; }
}
Modules
// math.js
export const PI = 3.14159;
export function area(r) { return PI * r * r; }
export default class Calculator {}
// app.js
import Calculator, { area, PI as pi } from './math.js';
import * as math from './math.js';
Promises
fetch('/api/users')
.then((res) => res.json())
.then((users) => console.log(users))
.catch((err) => console.error(err));
Promise.all([p1, p2]); // all must succeed
Promise.race([p1, p2]); // first to settle wins
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
Map, Set, Symbol
const map = new Map([['a', 1]]);
map.set('b', 2); map.get('a'); map.has('b'); map.size;
const set = new Set([1, 2, 2, 3]); // {1, 2, 3}
const unique = [...new Set(array)];
const id = Symbol('id'); // unique property key
Iterators and generators
function* range(start, end) {
for (let i = start; i < end; i++) yield i;
}
[...range(0, 3)]; // [0, 1, 2]
ES2016
[1, 2, 3].includes(2); // true
2 ** 10; // 1024
ES2017
async / await
async function loadUser(id) {
try {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (err) {
console.error('Failed to load user', err);
}
}
// Run in parallel, not one after another
const [user, orders] = await Promise.all([getUser(id), getOrders(id)]);
Object helpers and string padding
Object.keys({ a: 1, b: 2 }); // ['a', 'b']
Object.values({ a: 1, b: 2 }); // [1, 2]
Object.entries({ a: 1, b: 2 }); // [['a', 1], ['b', 2]]
'5'.padStart(3, '0'); // '005'
'ab'.padEnd(4, '.'); // 'ab..'
ES2018
const { password, ...safeUser } = user; // object rest
const updated = { ...user, active: false }; // object spread (shallow copy)
fetchData().finally(() => hideSpinner()); // runs on success or failure
for await (const chunk of stream) { /* ... */ } // async iteration
const m = '2026-11-18'.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/);
m.groups.year; // '2026' (named capture groups)
ES2019
[1, [2, [3, [4]]]].flat(2); // [1, 2, 3, [4]]
['a b', 'c'].flatMap((s) => s.split(' ')); // ['a', 'b', 'c']
Object.fromEntries([['a', 1], ['b', 2]]); // { a: 1, b: 2 }
' hi '.trimStart(); ' hi '.trimEnd();
try { risky(); } catch { /* error variable is optional */ }
ES2020
user?.address?.city; // undefined instead of an error
user.getName?.(); // call only if the method exists
items?.[0];
const port = config.port ?? 3000; // only null/undefined fall back (0 and '' are kept)
const big = 9007199254740993n; // BigInt
await Promise.allSettled([p1, p2]); // results of every promise, never rejects
const module = await import('./heavy.js'); // dynamic import (code splitting)
globalThis.setTimeout; // the global object everywhere
[...'a1b2'.matchAll(/\d/g)].map((m) => m[0]); // ['1', '2']
ES2021
'a-b-c'.replaceAll('-', '/'); // 'a/b/c'
await Promise.any([mirror1, mirror2]); // first to succeed
const budget = 1_000_000; // numeric separators
options.timeout ??= 5000; // assign if null/undefined
user.name ||= 'Anonymous'; // assign if falsy
flags.ready &&= isValid(); // assign if truthy
ES2022
class Counter {
count = 0; // public field
#secret = 'hidden'; // private field
static instances = 0;
static { Counter.instances = 0; } // static initialisation block
#log() { console.log(this.#secret); } // private method
increment() { this.count++; }
static isCounter(obj) { return #secret in obj; } // private brand check
}
const config = await loadConfig(); // top-level await in modules
[10, 20, 30].at(-1); // 30
Object.hasOwn(obj, 'key'); // safer than hasOwnProperty
throw new Error('Save failed', { cause: err }); // error cause
ES2023: change arrays without mutating them
const nums = [3, 1, 2];
nums.toSorted(); // [1, 2, 3] (nums unchanged)
nums.toReversed(); // [2, 1, 3]
nums.with(0, 99); // [99, 1, 2]
nums.toSpliced(1, 1); // [3, 2]
nums.findLast((n) => n > 1); // 2
nums.findLastIndex((n) => n > 1); // 2
These are ideal for React and other state-based UIs, where you should not mutate state directly.
ES2024
const people = [{ name: 'A', team: 'dev' }, { name: 'B', team: 'ops' }, { name: 'C', team: 'dev' }];
Object.groupBy(people, (p) => p.team);
// { dev: [{...A}, {...C}], ops: [{...B}] }
Map.groupBy(people, (p) => p.team); // same, as a Map
const { promise, resolve, reject } = Promise.withResolvers();
'text'.isWellFormed(); // checks for lone surrogate characters
ES2025
const a = new Set([1, 2, 3]);
const b = new Set([3, 4]);
a.union(b); // Set {1, 2, 3, 4}
a.intersection(b); // Set {3}
a.difference(b); // Set {1, 2}
a.symmetricDifference(b); // Set {1, 2, 4}
a.isSubsetOf(b); // false
// Iterator helpers: lazy map/filter/take on any iterator
const firstEvens = [1, 2, 3, 4, 5, 6].values()
.filter((n) => n % 2 === 0)
.map((n) => n * 10)
.take(2)
.toArray(); // [20, 40]
await Promise.try(() => mightThrowOrReturnPromise());
import data from './data.json' with { type: 'json' }; // JSON modules
new RegExp(RegExp.escape('1+1=2')); // escape user input
Check browser and Node.js support before relying on the newest features, or use a build tool that transpiles them.
Arrays: the methods you use every day
const nums = [1, 2, 3, 4];
nums.map((n) => n * 2); // [2, 4, 6, 8]
nums.filter((n) => n % 2); // [1, 3]
nums.reduce((sum, n) => sum + n, 0); // 10
nums.find((n) => n > 2); // 3
nums.findIndex((n) => n > 2); // 2
nums.some((n) => n > 3); // true
nums.every((n) => n > 0); // true
nums.slice(1, 3); // [2, 3] (copy)
nums.splice(1, 1); // removes 1 item (mutates)
nums.join(', '); // '1, 2, 3, 4'
Array.from({ length: 3 }, (_, i) => i); // [0, 1, 2]
[...nums].sort((a, b) => a - b); // numeric sort (default sort is alphabetical)
Strings
const s = 'Hello, World';
s.length; s.toUpperCase(); s.toLowerCase();
s.includes('World'); s.startsWith('He'); s.endsWith('d');
s.indexOf('o'); s.slice(0, 5); s.split(', ');
s.replace('World', 'JS'); s.trim(); s.repeat(2);
Objects
const copy = { ...obj }; // shallow copy
const deep = structuredClone(obj); // deep copy
Object.assign(target, source);
Object.freeze(config); // make read-only
JSON.stringify(obj, null, 2); // to JSON
JSON.parse('{"a":1}'); // from JSON
Error handling
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = 'ValidationError';
this.field = field;
}
}
try {
validate(form);
} catch (err) {
if (err instanceof ValidationError) showFieldError(err.field, err.message);
else throw err;
} finally {
setLoading(false);
}
DOM and browser essentials
const btn = document.querySelector('#save');
const items = document.querySelectorAll('.item');
btn.addEventListener('click', (e) => { e.preventDefault(); save(); });
el.classList.add('active'); el.classList.toggle('open');
el.textContent = 'Safe text'; // prefer over innerHTML for user input
el.dataset.id; // reads data-id="..."
localStorage.setItem('theme', 'dark');
const res = await fetch('/api/items', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'New' }),
});
Timers and the event loop
setTimeout(() => console.log('later'), 1000);
const id = setInterval(tick, 1000); clearInterval(id);
queueMicrotask(() => {}); // runs before the next macrotask
// Order: synchronous code → microtasks (promises) → macrotasks (timers, events)
Common gotchas
0.1 + 0.2 !== 0.3: use integers (paise, cents) or a rounding helper for money.[] + []is''and[] == falseistrue: always use===.sort()sorts as strings by default: pass a compare function for numbers.- Object and array copies with spread are shallow: use
structuredClonefor deep copies. thisinside a regular function depends on how it is called; arrow functions inherit it.- Forgetting
awaitreturns a pending promise instead of the value.
Conclusion
Modern JavaScript is far more pleasant than the ES5 code many developers learned first. Use const and let, arrow functions, destructuring and modules from ES6; async/await for asynchronous code; ?. and ?? to handle missing values safely; private fields and top-level await for cleaner modules; and the non-mutating array methods for predictable state. Keep this cheat sheet open while you code, and check runtime support before using the very latest features.



