Every essential JavaScript concept, syntax pattern, and built-in method — with clean, copy-paste-ready examples covering ES6 through the latest ECMAScript features.
JavaScript is the language of the web. Whether you are building UIs, APIs, or full-stack apps, this reference covers every fundamental and advanced construct you need to write clean, modern JS.
var / let / const: The three variable declaration keywords with different scoping and mutability rules.
var x = 10; // function-scoped, hoisted, re-declarable
let y = 20; // block-scoped, not re-declarable
const Z = 30; // block-scoped, cannot be reassignedPrimitive Types: JavaScript has seven primitive data types.
const str = "hello"; // String
const num = 42; // Number
const big = 9007199254740991n; // BigInt
const bool = true; // Boolean
const nil = null; // Null
const und = undefined; // Undefined
const sym = Symbol("id"); // Symboltypeof: Returns a string indicating the type of a value.
typeof "hello" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" (historical quirk)
typeof {} // "object"
typeof [] // "object"
typeof function(){} // "function"Type Coercion: Implicit vs explicit type conversion.
// Explicit
Number("42") // 42
String(100) // "100"
Boolean(0) // false
Boolean("") // false
Boolean(null) // false
// Implicit (avoid relying on these)
"5" + 3 // "53" (string concat wins)
"5" - 3 // 2 (numeric subtraction)
"5" == 5 // true (loose equality coerces)
"5" === 5 // false (strict — no coercion)Comparison & Logical
// Equality
a === b // Strict equal (type + value)
a !== b // Strict not equal
// Logical
a && b // AND — returns first falsy or last value
a || b // OR — returns first truthy or last value
!a // NOT — inverts boolean
// Nullish Coalescing (ES2020)
const name = user.name ?? "Anonymous"; // uses right side only if left is null/undefined
// Optional Chaining (ES2020)
const city = user?.address?.city; // safe deep accessArithmetic & Assignment Shortcuts
x += 5; x -= 5; x *= 2; x /= 2; x **= 2; x %= 3;
x++; x--; ++x; --x;
// Logical assignment (ES2021)
x ||= "default"; // assign if x is falsy
x &&= "updated"; // assign if x is truthy
x ??= "fallback"; // assign if x is null/undefinedif / else if / else & Ternary
if (score >= 90) {
grade = "A";
} else if (score >= 70) {
grade = "B";
} else {
grade = "C";
}
// Ternary
const result = score >= 50 ? "pass" : "fail";switch
switch (day) {
case "Mon":
case "Tue":
console.log("Weekday");
break;
case "Sat":
case "Sun":
console.log("Weekend");
break;
default:
console.log("Unknown");
}Loops
// Classic for
for (let i = 0; i < 5; i++) { console.log(i); }
// while
let i = 0;
while (i < 5) { console.log(i++); }
// for...of — iterates values (arrays, strings, sets)
for (const item of ["a", "b", "c"]) { console.log(item); }
// for...in — iterates keys of an object
for (const key in obj) { console.log(key, obj[key]); }Function Declaration vs Expression vs Arrow
// Declaration — hoisted
function greet(name) {
return "Hello " + name;
}
// Expression — not hoisted
const greet = function(name) {
return "Hello " + name;
};
// Arrow (ES6) — no own 'this'
const greet = (name) => "Hello " + name;
// Multi-line arrow
const add = (a, b) => {
const result = a + b;
return result;
};Default, Rest & Spread Parameters
// Default parameters
function greet(name = "World") {
return "Hello " + name;
}
// Rest — collects remaining args into an array
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
// Spread — expands iterable into arguments
const nums = [1, 2, 3];
Math.max(...nums); // 3Higher-Order Functions: Functions that take or return functions.
// Map, Filter, Reduce (see Arrays section)
const double = (fn) => (x) => fn(x) * 2;
const addOne = (x) => x + 1;
double(addOne)(4); // 10 — (4+1)*2IIFE: Immediately Invoked Function Expression — runs once on declaration.
(function() {
console.log("Runs immediately!");
})();
// Arrow IIFE
(() => console.log("Arrow IIFE"))();Creation & Access
const fruits = ["apple", "banana", "cherry"];
fruits[0]; // "apple"
fruits.length; // 3
fruits.at(-1); // "cherry" (ES2022 — negative index)Mutation Methods
fruits.push("date"); // Add to end — returns new length
fruits.pop(); // Remove from end — returns removed item
fruits.unshift("avocado"); // Add to start
fruits.shift(); // Remove from start
fruits.splice(1, 1, "blueberry"); // Remove 1 at index 1, insert "blueberry"Iteration Methods (non-mutating)
const nums = [1, 2, 3, 4, 5];
// map — transforms each element into a new array
nums.map(n => n * 2); // [2, 4, 6, 8, 10]
// filter — keeps elements that pass the test
nums.filter(n => n % 2 === 0); // [2, 4]
// reduce — accumulates a single value
nums.reduce((acc, n) => acc + n, 0); // 15
// find — returns first matching element
nums.find(n => n > 3); // 4
// some / every
nums.some(n => n > 4); // true
nums.every(n => n > 0); // true
// flat / flatMap
[[1, 2], [3, 4]].flat(); // [1, 2, 3, 4]Sort & Slice
// sort (comparator required for numbers)
[3, 1, 2].sort((a, b) => a - b); // [1, 2, 3]
// slice — non-mutating copy with start/end index
nums.slice(1, 3); // [2, 3]Creation & Shorthand
const name = "Alice";
const age = 30;
// Longhand
const user = { name: name, age: age };
// ES6 Shorthand (property name === variable name)
const user = { name, age };
// Computed property key
const key = "role";
const obj = { [key]: "admin" }; // { role: "admin" }Object Methods
const user = { name: "Alice", age: 30 };
Object.keys(user); // ["name", "age"]
Object.values(user); // ["Alice", 30]
Object.entries(user); // [["name","Alice"], ["age",30]]
// Merge / clone with Object.assign or spread
const merged = Object.assign({}, user, { role: "admin" });
const clone = { ...user }; // shallow copyOptional Chaining & Nullish Coalescing
const city = user?.address?.city ?? "Unknown";Getter & Setter
const person = {
_name: "Alice",
get name() { return this._name.toUpperCase(); },
set name(val) { this._name = val.trim(); }
};
console.log(person.name); // "ALICE"Array Destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];
// first=1, second=2, rest=[3,4,5]
// Swap variables
let a = 1, b = 2;
[a, b] = [b, a]; // a=2, b=1Object Destructuring
const { name, age, role = "user" } = user; // default value for role
// Rename during destructure
const { name: fullName } = user;
// Nested destructure
const { address: { city } } = user;
// In function parameters
function display({ name, age }) {
console.log(name, age);
}Spread & Rest
// Spread array
const combined = [...arr1, ...arr2];
// Spread object (shallow merge, rightmost wins)
const updated = { ...user, age: 31 };
// Rest in function (see Functions section)class Animal {
#sound; // private field (ES2022)
constructor(name, sound) {
this.name = name;
this.#sound = sound;
}
speak() {
return `${this.name} says ${this.#sound}`;
}
static create(name, sound) { // static factory
return new Animal(name, sound);
}
}
class Dog extends Animal {
constructor(name) {
super(name, "Woof");
}
fetch(item) {
return `${this.name} fetches the ${item}!`;
}
}
const d = new Dog("Rex");
d.speak(); // "Rex says Woof"
d.fetch("ball"); // "Rex fetches the ball!"Promise: Represents a value that will be available in the future.
const p = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000);
});
p.then(val => console.log(val)) // "done!"
.catch(err => console.error(err))
.finally(() => console.log("always runs"));Async/Await: Syntactic sugar over Promises for cleaner asynchronous code.
async function getUser(id) {
try {
const res = await fetch(`/api/users/${id}`);
const user = await res.json();
return user;
} catch (err) {
console.error("Failed:", err);
}
}Promise Combinators
// All must resolve (fails fast on first rejection)
const [a, b] = await Promise.all([fetchA(), fetchB()]);
// Settles when all are done (never rejects)
const results = await Promise.allSettled([p1, p2]);
// First to resolve wins
const fast = await Promise.race([p1, p2]);
// First to resolve (ignores rejections)
const first = await Promise.any([p1, p2, p3]);// --- math.js ---
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export default class Calculator { /* ... */ }
// --- app.js ---
import Calculator, { PI, add } from "./math.js";
// Rename import
import { add as sum } from "./math.js";
// Import everything
import * as MathUtils from "./math.js";
// Dynamic import (lazy loading)
const module = await import("./math.js");
module.add(1, 2);try {
JSON.parse("{invalid}");
} catch (err) {
console.error(err instanceof SyntaxError); // true
console.error(err.message);
console.error(err.stack);
} finally {
console.log("Cleanup runs regardless");
}
// Custom errors
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
throw new ValidationError("Required", "email");Selecting Elements
document.getElementById("app");
document.querySelector(".card"); // first match
document.querySelectorAll("li"); // NodeList of all matchesModifying Elements
const el = document.querySelector("#title");
el.textContent = "Hello World"; // text only
el.innerHTML = "<strong>Bold</strong>"; // HTML string
el.setAttribute("data-id", "42");
el.classList.add("active");
el.classList.remove("hidden");
el.classList.toggle("selected");
el.style.color = "red";Creating & Appending Elements
const li = document.createElement("li");
li.textContent = "New Item";
document.querySelector("ul").appendChild(li);
// Modern: insertAdjacentHTML
el.insertAdjacentHTML("beforeend", "<span>✅</span>");Events
// Add listener
button.addEventListener("click", (e) => {
e.preventDefault();
console.log("Clicked!", e.target);
});
// Event delegation
document.querySelector("#list").addEventListener("click", (e) => {
if (e.target.matches("li")) {
console.log("List item clicked:", e.target.textContent);
}
});Closure: A function that remembers the variables from its outer scope even after the outer function has returned.
function makeCounter() {
let count = 0; // enclosed in the returned function's closure
return {
increment() { return ++count; },
decrement() { return --count; },
value() { return count; },
};
}
const counter = makeCounter();
counter.increment(); // 1
counter.increment(); // 2
counter.value(); // 2Scope Chain: How JavaScript resolves variable names.
const x = "global";
function outer() {
const x = "outer";
function inner() {
const x = "inner";
console.log(x); // "inner" — nearest scope wins
}
inner();
console.log(x); // "outer"
}
outer();
console.log(x); // "global"Hoisting: var and function declarations are moved to the top of their scope at compile time.
console.log(a); // undefined (var hoisted, not value)
var a = 5;
// let/const — Temporal Dead Zone (TDZ): accessing before declaration throws ReferenceError
// console.log(b); // ReferenceError
let b = 10;Custom Iterator: Any object with a [Symbol.iterator] method that returns a { next() } iterator.
const range = {
from: 1, to: 5,
[Symbol.iterator]() {
let cur = this.from;
const last = this.to;
return {
next() {
return cur <= last
? { value: cur++, done: false }
: { value: undefined, done: true };
}
};
}
};
for (const n of range) console.log(n); // 1 2 3 4 5Generator Function: Uses function* and yield to produce a sequence of values lazily.
function* fibonacci() {
let [a, b] = [0, 1];
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
const fib = fibonacci();
fib.next().value; // 0
fib.next().value; // 1
fib.next().value; // 1
fib.next().value; // 2| Feature | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Hoisting | Yes (undefined) | Yes (TDZ) | Yes (TDZ) |
| Reassignable | Yes | Yes | No |
| Redeclarable | Yes | No | No |
| Method | Returns | Mutates? |
|---|---|---|
map(fn) | New array | No |
filter(fn) | New array | No |
reduce(fn, init) | Single value | No |
find(fn) | First match / undefined | No |
some(fn) | Boolean | No |
every(fn) | Boolean | No |
slice(s, e) | New array | No |
push(...items) | New length | Yes |
pop() | Removed item | Yes |
splice(s,d,...) | Removed items | Yes |
sort(fn?) | Sorted array | Yes |
reverse() | Reversed array | Yes |
| Value | Type |
|---|---|
false | Boolean |
0 | Number |
-0 | Number |
0n | BigInt |
"" | String (empty) |
null | Null |
undefined | Undefined |
NaN | Number |
| Method | Resolves When | Rejects When |
|---|---|---|
Promise.all() | All resolve | Any rejects |
Promise.allSettled() | All settle | Never |
Promise.race() | First settles | First settles (if rejected) |
Promise.any() | First resolves | All reject |
Md Rashid
Software engineer and career coach with 6+ years in the tech industry. Writes about interview prep, developer careers, and tech job markets.

Top 30 Most Asked JavaScript Interview Questions and Answers (2026 Edition)
Ace your next frontend interview with this comprehensive guide covering closures, the event loop, promises, async/await, prototypes, ES6 features, and 24 more must-know JavaScript concepts.

The Complete SQL Cheat Sheet 2026
Every SQL command, function, and pattern you need — from basic SELECT queries to advanced window functions, CTEs, indexes, and transactions. Clean, runnable examples for PostgreSQL, MySQL, and SQL Server.

Top 30 Most Asked React Interview Questions and Answers (2026 Edition)
Ace your next frontend interview with this comprehensive guide covering React hooks, virtual DOM, state management, context, performance optimisation, and the latest React 19 concepts.

The Complete Linux Commands Cheat Sheet 2026
Every essential Linux command defined with clean, practical examples. Covers file navigation, system monitoring, user permissions, networking, package management, and shell scripting.