Back
๐
UI Sheet โ Cheat Sheet
Quick revision โ JS ยท HTML ยท CSS ยท React
โก Core Language
var vs let vs const
varFunction-scoped, hoisted (undefined), re-declarable
letBlock-scoped, hoisted (TDZ), not re-declarable
constBlock-scoped, must be initialized, no reassign
โ const object properties can still be mutated
Hoisting
Declarations are moved to top of scope before execution.
// var โ hoisted as undefined
console.log(x); // undefined
var x = 5;
// let/const โ TDZ error
console.log(y); // ReferenceError
let y = 5;
// Function declarations โ fully hoisted
greet(); // works!
function greet() { console.log("hi"); }
// Function expressions โ not hoisted
sayHi(); // TypeError
var sayHi = () => {};Closures
A function that remembers its lexical scope even when called outside it.
function counter() {
let count = 0;
return {
inc: () => ++count,
get: () => count,
};
}
const c = counter();
c.inc(); c.inc();
c.get(); // 2
// Classic bug: var in loop
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
} // prints 3 3 3
// Fix: use let (block-scoped)
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
} // prints 0 1 2this keyword
Globalwindow (browser) / undefined (strict mode)
Method callThe object before the dot
Arrow fnInherits `this` from enclosing scope (no own this)
newThe newly created object
call/apply/bindExplicitly set
const obj = {
name: "Alice",
greet() { console.log(this.name); }, // Alice
arrowGreet: () => console.log(this), // window/undefined
};Prototype Chain
Every object has [[Prototype]]. Property lookup walks the chain until null.
function Animal(name) { this.name = name; }
Animal.prototype.speak = function() {
return this.name + " speaks";
};
// ES6 class is syntactic sugar
class Dog extends Animal {
bark() { return "woof"; }
}
// Check prototype
Object.getPrototypeOf(obj) === Constructor.prototype== vs === / Falsy values
=== โ strict equality, no type coercion
== โ loose equality, coerces types
Falsy values:
false0""nullundefinedNaN0n
null == undefined // true null === undefined // false NaN === NaN // false โ use Number.isNaN() [] == false // true (coercion)
๐ Async JavaScript
Event Loop
Call StackExecutes sync code (LIFO)
Web APIsHandles async ops (timers, fetch, DOM)
Microtask QPromise.then, queueMicrotask โ runs FIRST
Macrotask QsetTimeout, setInterval โ runs AFTER microtasks
console.log(1); // sync setTimeout(() => log(2), 0); // macrotask Promise.resolve().then(() => log(3)); // microtask console.log(4); // sync // Output: 1 โ 4 โ 3 โ 2
Promises
States: pendingfulfilledrejected
// Create
const p = new Promise((resolve, reject) => {
setTimeout(() => resolve("done"), 1000);
});
// Chain
p.then(v => v.toUpperCase())
.then(console.log)
.catch(err => console.error(err))
.finally(() => console.log("cleanup"));
// Combinators
Promise.all([p1, p2]) // fails if any fails
Promise.allSettled([p1,p2]) // always resolves
Promise.race([p1, p2]) // first to settle wins
Promise.any([p1, p2]) // first to FULFILL winsasync / await
Syntactic sugar over Promises. await pauses execution inside the async fn โ code after it is a microtask.
async function fetchUser(id) {
try {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error("Not found");
return await res.json();
} catch (err) {
console.error(err);
}
}
// Parallel awaits
const [a, b] = await Promise.all([fetchA(), fetchB()]);Callbacks โ Promises โ async/await
// Callback hell
getUser(id, (user) => {
getPosts(user, (posts) => {
getComments(posts[0], (comments) => { ... })
})
})
// Promise chain
getUser(id)
.then(user => getPosts(user))
.then(posts => getComments(posts[0]))
// async/await (cleanest)
const user = await getUser(id);
const posts = await getPosts(user);
const comments = await getComments(posts[0]);๐ ๏ธ Arrays & Objects
Must-know Array Methods
map(fn)Transform every element โ new array
filter(fn)Keep elements where fn returns true
reduce(fn, init)Accumulate to single value
find/findIndexFirst match / its index
some/everyAny match / all match โ boolean
flat(depth)Flatten nested arrays
flatMap(fn)map then flat(1)
includes(v)Check presence โ boolean
const nums = [1,2,3,4,5]; nums.map(x => x * 2); // [2,4,6,8,10] nums.filter(x => x % 2 === 0);// [2,4] nums.reduce((a,b) => a+b, 0); // 15
Spread, Rest & Destructuring
// Spread
const arr2 = [...arr1, 4, 5];
const obj2 = { ...obj1, key: "new" };
// Rest
function sum(...nums) { return nums.reduce((a,b) => a+b); }
// Destructuring
const { name, age = 25 } = user; // with default
const { name: alias } = user; // rename
const [first, , third] = arr; // skip elements
const { a, ...rest } = obj; // rest objectOptional Chaining & Nullish Coalescing
// Optional chaining (?.) โ short-circuits on null/undefined user?.profile?.avatar?.url // Nullish coalescing (??) โ only null/undefined, not 0 or "" const name = user.name ?? "Anonymous"; // vs OR (||) โ falsy fallback (0, "" also trigger) const name = user.name || "Anonymous"; // 0 and "" โ "Anonymous" // Optional call onClick?.(); arr?.[0]?.toUpperCase();
Useful Object Methods
Object.keys(obj) // ["a","b"]
Object.values(obj) // [1,2]
Object.entries(obj) // [["a",1],["b",2]]
Object.assign({},src) // shallow clone
Object.freeze(obj) // immutable (shallow)
Object.fromEntries(entries) // entries โ object
// Check own property (not prototype chain)
obj.hasOwnProperty("key")๐ฎ Advanced Concepts
Debounce vs Throttle
DebounceWaits N ms after LAST call. Good for search input.
ThrottleExecutes at most once per N ms. Good for scroll/resize.
// Debounce
function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
// Throttle
function throttle(fn, limit) {
let inThrottle;
return (...args) => {
if (!inThrottle) {
fn(...args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}typeof & instanceof / Type checks
typeof "str" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof undefined// "undefined"
typeof null // "object" โ famous bug
typeof {} // "object"
typeof [] // "object" โ use Array.isArray()
typeof fn // "function"
[] instanceof Array // true
{} instanceof Object // true
// Safe type check
Object.prototype.toString.call([]) // "[object Array]"Currying & Composition
// Currying โ fn with multiple args โ chain of fns with 1 arg const add = a => b => a + b; add(2)(3); // 5 // Partial application const add5 = add(5); add5(3); // 8 // Composition const compose = (...fns) => x => fns.reduceRight((v,f) => f(v), x); const pipe = (...fns) => x => fns.reduce((v,f) => f(v), x);
Generators & Symbol (quick ref)
// Generator โ pauseable function
function* gen() {
yield 1;
yield 2;
return 3;
}
const g = gen();
g.next(); // {value:1, done:false}
// Symbol โ unique primitive key
const id = Symbol("id");
obj[id] = 42; // won't clash with "id" string key