JavaScript Cheat Sheet
JavaScript quick reference — ES2024 syntax, array methods, promises, and DOM APIs.
Variables & Scope
// Prefer const by default; let when rebinding is needed
const PI = 3.14159; // block-scoped, can't reassign
let count = 0; // block-scoped, can reassign
var legacy = "avoid"; // function-scoped, hoisted — avoid
// Destructuring
const { name, age = 0 } = user; // object (with default)
const [first, ...rest] = items; // array + rest
const { a: renamed } = obj; // rename on destructure
// Nullish coalescing & optional chaining
const val = obj?.nested?.value ?? "default";Data Types
| Type | Example | typeof |
|---|---|---|
string | "hello" / 'world' / `${tpl}` | "string" |
number | 42 / 3.14 / NaN / Infinity | "number" |
bigint | 9007199254740993n | "bigint" |
boolean | true / false | "boolean" |
undefined | let x; // x is undefined | "undefined" |
null | null (intentional absence) | "object" ⚠️ |
symbol | Symbol('id') | "symbol" |
object | {} / [] / new Date() | "object" |
function | () => {} / function f(){} | "function" |
Array Methods
const nums = [1, 2, 3, 4, 5]; // Transform nums.map(n => n * 2); // [2, 4, 6, 8, 10] nums.filter(n => n > 2); // [3, 4, 5] nums.reduce((acc, n) => acc + n, 0); // 15 nums.flatMap(n => [n, n * 2]); // [1,2, 2,4, 3,6, 4,8, 5,10] // Find nums.find(n => n > 3); // 4 (first match) nums.findIndex(n => n > 3); // 3 (index of first match) nums.some(n => n > 4); // true nums.every(n => n > 0); // true nums.includes(3); // true // Mutate (changes original) nums.push(6); // add to end nums.pop(); // remove from end nums.unshift(0); // add to start nums.shift(); // remove from start nums.splice(1, 2); // remove 2 at index 1 nums.sort((a, b) => a - b); // sort numerically // Copy / combine (immutable patterns) const copy = [...nums]; const merged = [...a, ...b]; const sliced = nums.slice(1, 3); // [2, 3] (end exclusive)
Objects
// Shorthand properties & methods
const x = 1, y = 2;
const point = { x, y, toString() { return `(${this.x},${this.y})`; } };
// Spread & merge (shallow)
const merged = { ...defaults, ...overrides };
// Dynamic keys
const key = "name";
const obj = { [key]: "Alice" }; // { name: "Alice" }
// Useful Object methods
Object.keys(obj) // ["name"]
Object.values(obj) // ["Alice"]
Object.entries(obj) // [["name","Alice"]]
Object.fromEntries(entries) // reverse of entries
Object.assign({}, a, b) // merge (mutates first arg)
Object.freeze(obj) // make immutable (shallow)
structuredClone(obj) // deep clone (modern)Functions & Closures
// Declaration (hoisted)
function add(a, b) { return a + b; }
// Expression (not hoisted)
const add = function(a, b) { return a + b; };
// Arrow (lexical this, implicit return for single expression)
const add = (a, b) => a + b;
const double = n => n * 2; // parens optional for 1 param
// Default parameters & rest
function greet(name = "World", ...tags) { ... }
// Closures
function counter() {
let n = 0;
return { inc: () => ++n, get: () => n };
}
const c = counter();
c.inc(); c.inc(); c.get(); // 2
// IIFE (immediately invoked)
const result = (() => 42)();Promises & Async/Await
// Promise
fetch("/api/data")
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err))
.finally(() => setLoading(false));
// Async / Await (same thing, cleaner syntax)
async function loadData() {
try {
const res = await fetch("/api/data");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
return data;
} catch (err) {
console.error(err);
} finally {
setLoading(false);
}
}
// Parallel execution
const [users, posts] = await Promise.all([
fetchUsers(),
fetchPosts(),
]);
// Race / any
const first = await Promise.race([slow(), fast()]);
const anyOne = await Promise.any([p1, p2, p3]);ES2015–2024 Highlights
| Feature | Syntax / Example | Since |
|---|---|---|
| Template literals | `Hello ${name}` | ES6 |
| Destructuring | const { a, b } = obj | ES6 |
| Spread / rest | [...arr] / fn(...args) | ES6 |
| Modules | import x from './x.js' | ES6 |
| Symbol | Symbol('id') | ES6 |
| Proxy / Reflect | new Proxy(target, handler) | ES6 |
| Async / Await | async fn + await promise | ES2017 |
| Optional chaining | obj?.prop?.sub | ES2020 |
| Nullish coalescing | val ?? 'default' | ES2020 |
| Nullish assignment | x ??= 'default' | ES2021 |
| Array at() | [1,2,3].at(-1) → 3 | ES2022 |
| Object.hasOwn() | Object.hasOwn(obj, 'k') | ES2022 |
| Array groupBy | Map.groupBy(items, fn) | ES2024 |
| Promise.withResolvers() | const {promise,resolve} = … | ES2024 |
Error Handling
// try / catch / finally
try {
riskyOperation();
} catch (err) {
if (err instanceof TypeError) { /* handle */ }
console.error(err.message, err.stack);
} finally {
cleanup();
}
// Custom errors
class AppError extends Error {
constructor(message, public code: number) {
super(message);
this.name = "AppError";
}
}
// Error types
new TypeError("wrong type");
new RangeError("out of range");
new ReferenceError("not defined");
new SyntaxError("invalid syntax");DOM Quick Reference
// Select
document.querySelector(".class") // first match
document.querySelectorAll("p") // NodeList
document.getElementById("id")
// Create & insert
const el = document.createElement("div");
el.textContent = "Hello";
el.classList.add("active");
el.setAttribute("data-id", "42");
parent.append(el); // insert at end
parent.prepend(el); // insert at start
ref.before(el); ref.after(el); // siblings
// Events
el.addEventListener("click", (e) => {
e.preventDefault();
e.stopPropagation();
});
el.removeEventListener("click", handler);
// Styles
el.style.color = "red";
el.style.cssText = "color:red; font-size:16px";
getComputedStyle(el).getPropertyValue("color");JavaScript in one paragraph
JavaScript is a dynamically-typed, prototype-based language that runs in browsers (via the V8, SpiderMonkey, or JavaScriptCore engine) and on servers (Node.js, Deno, Bun). Modern JS (ES2015+) is a substantially different language from the ES5 era — block-scoped variables, arrow functions, Promises, modules, destructuring, and optional chaining have replaced most of the old patterns. This cheat sheet covers the modern idioms you'll reach for every day.
When to use TypeScript instead
TypeScript adds static types to JavaScript. For projects larger than ~500 lines, or any library/API others will consume, TypeScript's type system catches entire classes of bugs at compile time. All valid JavaScript is valid TypeScript — you can adopt it incrementally. Use the JSON to TypeScript converter to generate types from existing data.
คำถามที่พบบ่à¸à¸¢
- What's the difference between let, const, and var?
- var is function-scoped and hoisted — its declaration is moved to the top of the function at runtime, which causes subtle bugs. let and const are block-scoped (limited to the nearest {} block) and not hoisted. const means the binding can't be reassigned — but the value it points to (an object or array) can still be mutated. Use const by default; use let when you need to reassign; avoid var in modern code.
- What is the difference between == and === in JavaScript?
- == performs type coercion before comparing — it converts both sides to the same type, which leads to surprises: '0' == false is true. === (strict equality) compares both value AND type with no conversion — '0' === false is false. Always use === unless you explicitly need the coercion behaviour, which is rare.
- What is a Promise and how does async/await work?
- A Promise represents an asynchronous operation that will eventually resolve (succeed) or reject (fail). You chain .then() for success and .catch() for errors. async/await is syntactic sugar over Promises: mark a function as async, then use await before any Promise to pause execution until it settles — without blocking the main thread. Error handling uses try/catch instead of .catch(). Both approaches are equivalent; async/await is more readable for sequential async logic.
- What is the difference between null and undefined?
- undefined means a variable has been declared but not assigned a value — it's the JS engine's default. null is an explicit assignment meaning 'no value' — you set it intentionally. typeof undefined is 'undefined'; typeof null is 'object' (a historical bug in JS). In practice: functions that find nothing return undefined; you use null to intentionally clear a reference. Both are falsy, and null == undefined is true (but null === undefined is false).
- What are arrow functions and when should I use them?
- Arrow functions (=>) are a shorter syntax for functions that also lexically bind this — meaning they inherit this from the surrounding context rather than defining their own. Use arrows for callbacks, array methods (.map, .filter, .reduce), and any case where you want the outer this. Avoid arrows for object methods (where you want this to refer to the object) and constructors (arrows can't be used with new).
- What is event bubbling and how do I stop it?
- When an event fires on an element, it bubbles up through all parent elements, triggering their event listeners too. Use event.stopPropagation() to prevent the event from bubbling further. event.preventDefault() is different — it stops the default browser action (like following a link or submitting a form) but still lets the event bubble. You usually want preventDefault() for forms and links; stopPropagation() is less common and can break event delegation patterns.
เครื่à¸à¸‡à¸¡à¸·à¸à¸—ี่เà¸à¸µà¹ˆà¸¢à¸§à¸‚้à¸à¸‡
- ตัวจัดรูปà¹à¸šà¸š JSON
จัดรูปà¹à¸šà¸š ทำให้สวยงาม ย่ภà¹à¸¥à¸°à¸•รวจสà¸à¸š JSON ในเบราว์เซà¸à¸£à¹Œ
- ตัวสร้าง QR Code
สร้าง QR code สำหรับ URL ข้à¸à¸„วาม Wi-Fi à¹à¸¥à¸°à¸à¸·à¹ˆà¸™à¹† ดาวน์โหลดเป็น PNG
- ตัวสร้างรหัสผ่าน
สร้างรหัสผ่านสุ่มที่à¹à¸‚็งà¹à¸à¸£à¹ˆà¸‡à¸”้วยความยาวà¹à¸¥à¸°à¸Šà¸¸à¸”à¸à¸±à¸à¸‚ระที่à¸à¸³à¸«à¸™à¸”เà¸à¸‡
- Base64 เข้ารหัส / ถà¸à¸”รหัส
เข้ารหัสข้à¸à¸„วามเป็น Base64 หรืà¸à¸–à¸à¸”รหัสà¸à¸¥à¸±à¸šà¹€à¸›à¹‡à¸™à¸‚้à¸à¸„วามธรรมดา
- URL เข้ารหัส / ถà¸à¸”รหัส
เข้ารหัสหรืà¸à¸–à¸à¸”รหัส URL à¹à¸¥à¸° query strings ด้วย percent-encoding