Modern syntax, array methods, and async logic.
let / const / varconst PI = 3.14; let count = 0; // never use var?. Optional chainingconst city = user?.address?.city ?? 'Unknown';?? Nullish coalescingconst port = config.port ?? 3000; // 0 is valid!??= &&= ||= (Logical assign)user.name ??= 'Anonymous'; cache ||= fetchData();Destructuringconst { id, name: fullName = 'N/A', ...rest } = user;Spread / Rest (...)const merged = {...defaults, ...overrides}; fn(...args);Template literalsconst sql = gfx`SELECT * FROM ${table} WHERE id = ${id}`;Computed property namesconst key = 'name'; const obj = { [key]: 'Alice', [`${key}_upper`]: 'ALICE' };.map(fn)const doubled = [1,2,3].map(x => x * 2); // [2,4,6].filter(fn)const adults = users.filter(u => u.age >= 18);.reduce(fn, init)const sum = [1,2,3].reduce((acc, n) => acc + n, 0);.find() / .findIndex()const admin = users.find(u => u.role === 'admin');.flat(n) / .flatMap(fn)[1,[2,[3]]].flat(2); // [1,2,3].at(-1)const last = arr.at(-1); const second = arr.at(-2);Array.from() / Array.of()Array.from({length:5}, (_,i) => i+1); // [1,2,3,4,5].toSorted() / .toReversed()const sorted = arr.toSorted((a,b) => a-b); // original unchangedObject.entries/keys/valuesObject.entries(obj).map(([k,v]) => `${k}:${v}`);Object.fromEntries()Object.fromEntries(Object.entries(obj).filter(([,v]) => v > 0));Object.assign() / {...spread}const config = { ...defaults, ...userConfig };structuredClone()const deep = structuredClone({ a: { b: [1,2,3] } });Map / WeakMapconst cache = new Map(); cache.set(user, data);Set / WeakSetconst unique = [...new Set([1,1,2,3])]; // [1,2,3]Symbol()const ID = Symbol('id'); obj[ID] = 42; // non-enumerableProxy / Reflectnew Proxy(target, { get(t,k) { log(k); return Reflect.get(t,k); } });async / awaitconst data = await fetch(url).then(r => r.json());Promise.all()const [users, posts] = await Promise.all([getUsers(), getPosts()]);Promise.allSettled()const results = await Promise.allSettled(requests); // handle failures individuallyPromise.race() / any()Promise.any([fetch(url1), fetch(url2)]); // fastest successfulAbortControllerconst ctrl = new AbortController(); fetch(url, {signal: ctrl.signal}); ctrl.abort();for await...offor await (const chunk of stream) { process(chunk); }async generatorsasync function* paginate(url) { let page=1; while(true) yield await fetch(`${url}?page=${page++}`); }queueMicrotask()queueMicrotask(() => updateUI()); // before next render tickclass / extends / superclass Dog extends Animal { constructor(n) { super(n); this.type='dog'; } }#privateFieldclass BankAccount { #balance = 0; deposit(n) { this.#balance += n; } }static / static #privateclass Config { static #instance; static getInstance() { return Config.#instance ??= new Config(); } }get / set accessorsget fullName() { return `${this.first} ${this.last}`; }Mixin patternconst Serializable = (Base) => class extends Base { toJSON() {...} };querySelector / querySelectorAllconst btns = [...document.querySelectorAll('.btn:not(:disabled)')];addEventListener(type, fn, opts)el.addEventListener('scroll', fn, { passive: true, once: true });IntersectionObservernew IntersectionObserver(([e]) => e.isIntersecting && loadMore(), {threshold:0.1}).observe(sentinel);MutationObservernew MutationObserver(muts => muts.forEach(m => handle(m))).observe(el, {childList:true});ResizeObservernew ResizeObserver(([e]) => setWidth(e.contentRect.width)).observe(el);localStorage / sessionStoragelocalStorage.setItem('prefs', JSON.stringify(prefs)); JSON.parse(localStorage.getItem('prefs'));Clipboard APIawait navigator.clipboard.writeText('Copied text!');Web Workersconst w = new Worker('worker.js'); w.postMessage(data); w.onmessage = ({data}) => handle(data);Closureconst makeCounter = (n=0) => ({ inc: () => ++n, get: () => n });Currying / Partial applicationconst mul = a => b => a * b; const double = mul(2); double(5); // 10Debounce / Throttleconst debouncedSearch = debounce(search, 300); // wait 300ms after typing stopsMemoizationconst memo = fn => { const c = new Map(); return x => c.has(x) ? c.get(x) : c.set(x, fn(x)).get(x); };requestAnimationFrameconst animate = t => { draw(t); requestAnimationFrame(animate); }; requestAnimationFrame(animate);WeakRef / FinalizationRegistryconst ref = new WeakRef(target); ref.deref()?.doSomething();