Intl Arrow functions
JavaScript Top new Intl.NumberFormat('en-IN').format(1234567) const add = (a,b)=>a+b;
Commands / Idioms Create/convert Default params
Cheatsheet Array.from(nodeList); [...iterable];
Push/pop/shift/unshift
function f(x=42){...}
Classes
Log / Warn / Error arr.push(x); arr.pop(); arr.shift(); arr.unshift(x) class A { constructor(x){this.x=x} method(){...} }
console.log(x); console.warn('!'); console.error(err); map/filter/reduce Getters/Setters
Declarations arr.map(f); arr.filter(pred); arr.reduce(fn, init) class A{ get v(){...} set v(x){...} }
let x=1; const PI=3.14; var legacy; find/some/every Modules (ESM)
Strict mode arr.find(pred); arr.some(pred); arr.every(pred) export function f(){}; import {f} from './m.js'
"use strict"; // at top of file/function sort CommonJS (Node)
Template literals arr.sort((a,b)=>a-b) // beware in-place module.exports = fn; const fn = require('./m')
const s = `Hello ${name}!`; flat/flatMap Promise
Destructuring arr.flat(2); arr.flatMap(x=>[x,x]) new Promise((res,rej)=>{...; res(v)})
const {a,b} = obj; const [x,y,...rest] = arr; Object keys/values Then/Catch/Finally
Spread / Rest Object.keys(o); Object.values(o); Object.entries(o) p.then(v=>...).catch(e=>...).finally(()=>...)
const z = {...o1, ...o2}; const arr2=[...arr, 4]; function Assign/merge async/await
f(...args){}
Object.assign({}, a, b) // or {...a, ...b} const v = await fetch(...);
Optional chaining
Freeze/Seal Promise.all/race
obj?.user?.name; fn?.(x);
Object.freeze(o); Object.seal(o) await Promise.all([p1,p2]); await Promise.race(ps)
Nullish coalescing
hasOwn fetch (GET)
value ?? defaultValue
Object.hasOwn(o,'k') // ES2022 const res = await fetch(url); const data = await res.json()
Type checks
Set / Map fetch (POST JSON)
typeof x==='string'; Array.isArray(a); x instanceof Date
const s=new Set([1,2]); s.has(1); const m=new Map([['k',1]]) await fetch(u,{method:'POST',headers:{'Content-Type':'applic
Equality ation/json'},body:JSON.stringify(obj)})
WeakMap/WeakSet
=== and !== (avoid == unless needed) URL & params
GC-aware refs for objects (no strong hold)
String methods const u=new URL(loc); u.searchParams.get('q')
for...of
'abc'.includes('b'); ' hi '.trim(); 'a-b'.split('-') setTimeout/Interval
for (const v of arr) {...}
Number parse const id=setTimeout(fn,300); clearTimeout(id)
for...in
Number('3'); parseInt('08',10); parseFloat('1.2') requestAnimationFrame
for (const k in obj) {...} // enumerable props
Math const id=requestAnimationFrame(step)
forEach
Math.max(...arr); Math.round(1.6); Math.random() console.time()
arr.forEach((v,i)=>...)
Date console.time('t'); //...; console.timeEnd('t')
try/catch
new Date(); Date.now(); d.toISOString()
try { ... } catch (e) { ... } finally { ... }
performance.now() Debounce (snippet)
const t=performance.now() const debounce=(f,d)=>{let
Select t;return(...a)=>{clearTimeout(t);t=setTimeout(()=>f(...a),d)}}
Throttle (snippet)
document.querySelector('.cls');
document.querySelectorAll('li') const throttle=(f,d)=>{let r=false;return(...a)=>{if(r)return;r=tru
Create/append e;f(...a);setTimeout(()=>r=false,d)}}
Guard optional
const el=document.createElement('div'); parent.append(el)
Classes/attrs if (!node) return; // early exit
Non-null assert (TS)
el.classList.add('x'); el.setAttribute('role','button')
Content el!.value // TS only
fs readFileSync
el.textContent='Hi'; el.innerHTML='<b>Hi</b>'
Styles const fs=require('fs'); const s=fs.readFileSync('a.txt','utf8')
path join/resolve
el.style.background='red'
Events const path=require('path'); path.join(a,b); path.resolve(p)
process
el.addEventListener('click', handler)
Closest process.env.NODE_ENV; process.cwd(); process.argv
child_process
el.closest('.card')
Dataset require('child_process').exec('ls', cb)
npm scripts
el.dataset.id = '42'
Scroll npm init -y; npm run build; npx tool
Jest/Vitest basic
el.scrollIntoView({behavior:'smooth'})
localStorage test('x',()=>{ expect(2+2).toBe(4) })
localStorage.setItem('k','v'); localStorage.getItem('k')
sessionStorage
sessionStorage.setItem('k','v')
Cookies
document.cookie='k=v; SameSite=Lax; Secure'
RegExp
const re=/\d+/g; 'a1b2'.match(re); re.test('123')
Replace
'a b'.replace(/\s+/g,' ')
Deep clone (simple)
JSON.parse(JSON.stringify(obj)) // beware types