JavaScript Cheatsheet ES2024+
1

Variables & Types

Déclaration

JS
const PI = 3.14;        // immuable (binding, pas valeur)
let count = 0;           // réassignable, block-scoped
var legacy = "éviter";    // function-scoped, hoisted → ne plus utiliser

// const pour tout par défaut, let si réassignation nécessaire

Types primitifs (7) + Object

JS
typeof "hello"       // "string"
typeof 42             // "number"    (64-bit float, pas d'int)
typeof 42n            // "bigint"    (précision arbitraire)
typeof true           // "boolean"
typeof undefined      // "undefined"
typeof null           // "object"    ⚠️ bug historique
typeof Symbol()       // "symbol"
typeof {}             // "object"
typeof []             // "object"    → utiliser Array.isArray()
typeof function(){}  // "function"

Conversions & Vérifications

JS
// Vers nombre
Number("42")          // 42
parseInt("42px", 10)  // 42
parseFloat("3.14")    // 3.14
+"42"                  // 42 (unary +)

// Vers string
String(42)            // "42"
(42).toString(16)     // "2a" (base 16)

// Vers booléen — valeurs falsy :
// false, 0, -0, 0n, "", null, undefined, NaN
Boolean("")           // false
!!"hello"             // true

// Vérifications
Number.isFinite(x)    Number.isNaN(x)    Number.isInteger(x)
Array.isArray([])     // true
x instanceof Date     // true si x est une Date
2

Opérateurs

JS
// Comparaison
===  !==            // strict (type + valeur) → TOUJOURS utiliser
==   !=             // loose (coercion) → éviter

// Logiques
&&   ||   !         // ET, OU, NON
a ?? b              // Nullish coalescing : b si a est null/undefined (pas 0/"")
a ??= b             // Assign si null/undefined
a ||= b             // Assign si falsy
a &&= b             // Assign si truthy

// Optional chaining
obj?.prop            // undefined si obj est null/undefined
obj?.[expr]          // accès dynamique
obj?.method()        // appel conditionnel
arr?.[0]             // accès tableau

// Arithmétique
+  -  *  /  %       // classiques
**                   // exponentiation : 2 ** 3 === 8

// Bitwise
&  |  ^  ~  <<  >>  >>>

// Ternaire
const msg = age >= 18 ? "majeur" : "mineur";

// Virgule, void, typeof, in, instanceof, delete
"name" in obj        // true si propriété existe
delete obj.prop       // supprime une propriété
3

Structures de contrôle

JS
// if / else if / else
if (x > 0) { ... }
else if (x === 0) { ... }
else { ... }

// switch
switch (action) {
  case "start": run(); break;
  case "stop":  halt(); break;
  default: idle();
}

// Boucles
for (let i = 0; i < n; i++) { ... }

for (const item of iterable) { ... }  // tableaux, strings, Map, Set
for (const key in obj) { ... }        // clés d'objet (+ proto) — éviter

while (cond) { ... }
do { ... } while (cond);

// Contrôle de boucle
break       // sort de la boucle
continue    // itération suivante
break label // sort d'une boucle nommée

// for...of avec index
for (const [i, val] of arr.entries()) { ... }
4

Fonctions

JS
// Déclaration (hoisted)
function add(a, b) { return a + b; }

// Expression
const add = function(a, b) { return a + b; };

// Arrow function (pas de this propre, pas de arguments)
const add = (a, b) => a + b;              // return implicite
const greet = name => `Hello ${name}`;    // 1 param : pas de ()
const getObj = () => ({ key: "val" });     // retourner un objet : ({})

// Paramètres par défaut
function greet(name = "World") { ... }

// Rest parameters
function sum(...nums) { return nums.reduce((a,b) => a+b, 0); }

// IIFE (Immediately Invoked)
(function() { ... })();
(() => { ... })();

// Closures
function counter() {
  let n = 0;
  return { inc: () => ++n, get: () => n };
}

// Currying
const multiply = a => b => a * b;
const double = multiply(2);  // double(5) === 10

// Arguments object (pas dans arrow functions)
function legacy() { return arguments.length; }
5

Strings

JS
// Template literals
const msg = `Hello ${name}, tu as ${age} ans`;
const multi = `ligne 1
ligne 2`;

// Tagged templates
function html(strings, ...vals) { /* custom processing */ }
html`<p>${name}</p>`;

// Méthodes courantes
s.length                      // longueur
s.at(-1)                      // dernier char (ES2022)
s.includes("abc")             // true/false
s.startsWith("He")            // true/false
s.endsWith(".js")              // true/false
s.indexOf("abc")              // index ou -1
s.slice(1, 5)                 // extraction (négatifs ok)
s.substring(1, 5)             // comme slice mais pas de négatifs
s.toUpperCase()  s.toLowerCase()
s.trim()  s.trimStart()  s.trimEnd()
s.padStart(5, "0")            // "00042"
s.padEnd(10, ".")             // "hello....."
s.repeat(3)                   // "abcabcabc"
s.replace("a", "b")          // premier seulement
s.replaceAll("a", "b")       // tous
s.split(",")                   // → array
s.match(/regex/)              // → array ou null
s.matchAll(/regex/g)          // → iterator
s.search(/regex/)             // → index ou -1
s.normalize("NFC")            // normalisation Unicode
s.codePointAt(0)              // code Unicode
String.fromCodePoint(128512)  // emoji à partir du code

// Chaîne immutable — chaque méthode retourne une NOUVELLE chaîne
6

Numbers & Math

JS
// Littéraux
255    0xFF    0o377    0b11111111    // décimal, hex, octal, binaire
1_000_000                                  // séparateur numérique (ES2021)
42n                                        // BigInt

// Constantes
Number.MAX_SAFE_INTEGER   // 2^53 - 1
Number.MIN_SAFE_INTEGER   Number.EPSILON
Infinity   -Infinity   NaN

// Vérifications
Number.isNaN(x)           // ≠ isNaN() global (coercion)
Number.isFinite(x)
Number.isInteger(x)
Number.isSafeInteger(x)

// Formatage
(3.14159).toFixed(2)      // "3.14"
(1234.5).toLocaleString("fr-FR")  // "1 234,5"
(255).toString(16)        // "ff"

// Math
Math.round(x)  Math.ceil(x)  Math.floor(x)  Math.trunc(x)
Math.abs(x)    Math.sign(x)  Math.sqrt(x)   Math.cbrt(x)
Math.pow(x,n)  Math.log(x)   Math.log2(x)   Math.log10(x)
Math.min(...arr)  Math.max(...arr)
Math.random()              // [0, 1)
Math.floor(Math.random() * (max - min + 1)) + min  // entier [min, max]
Math.PI  Math.E
Math.hypot(a, b)           // √(a² + b²)
Math.clz32(x)              // leading zeros 32-bit
7

Arrays

Création

JS
const a = [1, 2, 3];
const b = Array.from({ length: 5 }, (_, i) => i);  // [0,1,2,3,4]
const c = Array.from("hello");                      // ["h","e","l","l","o"]
const d = Array(5).fill(0);                          // [0,0,0,0,0]
const e = Array.of(1, 2, 3);                        // [1,2,3]

Méthodes qui MODIFIENT le tableau (mutating)

JS
arr.push(...items)       // ajoute à la fin → retourne length
arr.pop()                // retire le dernier → retourne l'élément
arr.unshift(...items)    // ajoute au début
arr.shift()              // retire le premier
arr.splice(i, del, ...add) // supprime/insère à l'index i
arr.sort((a,b) => a-b)   // tri en place (⚠️ alphabétique par défaut)
arr.reverse()            // inverse en place
arr.fill(val, start, end) // remplit
arr.copyWithin(t, s, e)  // copie interne

Méthodes qui RETOURNENT un nouveau tableau (non-mutating)

JS
arr.map(x => x * 2)          // transforme chaque élément
arr.filter(x => x > 0)        // garde les éléments truthy
arr.reduce((acc, x) => acc + x, 0)  // accumule
arr.reduceRight(...)           // de droite à gauche
arr.flat(2)                    // aplatit 2 niveaux
arr.flatMap(x => [x, x*2])    // map + flat(1)
arr.slice(start, end)          // extraction
arr.concat(other)              // fusion
[...a, ...b]                    // fusion (spread)

// ES2023 — versions non-mutating de sort/reverse/splice
arr.toSorted((a,b) => a-b)    // sort sans muter
arr.toReversed()               // reverse sans muter
arr.toSpliced(i, del, ...add)  // splice sans muter
arr.with(index, value)         // remplace un index sans muter

Recherche & Test

JS
arr.find(x => x > 5)          // 1er élément correspondant
arr.findIndex(x => x > 5)     // index du 1er correspondant
arr.findLast(x => x > 5)      // dernier correspondant (ES2023)
arr.findLastIndex(...)         // index du dernier (ES2023)
arr.includes(val)              // true/false
arr.indexOf(val)               // index ou -1
arr.every(x => x > 0)         // tous vérifient ?
arr.some(x => x > 0)          // au moins un ?

// Itération
arr.forEach((val, i, arr) => { ... })
arr.entries()  arr.keys()  arr.values()
arr.at(-1)                      // dernier élément (ES2022)

// Conversion
arr.join(", ")                 // → string
Array.isArray(arr)             // true
structuredClone(arr)           // deep clone
8

Objets

JS
// Création
const obj = { name: "Alice", age: 30 };
const obj2 = Object.create(proto);

// Shorthand
const name = "Alice";
const obj = { name, greet() { return `Hi ${this.name}`; } };

// Computed property names
const key = "color";
const obj = { [key]: "blue", [`get_${key}`]() { return this[key]; } };

// Accès
obj.name       obj["name"]       obj?.nested?.prop

// Méthodes statiques
Object.keys(obj)              // ["name", "age"]
Object.values(obj)            // ["Alice", 30]
Object.entries(obj)           // [["name","Alice"], ["age",30]]
Object.fromEntries(entries)   // inverse de entries
Object.assign(target, ...sources) // shallow merge (mute target)
{ ...obj1, ...obj2 }          // shallow merge (immutable)
structuredClone(obj)          // deep clone

// Figer un objet
Object.freeze(obj)            // lecture seule (shallow)
Object.seal(obj)              // pas d'ajout/suppression, modif ok
Object.isFrozen(obj)          Object.isSealed(obj)

// Property descriptors
Object.defineProperty(obj, "prop", {
  value: 42, writable: false, enumerable: true, configurable: false
});
Object.getOwnPropertyDescriptor(obj, "prop")

// Vérifications
"name" in obj                // true (inclut prototype)
obj.hasOwnProperty("name")   // true (propre seulement)
Object.hasOwn(obj, "name")   // ES2022 — préférer

// Prototype
Object.getPrototypeOf(obj)
Object.setPrototypeOf(obj, proto)
obj instanceof Constructor
9

Map, Set, WeakMap, WeakSet

JS
// ── Map (clé → valeur, clés de tout type) ──
const map = new Map([  ["a", 1], ["b", 2]  ]);
map.set(key, val)     map.get(key)     map.has(key)
map.delete(key)       map.clear()      map.size
map.forEach((val, key) => { ... })
for (const [k, v] of map) { ... }
map.keys()   map.values()   map.entries()

// Map vs Object : clés non-string, ordre d'insertion garanti,
// .size, itérable, pas de pollution prototype

// ── Set (valeurs uniques) ──
const set = new Set([1, 2, 3, 2]);  // {1, 2, 3}
set.add(val)   set.has(val)   set.delete(val)   set.clear()   set.size
[...new Set(arr)]               // dédupliquer un array

// ES2025 — Set methods
setA.union(setB)                // A ∪ B
setA.intersection(setB)         // A ∩ B
setA.difference(setB)           // A \ B
setA.symmetricDifference(setB)  // (A \ B) ∪ (B \ A)
setA.isSubsetOf(setB)           // A ⊆ B
setA.isSupersetOf(setB)         // A ⊇ B
setA.isDisjointFrom(setB)       // A ∩ B = ∅

// ── WeakMap / WeakSet ──
// Clés = objets uniquement, garbage-collectées si plus de référence
// Pas itérable, pas de .size, pas de .clear()
const wm = new WeakMap();  wm.set(obj, data);
const ws = new WeakSet();  ws.add(obj);
10

Destructuring & Spread

JS
// ── Array destructuring ──
const [a, b, c] = [1, 2, 3];
const [first, , third] = arr;          // skip 2e
const [head, ...rest] = arr;           // rest = reste du tableau
const [x = 0, y = 0] = [];             // valeurs par défaut

// Swap
[a, b] = [b, a];

// ── Object destructuring ──
const { name, age } = user;
const { name: userName, age: userAge } = user;  // renommer
const { a = 1, b = 2 } = obj;                   // défaut
const { nested: { deep } } = obj;                // imbriqué
const { x, ...others } = obj;                    // rest

// Dans les paramètres de fonction
function greet({ name, age = 18 }) { ... }
greet({ name: "Alice" });

// ── Spread ──
const arr2 = [...arr1, 4, 5];          // arrays
const obj2 = { ...obj1, extra: true }; // objects (shallow)
Math.max(...numbers);                  // dans un appel
11

Classes & OOP

JS
class Animal {
  // Champs (ES2022)
  name;
  #sound;                        // champ privé
  static count = 0;             // champ statique
  static #instances = [];        // statique privé

  constructor(name, sound) {
    this.name = name;
    this.#sound = sound;
    Animal.count++;
    Animal.#instances.push(this);
  }

  // Méthode
  speak() { return `${this.name} dit ${this.#sound}`; }

  // Getter / Setter
  get info() { return `${this.name}`; }
  set info(val) { this.name = val; }

  // Méthode statique
  static getCount() { return Animal.count; }

  // Static initialization block (ES2022)
  static { console.log("Animal class loaded"); }
}

// Héritage
class Dog extends Animal {
  breed;
  constructor(name, breed) {
    super(name, "Woof");         // appel parent OBLIGATOIRE avant this
    this.breed = breed;
  }
  speak() { return super.speak() + " !"; }  // override
}

// Vérification
dog instanceof Dog      // true
dog instanceof Animal   // true

// Mixins (pas de multiple inheritance en JS)
const Serializable = (Base) => class extends Base {
  toJSON() { return JSON.stringify(this); }
};
12

Promises & Async/Await

JS
// ── Créer une Promise ──
const p = new Promise((resolve, reject) => {
  setTimeout(() => resolve("done"), 1000);
});

// ── Chaîner ──
p.then(val => transform(val))
 .then(val => save(val))
 .catch(err => console.error(err))
 .finally(() => cleanup());

// ── Combinateurs ──
Promise.all([p1, p2, p3])        // toutes ok → array résultats, 1 fail → reject
Promise.allSettled([p1, p2])     // attend toutes, jamais reject
Promise.race([p1, p2])           // 1ère terminée (resolve ou reject)
Promise.any([p1, p2])            // 1ère résolue (ignore rejets sauf si tous)
Promise.resolve(val)             // crée une promise résolue
Promise.reject(err)              // crée une promise rejetée
Promise.withResolvers()          // ES2024 : { promise, resolve, reject }

// ── Async/Await ──
async function fetchData() {
  try {
    const res = await fetch(url);
    const data = await res.json();
    return data;
  } catch (err) {
    console.error(err);
  }
}

// Parallèle avec await
const [users, posts] = await Promise.all([
  fetchUsers(), fetchPosts()
]);

// Top-level await (ESM only)
const config = await loadConfig();

// for await...of (async iteration)
for await (const chunk of readableStream) { ... }
13

Modules (ESM)

JS
// ── Export ──
export const PI = 3.14;
export function add(a, b) { return a + b; }
export class User { ... }
export default class App { ... }        // 1 par module max
export { helper as utils };              // renommer

// ── Import ──
import App from './app.js';              // default
import { add, PI } from './math.js';    // named
import { add as sum } from './math.js'; // renommer
import * as math from './math.js';     // namespace
import './styles.css';                   // side-effect

// ── Dynamic import ──
const module = await import('./heavy.js');  // lazy loading
const { default: App, helper } = await import('./app.js');

// ── Re-export ──
export { add } from './math.js';
export * from './utils.js';
export { default } from './app.js';

// import.meta
import.meta.url                            // URL du module courant
14

Iterators & Generators

JS
// ── Iterable protocol ──
const iterable = {
  [Symbol.iterator]() {
    let i = 0;
    return { next() { return i < 3 ? { value: i++, done: false } : { done: true }; } };
  }
};
for (const v of iterable) { ... }

// ── Generator ──
function* range(start, end) {
  for (let i = start; i < end; i++) yield i;
}
const nums = [...range(0, 5)];  // [0,1,2,3,4]

// yield* : délégation
function* concat(a, b) { yield* a; yield* b; }

// ── Async Generator ──
async function* fetchPages(url) {
  let page = 1;
  while (true) {
    const data = await fetch(`${url}?page=${page++}`).then(r => r.json());
    if (!data.length) return;
    yield data;
  }
}
for await (const page of fetchPages(url)) { ... }

// Iterator helpers (ES2025)
iterator.map(fn)  .filter(fn)  .take(n)  .drop(n)  .toArray()
15

Proxy & Reflect

JS
const handler = {
  get(target, prop, receiver) {
    console.log(`Accès: ${prop}`);
    return Reflect.get(target, prop, receiver);
  },
  set(target, prop, value, receiver) {
    if (prop === "age" && value < 0) throw new Error("Invalid");
    return Reflect.set(target, prop, value, receiver);
  },
  has(target, prop) { ... },
  deleteProperty(target, prop) { ... },
  apply(target, thisArg, args) { ... },   // pour les fonctions
  construct(target, args) { ... },         // pour new
};

const proxy = new Proxy(target, handler);
const revocable = Proxy.revocable(target, handler);
revocable.revoke();  // désactive le proxy
16

Symbols

JS
const sym = Symbol("description");        // unique à chaque appel
const globalSym = Symbol.for("shared");  // registre global
Symbol.keyFor(globalSym);                // "shared"

// Well-known symbols
Symbol.iterator      // rend un objet itérable
Symbol.asyncIterator // async itérable
Symbol.hasInstance   // personnalise instanceof
Symbol.toPrimitive   // conversion vers primitif
Symbol.toStringTag   // personnalise Object.prototype.toString
Symbol.species       // constructeur pour méthodes dérivées
17

Regex

JS
// Création
const re = /pattern/flags;
const re = new RegExp("pattern", "flags");

// Flags
g   // global          i   // insensible casse
m   // multiline       s   // dotAll (. matche \n)
u   // unicode         v   // unicodeSets (ES2024)
d   // hasIndices      y   // sticky

// Méthodes
re.test(str)              // → boolean
re.exec(str)              // → match array ou null
str.match(re)             // → array (sans g) ou tous les matchs (avec g)
str.matchAll(re)          // → iterator de match arrays (avec g)
str.replace(re, rep)      // remplacement
str.replaceAll(re, rep)   // tous (re doit avoir flag g)
str.search(re)            // → index ou -1
str.split(re)             // → array

// Groupes nommés
const re = /(?<year>\d{4})-(?<month>\d{2})/;
const { groups: { year, month } } = re.exec("2024-06");

// Lookbehind / Lookahead
/(?<=@)\w+/    // lookbehind positif
/(?<!@)\w+/    // lookbehind négatif
/\w+(?=@)/     // lookahead positif
/\w+(?!@)/     // lookahead négatif

// Classes courantes
\d  \D   // chiffre / non-chiffre
\w  \W   // mot [a-zA-Z0-9_] / non-mot
\s  \S   // espace / non-espace
\b  \B   // word boundary / non-boundary
.        // tout sauf \n (sauf flag s)
^  $     // début / fin
18

Date & Intl

JS
// ── Date ──
const now = new Date();
new Date("2024-06-15")      new Date(2024, 5, 15)  // mois 0-indexé !
Date.now()                   // timestamp ms

now.getFullYear()  .getMonth()  .getDate()  .getDay()
now.getHours()    .getMinutes()  .getSeconds()  .getMilliseconds()
now.getTime()     // timestamp ms
now.toISOString() // "2024-06-15T12:00:00.000Z"
now.toLocaleDateString("fr-FR")  // "15/06/2024"

// ── Intl (internationalisation) ──
new Intl.DateTimeFormat("fr-FR", {
  weekday: "long", year: "numeric", month: "long", day: "numeric"
}).format(date);

new Intl.NumberFormat("fr-FR", {
  style: "currency", currency: "EUR"
}).format(1234.56);  // "1 234,56 €"

new Intl.RelativeTimeFormat("fr").format(-3, "day");  // "il y a 3 jours"
new Intl.PluralRules("fr").select(1);   // "one"
new Intl.ListFormat("fr").format(["a","b","c"]);  // "a, b et c"
new Intl.Collator("fr").compare(a, b);  // tri locale-aware
new Intl.Segmenter("fr", { granularity: "word" })  // découpage mot
19

JSON

JS
JSON.stringify(obj)                      // → string JSON
JSON.stringify(obj, null, 2)             // → pretty print
JSON.stringify(obj, ["name", "age"])     // → seulement ces clés
JSON.stringify(obj, (key, val) => {      // replacer function
  if (key === "password") return undefined;
  return val;
});

JSON.parse(str)                           // → objet JS
JSON.parse(str, (key, val) => {           // reviver function
  if (key === "date") return new Date(val);
  return val;
});

// Méthode toJSON (custom serialization)
class User {
  toJSON() { return { name: this.name }; }
}

// structuredClone — deep clone (gère Date, Map, Set, ArrayBuffer, etc.)
const copy = structuredClone(obj);

// JSON.parse(JSON.stringify(obj)) — deep clone basique
// ⚠️ perd functions, undefined, Date→string, Map/Set→{}
20

Error Handling

JS
// try / catch / finally
try {
  riskyOperation();
} catch (err) {
  console.error(err.message, err.stack);
} finally {
  cleanup();  // toujours exécuté
}

// Types d'erreur natifs
new Error("msg")           new TypeError("msg")
new RangeError("msg")      new ReferenceError("msg")
new SyntaxError("msg")     new URIError("msg")
new AggregateError([err1, err2])

// Custom error
class AppError extends Error {
  constructor(message, code) {
    super(message);
    this.name = "AppError";
    this.code = code;
  }
}

// Error cause (ES2022)
throw new Error("Failed", { cause: originalError });

// Catch sans binding
try { ... } catch { /* pas de variable err */ }
21

DOM

JS
// ── Sélection ──
document.querySelector(".class")          // 1er match
document.querySelectorAll("div.card")      // NodeList (forEach ok)
document.getElementById("id")
document.getElementsByClassName("cls")     // HTMLCollection (live)

// ── Créer / Modifier ──
const el = document.createElement("div");
el.textContent = "Hello";              // texte sûr
el.innerHTML = "<b>Bold</b>";          // ⚠️ XSS si contenu non fiable
el.id = "myDiv";
el.classList.add("active");
el.classList.remove("hidden");
el.classList.toggle("open");
el.classList.contains("active");
el.setAttribute("data-id", "42");
el.getAttribute("data-id");
el.dataset.id;                          // accès data-id
el.style.color = "red";
el.style.cssText = "color:red; font-size:16px;";

// ── Insérer / Supprimer ──
parent.appendChild(el);
parent.append(el, text, el2);           // multiple, strings ok
parent.prepend(el);
el.before(sibling);   el.after(sibling);
el.replaceWith(newEl);
el.remove();
parent.insertAdjacentHTML("beforeend", html);

// ── Traversal ──
el.parentElement      el.children
el.firstElementChild  el.lastElementChild
el.nextElementSibling el.previousElementSibling
el.closest(".parent") // ancêtre le plus proche
el.matches(".class")  // teste un sélecteur

// ── Dimensions ──
el.getBoundingClientRect()  // { top, left, width, height, ... }
el.offsetWidth  el.offsetHeight
el.scrollTop   el.scrollLeft
window.innerWidth  window.innerHeight
22

Events

JS
// Ajouter / Retirer
el.addEventListener("click", handler);
el.addEventListener("click", handler, { once: true, passive: true, capture: true });
el.removeEventListener("click", handler);

// Event object
function handler(e) {
  e.preventDefault();      // empêche l'action par défaut
  e.stopPropagation();     // arrête la propagation
  e.target                 // élément cliqué
  e.currentTarget          // élément sur lequel le listener est attaché
  e.type                   // "click"
}

// Event delegation
document.querySelector(".list").addEventListener("click", (e) => {
  const item = e.target.closest(".item");
  if (!item) return;
  // traiter item
});

// Custom events
const event = new CustomEvent("myevent", { detail: { id: 42 }, bubbles: true });
el.dispatchEvent(event);

// AbortController (annuler des listeners)
const ctrl = new AbortController();
el.addEventListener("click", handler, { signal: ctrl.signal });
ctrl.abort();  // retire tous les listeners attachés avec ce signal

// Événements courants
// click, dblclick, mousedown/up, mouseover/out, mouseenter/leave
// keydown, keyup, keypress (deprecated)
// input, change, submit, focus, blur
// scroll, resize, DOMContentLoaded, load
// touchstart, touchmove, touchend
// dragstart, drag, drop
23

Fetch & HTTP

JS
// ── GET ──
const res = await fetch("https://api.example.com/data");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();

// ── POST ──
const res = await fetch(url, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "Alice" }),
});

// ── Upload fichier ──
const form = new FormData();
form.append("file", fileInput.files[0]);
await fetch(url, { method: "POST", body: form });

// ── Annuler une requête ──
const ctrl = new AbortController();
setTimeout(() => ctrl.abort(), 5000);  // timeout 5s
await fetch(url, { signal: ctrl.signal });

// ── Response methods ──
res.json()   res.text()   res.blob()   res.arrayBuffer()
res.formData()   res.clone()
res.ok   res.status   res.statusText   res.headers

// ── Streaming ──
const reader = res.body.getReader();
while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  processChunk(value);
}
24

Storage & Web APIs

JS
// ── localStorage / sessionStorage ──
localStorage.setItem("key", JSON.stringify(val));
const val = JSON.parse(localStorage.getItem("key"));
localStorage.removeItem("key");   localStorage.clear();

// ── URL API ──
const url = new URL("https://example.com/path?q=hello");
url.hostname  url.pathname  url.searchParams.get("q")
url.searchParams.set("page", "2");

// ── Timer ──
const id = setTimeout(fn, ms);   clearTimeout(id);
const id = setInterval(fn, ms);  clearInterval(id);
requestAnimationFrame(fn);       // animation 60fps
queueMicrotask(fn);              // microtask queue

// ── Clipboard ──
await navigator.clipboard.writeText("Hello");
const text = await navigator.clipboard.readText();

// ── IntersectionObserver (lazy load, infinite scroll) ──
const obs = new IntersectionObserver((entries) => {
  entries.forEach(e => { if (e.isIntersecting) loadImage(e.target); });
}, { threshold: 0.1 });
obs.observe(el);

// ── MutationObserver ──
const mo = new MutationObserver(mutations => { ... });
mo.observe(el, { childList: true, subtree: true });

// ── ResizeObserver ──
new ResizeObserver(entries => { ... }).observe(el);

// ── Web Workers ──
const worker = new Worker("worker.js");
worker.postMessage(data);
worker.onmessage = (e) => console.log(e.data);
25

ES2022 – ES2024 Nouveautés

ES2022
// Top-level await
const data = await fetch(url);

// Class fields, private, static blocks
class C { #x; static { /* init */ } }

// .at() — accès négatif
[1,2,3].at(-1)  // 3

// Object.hasOwn()
Object.hasOwn(obj, "key")

// Error cause
throw new Error("msg", { cause: err });

// RegExp match indices (flag d)
/(?<name>\w+)/d.exec(str).indices
ES2023
// Array non-mutating methods
arr.toSorted()   arr.toReversed()   arr.toSpliced(i,n)   arr.with(i, val)

// findLast / findLastIndex
arr.findLast(x => x > 0)
arr.findLastIndex(x => x > 0)

// Hashbang support
#!/usr/bin/env node
ES2024
// Promise.withResolvers()
const { promise, resolve, reject } = Promise.withResolvers();

// Object.groupBy / Map.groupBy
Object.groupBy(items, item => item.category);
Map.groupBy(items, item => item.category);

// RegExp v flag (unicodeSets)
/[\p{Script=Greek}&&\p{Letter}]/v

// ArrayBuffer.prototype.resize / transfer
const buf = new ArrayBuffer(8, { maxByteLength: 16 });
buf.resize(12);

// Atomics.waitAsync()
Atomics.waitAsync(int32Array, 0, 0)
26

Bonnes pratiques

Conseils
// ✅ const par défaut, let si nécessaire, jamais var
// ✅ === au lieu de ==
// ✅ Arrow functions pour les callbacks
// ✅ Template literals au lieu de concaténation
// ✅ Destructuring pour extraire les données
// ✅ Optional chaining (?.) et nullish coalescing (??)
// ✅ for...of au lieu de for classique quand possible
// ✅ Array methods (map, filter, reduce) au lieu de boucles manuelles
// ✅ async/await au lieu de .then() chains
// ✅ Modules ESM (import/export)
// ✅ structuredClone() pour deep clone
// ✅ AbortController pour annuler fetch/listeners
// ✅ Méthodes non-mutating (toSorted, toReversed, with)
// ✅ Object.groupBy au lieu de reduce pour grouper
// ✅ Error cause pour chaîner les erreurs

// ❌ eval() — jamais
// ❌ with — obsolète
// ❌ arguments — utiliser ...rest
// ❌ var — utiliser const/let
// ❌ for...in sur arrays — utiliser for...of
// ❌ innerHTML avec données utilisateur — XSS
// ❌ == et != — coercion implicite
// ❌ new Array(n) — utiliser Array.from ou Array(n).fill()

JavaScript Cheatsheet Complet — ES2024+ — 2026