// Constant (cannot be reassigned — preferred)const name = "Alice";// Variable (can be reassigned)let count = 0;count = 1;// var is avoided (function-scoped and has hoisting issues)var old = "avoid";
Scope Differences
function example() { if (true) { var a = "var"; // function-scoped → accessible outside the if block let b = "let"; // block-scoped → not accessible outside the if block const c = "const"; // block-scoped } console.log(a); // "var" console.log(b); // ReferenceError}
// === compares value AND type (recommended)1 === 1; // true1 === "1"; // false// == performs type coercion (not recommended)1 == "1"; // true ← can cause unexpected behavior// Others1 !== 2; // true1 > 0; // true1 >= 1; // true
Logical Operators
true && false; // false (AND)true || false; // true (OR)!true; // false (NOT)// Short-circuit evaluationconst name = user && user.name; // undefined if user is falsyconst label = name || "Anonymous"; // "Anonymous" if name is falsy// Nullish Coalescing (only null / undefined)const value = data ?? "default"; // right side only when data is null/undefined
Optional Chaining
const user = { profile: { name: "Alice" } };user?.profile?.name; // "Alice"user?.address?.city; // undefined (no error)user?.getName?.(); // safe even if method doesn't existarr?.[0]; // optional chaining on arrays
const name = "Alice";const age = 30;// Embed expressionsconst greeting = `Hello, ${name}! You are ${age} years old.`;// Multi-lineconst multiline = ` Line 1 Line 2 Line 3`.trim();// Expressions are supportedconst result = `Total: ${1 + 2 + 3}`;
5. Array Operations
Basic Operations
const arr = [1, 2, 3, 4, 5];arr.length; // 5arr[0]; // 1arr.at(-1); // 5 (from the end)// Add / removearr.push(6); // add to end → [1,2,3,4,5,6]arr.pop(); // remove from end and return itarr.unshift(0); // add to beginningarr.shift(); // remove from beginning and return itarr.splice(1, 2); // remove 2 elements starting at index 1// Searcharr.indexOf(3); // 2arr.includes(3); // truearr.find(x => x > 3); // 4 (first matching element)arr.findIndex(x => x > 3); // 3 (index of first match)
Higher-Order Functions (Immutable Operations)
const numbers = [1, 2, 3, 4, 5];// map: transform each element into a new arraynumbers.map(n => n * 2); // [2, 4, 6, 8, 10]// filter: return a new array of elements that pass the testnumbers.filter(n => n % 2 === 0); // [2, 4]// reduce: reduce array to a single valuenumbers.reduce((acc, n) => acc + n, 0); // 15// forEach: iterate for side effects (no return value)numbers.forEach(n => console.log(n));// find / some / everynumbers.find(n => n > 3); // 4numbers.some(n => n > 4); // true (at least one passes)numbers.every(n => n > 0); // true (all pass)// flat / flatMap[[1, 2], [3, 4]].flat(); // [1, 2, 3, 4][1, 2, 3].flatMap(n => [n, n * 2]); // [1, 2, 2, 4, 3, 6]
const status = "loading";switch (status) { case "loading": console.log("Loading"); break; case "success": console.log("Success"); break; case "error": console.log("Error"); break; default: console.log("Unknown");}
Loops
// forfor (let i = 0; i < 3; i++) { console.log(i); // 0, 1, 2}// for...of (iterate values of an iterable)for (const item of ["a", "b", "c"]) { console.log(item);}// for...in (iterate keys of an object — avoid with arrays)const obj = { a: 1, b: 2 };for (const key in obj) { console.log(key, obj[key]);}// whilelet count = 0;while (count < 3) { count++;}// break / continuefor (const n of [1, 2, 3, 4, 5]) { if (n === 3) continue; // skip if (n === 5) break; // exit loop console.log(n); // 1, 2, 4}
8. Functions
Function Declaration / Expression / Arrow Function
// Function declaration (hoisted)function add(a, b) { return a + b;}// Function expression (not hoisted)const multiply = function (a, b) { return a * b;};// Arrow function (concise syntax)const square = (n) => n * n;const greet = (name) => `Hello, ${name}`;const noop = () => {};// Multi-lineconst divide = (a, b) => { if (b === 0) throw new Error("Cannot divide by zero"); return a / b;};
class AppError extends Error { constructor(message, public code) { super(message); this.name = "AppError"; }}const validate = (value) => { if (!value) throw new AppError("Value is empty", "EMPTY_VALUE");};try { validate("");} catch (err) { if (err instanceof AppError) { console.error(`[${err.code}] ${err.message}`); }}
Error Types
Error
Common Cause
SyntaxError
Syntax error (e.g. JSON.parse)
TypeError
Type mismatch (e.g. null.property)
ReferenceError
Accessing an undefined variable
RangeError
Out-of-range value (e.g. new Array(-1))
URIError
Invalid URI encoding/decoding
13. Classes
Basic Syntax
class Animal { // Fields #name; // private field species = "Unknown"; // public field constructor(name) { this.#name = name; } // Getter get name() { return this.#name; } // Method speak() { return `${this.#name} makes a sound`; } // Static method static create(name) { return new Animal(name); }}const dog = new Animal("Rex");dog.name; // "Rex"dog.speak(); // "Rex makes a sound"Animal.create("Kitty"); // same as new Animal("Kitty")
Inheritance
class Dog extends Animal { #breed; constructor(name, breed) { super(name); // call parent constructor this.#breed = breed; } speak() { return `${super.speak()} (Woof!)`; } get info() { return `${this.name} / ${this.#breed}`; }}const rex = new Dog("Rex", "Shiba Inu");rex.speak(); // "Rex makes a sound (Woof!)"rex.info; // "Rex / Shiba Inu"rex instanceof Dog; // truerex instanceof Animal; // true
14. Modules
Export
// Named export (multiple allowed)export const PI = 3.14159;export const add = (a, b) => a + b;export class Calculator { /* ... */ }// Export togetherconst subtract = (a, b) => a - b;const divide = (a, b) => a / b;export { subtract, divide };// Export with aliasexport { subtract as sub };// Default export (one per file)export default function main() { /* ... */ }
Import
// Named importimport { PI, add } from "./math.js";// Import with aliasimport { add as sum } from "./math.js";// Default importimport main from "./main.js";// Import everything as namespaceimport * as math from "./math.js";math.add(1, 2);// Default and named togetherimport main, { PI, add } from "./module.js";// Side-effects only (just execute)import "./setup.js";
// Map (keys can be any value)const map = new Map();map.set("key", "value");map.set(1, "one");map.get("key"); // "value"map.has("key"); // truemap.delete("key");map.size; // 1for (const [key, value] of map) { console.log(key, value);}// Set (unique collection)const set = new Set([1, 2, 3, 2, 1]);set.size; // 3set.add(4);set.has(2); // trueset.delete(2);for (const value of set) { console.log(value);}