JavaScript Cheat Sheet
1 Basics
- Variables:
let, const (prefer), (avoid var)
- Types:
number, string, boolean, null, undefined, object, bigint, symbol
- Template literals:
`Hello ${name}`
- Strict equality:
=== / !==
- Modules:
export, import
const name = "Ada";
const age = 37;
console.log(`Hi ${name}, ${age} next year: ${age + 1}`);
2 Operators
- Arithmetic:
+ - * / % **
- Assignment:
+= -= *= /= %= **=
- Comparison:
=== !== < <= > >=
- Logical:
&&, ||, !, ?? (nullish)
- Optional chaining:
user?.profile?.email
- Type:
typeof x, Array.isArray(x)
3 Strings
- Length:
str.length
- Case:
toUpperCase(), toLowerCase()
- Search:
includes(), indexOf(), startsWith(), endsWith()
- Cut/replace:
slice(), substring(), replace(), trim()
- Split/join:
split(",") ⇄ Array (join is on arrays)
" hello ".trim().toUpperCase(); // "HELLO"
4 Arrays
- Stack/queue:
push, pop, shift, unshift
- Search:
indexOf, includes, find
- Slice/mutate:
slice (copy), splice (mutate)
- Iterate:
forEach, map, filter, reduce
- Test/order:
some, every, sort, reverse
const odds = [1,2,3,4,5].filter(n => n % 2);
const sum = odds.reduce((a,b) => a + b, 0);
5 Functions
- Declarations:
function greet(){}
- Expressions:
const f = function(){}
- Arrow:
const f = (x) => x * 2
- Defaults:
function f(x = 1){}
- Rest/spread:
function f(...xs){}, f(...arr)
- Closures & higher-order functions
const once = fn => { let ran=false, val; return (...a)=> ran ? val : (ran=true, val=fn(...a)); };
6 Objects
- Create:
{ a:1 }, Object.create(proto)
- Read/write:
obj.key, obj["key"], delete obj.key
- Utilities:
Object.keys, values, entries, hasOwn
- Merge/clone:
{...a, ...b}, Object.assign({}, a, b)
- Destructuring:
const {x, y:yy=0} = pt
const user = {id:1, name:"Ada"};
const {name} = user; // "Ada"
7 Conditionals & Loops
if / else, switch, ternary cond ? A : B
- Loops:
for, for...of (iterables), for...in (object keys)
while, do...while, break/continue
- Error handling:
try/catch/finally
8 DOM Manipulation
- Select:
getElementById(), querySelector(), querySelectorAll()
- Create/insert:
document.createElement(), append()/appendChild()
- Events:
el.addEventListener('click', fn)
- Classes:
el.classList.add/remove/toggle
- Content:
textContent, innerHTML
const btn = document.querySelector('#buy');
btn?.addEventListener('click', () => alert('Thanks!'));
9 ES6+ Features
let/const, arrow functions, template literals
- Destructuring & rest/spread
...
- Modules
import/export
- Iterables & generators:
function* g(){}
- Optional chaining
?., nullish coalescing ??
10 Promises & Async
- Create:
new Promise((res, rej) => {...})
- Consume:
.then(...).catch(...).finally(...)
async/await for linear style
- Combinators:
Promise.all, race, allSettled, any
- Fetch:
await fetch(url).then(r => r.json())
async function getUser(id){
const r = await fetch(`/api/users/${id}`);
if(!r.ok) throw new Error('HTTP ' + r.status);
return r.json();
}
11 Common Built‑ins
- Math:
Math.max, min, floor, ceil, round, random
- Date:
Date.now(), new Date(), getFullYear()
- JSON:
JSON.stringify() / JSON.parse()
- Number:
parseInt, parseFloat, Number.isNaN
- Timers:
setTimeout, setInterval, clear*
- URL utils:
URL, URLSearchParams
const q = new URLSearchParams(location.search);
const page = Number(q.get('page') ?? 1);
12 Patterns & Tips
- Immutability: prefer
map/filter/slice over mutation
- Guard clause: return early to reduce nesting
- Pure functions & small modules
- Use
try/catch at boundaries (I/O, network)
- Lint/format: ESLint + Prettier
function price(cents){
if(cents == null || cents < 0) throw new Error('bad');
return `$${(cents/100).toFixed(2)}`;
}
Comments
Post a Comment