JavaScript Basics
The essentials of modern JavaScript — where it runs, let/const, primitives and objects, functions and arrow functions, arrays and their methods, destructuring, spread, optional chaining, and the gotchas.
JavaScript is the language of the web: every browser runs it, and with Node.js, Deno and Bun it runs on servers, CLIs and edge platforms too. It's dynamically typed, garbage collected, single-threaded with an event loop, and supports both object-oriented and functional styles. The language standard is ECMAScript, updated yearly (ES2015/"ES6" was the big modernisation).
Running JavaScript
node app.js # run a file with Node.js
node # REPL
# In a browser: DevTools console, or <script type="module" src="app.js"></script>Variables: let, const (and why not var)
const name = "Ada"; // can't be reassigned (the object it points to can still change)
let count = 0; // block-scoped, reassignable
count += 1;
const user = { name: "Ada" };
user.name = "Grace"; // fine: mutating the object
// user = {}; // TypeError: assignment to constantvar is function-scoped and hoisted in confusing ways (Scope, closures & hoisting). Default to const, use let when you must reassign, never var.
Types
Primitives (immutable, compared by value): string, number (64-bit float), bigint, boolean, undefined, null, symbol. Everything else is an object (compared by reference): plain objects, arrays, functions, dates, maps…
typeof "hi" // "string"
typeof 42 // "number"
typeof 10n // "bigint"
typeof undefined // "undefined"
typeof null // "object" ← historical bug
typeof [] // "object" → use Array.isArray([])
typeof (() => {}) // "function"
0.1 + 0.2 === 0.3 // false (floating point)
Number.MAX_SAFE_INTEGER // 9007199254740991 — beyond this integers lose precision; use BigInt
[1, 2] === [1, 2] // false: different objectsCoercion rules (== vs ===, truthiness) get their own lesson: Types & coercion. Rule of thumb: always use ===.
Strings
const who = "world";
const msg = `Hello, ${who.toUpperCase()}!`; // template literal with interpolation
"a,b,c".split(","); // ["a", "b", "c"]
" hi ".trim(); "abc".includes("b"); "abc".at(-1); // "c"
"5".padStart(3, "0"); // "005"Objects
const key = "role";
const user = {
name: "Ada",
age: 36,
[key]: "admin", // computed key
greet() { return `Hi, I'm ${this.name}`; }, // method shorthand
};
user.email = "ada@example.com"; // add a property
delete user.age;
"name" in user; // true
Object.keys(user); // ["name", "role", "greet", "email"]
Object.entries(user); // [["name","Ada"], ...]
const copy = { ...user, age: 37 }; // shallow copy + override
const deep = structuredClone(user); // deep copy (no functions)Functions
function add(a, b = 0) { return a + b; } // declaration (hoisted), default parameter
const mul = function (a, b) { return a * b; }; // expression
const square = (x) => x * x; // arrow function, implicit return
const sum = (...nums) => nums.reduce((s, n) => s + n, 0); // rest parameters
const makeUser = (name) => ({ name, createdAt: Date.now() }); // return an object: wrap in ()Functions are first-class values: pass them, return them, store them. Arrow functions don't have their own this or arguments — important for callbacks (The this keyword).
Arrays and their methods
const nums = [5, 1, 4, 2, 3];
nums.map((n) => n * 2); // [10, 2, 8, 4, 6] transform
nums.filter((n) => n % 2); // [5, 1, 3] keep matching
nums.reduce((s, n) => s + n, 0); // 15 fold
nums.find((n) => n > 3); // 5 first match
nums.findIndex((n) => n > 3); // 0
nums.some((n) => n > 4); // true
nums.every((n) => n > 0); // true
nums.includes(4); // true
nums.slice(1, 3); // [1, 4] copy of a range
[[1, 2], [3]].flat(); // [1, 2, 3]
nums.flatMap((n) => [n, n]);
// Mutating vs copying
nums.sort(); // MUTATES, and sorts as STRINGS by default!
[10, 9, 1].sort(); // [1, 10, 9] ← surprise
[10, 9, 1].sort((a, b) => a - b); // [1, 9, 10]
const sorted = nums.toSorted((a, b) => a - b); // ES2023: non-mutating
nums.toReversed(); nums.with(0, 99); // non-mutating versions
nums.push(6); nums.pop(); nums.unshift(0); nums.shift(); // ends
nums.splice(1, 2); // remove 2 items at index 1 (mutates)Destructuring, spread and rest
const { name, role = "user", address: { city } = {} } = user; // with defaults and nesting
const [first, second, ...rest] = [1, 2, 3, 4]; // rest: [3, 4]
[a, b] = [b, a]; // swap
function draw({ x = 0, y = 0, color = "black" } = {}) { ... } // named-style parameters
draw({ color: "red" });
const merged = [...arr1, ...arr2];
const settings = { ...defaults, ...userSettings }; // later keys win
Math.max(...nums);Modern conveniences
user?.address?.city; // optional chaining: undefined instead of TypeError
user.getName?.(); // call only if it exists
const port = config.port ?? 3000; // nullish coalescing: only null/undefined fall back
const n = input || 10; // || falls back for ANY falsy value (0, "", false)!
count ||= 1; opts.retries ??= 3; // logical assignment
for (const item of items) { } // iterate VALUES (arrays, strings, maps, sets)
for (const key in obj) { } // iterate KEYS (including inherited) — rarely what you want
for (const [k, v] of Object.entries(obj)) { }
const m = new Map([["a", 1]]); // any key type, ordered, has size
const s = new Set([1, 2, 2, 3]); // {1, 2, 3}
[...new Set(arr)]; // dedupe an arrayErrors
try {
const data = JSON.parse(text);
} catch (err) {
console.error("Invalid JSON:", err.message);
} finally {
cleanup();
}
class ValidationError extends Error {
constructor(field, message) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
throw new ValidationError("email", "Email is required");Common gotchas
| Gotcha | Example | Fix |
|---|---|---|
| Default sort is lexicographic | [10, 9, 1].sort() | Pass (a, b) => a - b |
typeof null is "object" | Check x === null | |
| Floating point | 0.1 + 0.2 | Integers (cents), or a decimal library |
|| treats 0 and "" as missing | count || 10 | Use ?? |
| Automatic semicolon insertion | return then a newline before the value returns undefined | Keep the value on the same line |
for...in on arrays | Iterates string keys and inherited props | Use for...of |
| Mutating shared objects | Passing an object and changing it | Copy with spread/structuredClone |
- Use const by default, let when reassigning, never var.
- Seven primitive types plus objects; arrays and functions are objects.
- Arrow functions, default/rest parameters, destructuring and spread are everyday tools.
- Master map, filter, reduce, find, some/every; remember sort mutates and is lexicographic by default.
- Use ===, ?. and ?? to avoid the classic coercion and null bugs.