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をひと言で
代わりにTypeScriptを使う場面
JavaScriptはブラウザ(V8・SpiderMonkey・JavaScriptCoreエンジン経由)とサーバー(Node.js・Deno・Bun)上で動作する動的型付けのプロトタイプベース言語です。現代のJS(ES2015+)はES5時代とは実質的に異なる言語です。ブロックスコープの変数・アロー関数・Promise・モジュール・分割代入・オプショナルチェーニングが古いパターンのほとんどを置き換えました。このチートシートは毎日使用する現代のイディオムをカバーします。
TypeScriptはJavaScriptに静的型を追加します。~500行を超えるプロジェクト、または他者が使用するライブラリ/APIには、TypeScriptの型システムがコンパイル時にバグのクラス全体を検出します。有効なJavaScriptはすべて有効なTypeScriptです。段階的に採用できます。JSON to TypeScriptコンバーターを使用して既存データから型を生成してください。
フロントエンド開発者はクイックな配列メソッドの参照のためにこのページをブックマークします。findとfindIndexの違いや、reduceの正確なシグネチャは常に出てきます。Node.jsのバックエンドエンジニアはレガシーコードベースでPromiseチェーンと非同期構文を切り替える際にasync/awaitセクションを参照します。技術面接の準備をしているブートキャンプ生はデータ型とスコープのセクションで基礎を固めます。PythonやJavaから移行するフルスタック開発者は、プロトタイプベースの継承とアロー関数のthisバインディングのセクションが最も混乱することが多く、頻繁に見返します。
オプショナルチェーニング(obj?.prop?.sub)は典型的なフロントエンドコードで何十もの防御的なnullチェックを排除します。Null合体演算子(val ?? 'default')はデフォルト値には||より安全です。0や''などのfalsy値ではなく、nullとundefinedの場合のみフォールバックするからです。structuredClone(obj)はJSON.parse(JSON.stringify())ハックを置き換える現代的なディープクローンで、Dates・Maps・Sets・循環参照を正しく処理します。Promise.allSettled()はすべてのPromiseを実行し、最初の失敗でショートサーキットせずに結果を報告します。部分的な失敗が許容されるバッチ操作に理想的です。
JavaScriptのシングルスレッドイベントループは、長時間実行する同期コードがUI全体をブロックすることを意味します。常にI/Oには非同期パターンを使用してください。JavaやC#やPythonから来た開発者には等価比較における型強制がバグの頻繁な原因です。常に===を使用してください。クラシカルな継承ではなくプロトタイプ継承は、オブジェクトが他のオブジェクトから直接継承できることを意味します。これにより柔軟なパターンが可能ですが、組み込みプロトタイプを変更すると予期しない動作が起きます。varのホイスティング(値ではなく宣言のみ)は、letとconstが現代のコードで完全に排除するレガシーな動作です。
よくある質問
- 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 Formatter, Validator & Repair Tool
Format, minify, validate, and repair JSON instantly in your browser. Sort keys alphabetically, auto-format on paste, download as file, escape/unescape strings — free, no sign-up, 100% client-side.
- QRコード生成
URL、テキスト、Wi-FiなどのQRコードを生成。PNGでダウンロード可能。
- パスワード生成
カスタム長と文字セットで強力なランダムパスワードを生成。
- Base64 エンコーダー / デコーダー
テキストをBase64にエンコード、または逆にデコード。
- URLエンコーダー / デコーダー
パーセントエンコーディングでURLとクエリ文字列をエンコードまたはデコード。