Web & Mobile Development
JavaScript Fundamentals: Types, Scope, Closures, Async and the DOM
Beginner8 min readUpdated
JavaScript rewards a mental model more than memorised syntax: how values coerce, how scope and closures capture variables, what decides the value of this, and how the event loop orders your callbacks. This guide builds those models and then applies them to modules, classes, promises, error handling, the DOM and fetch, with the modern syntax you can rely on today.
What you will learn
- Distinguish primitives from objects and predict how comparison and coercion behave
- Use let, const, closures and modules to control scope and avoid shared-state bugs
- Explain what sets the value of this and when an arrow function is the right choice
- Transform data with array and object methods instead of manual loops and mutation
- Reason about the event loop, and write asynchronous code with promises and async/await
- Manipulate the DOM and call HTTP APIs with fetch, handling errors deliberately
JavaScript is a small language wrapped in a large surface area. Most of the confusion people carry around it — why a comparison returned something surprising, why a variable inside a callback held the wrong value, why this evaporated — comes from four or five underlying rules rather than from the syntax itself. Learn those rules and the rest of the language, including whatever framework you happen to be using, becomes far easier to reason about.
This guide covers that core. It assumes you can already read a for loop and focuses on the model: how values behave, how scope and closures capture them, what determines this, how the event loop schedules your work, and how the standard library expects you to transform data. It uses modern syntax throughout, including features finalised through recent ECMAScript editions, and ends with the DOM and network APIs that most browser code spends its time in.
Values: seven primitives and everything else
There are exactly seven primitive types — string, number, boolean, undefined, null, bigint and symbol — and everything else is an object, including arrays, functions, dates and regular expressions. Primitives are copied by value and are immutable; objects are handled through references, so two variables can point at the same thing.
let a = { count: 1 };
let b = a;
b.count = 2;
console.log(a.count); // 2 — same object
let x = "hi";
let y = x;
y += "!";
console.log(x); // "hi" — strings are immutable
number is a 64-bit float, which is why 0.1 + 0.2 is not 0.3 and why integers above 2^53 lose precision; use bigint (a literal ending in n) for large integers and integer arithmetic on money in minor units. typeof null returns "object", a bug preserved since 1995 for compatibility.
Coercion is where beginners get burned. The operators +, == and the truthiness test all convert types implicitly, and the rules are elaborate. Two habits eliminate almost all of the risk. First, always compare with ===; the sole exception worth keeping is value == null, a compact test for "null or undefined". Second, remember the falsy list exactly — false, 0, -0, 0n, "", null, undefined, NaN — because everything else, including [], {} and "0", is truthy. When you want a default only for null and undefined, use the nullish coalescing operator ?? rather than ||, which would also replace a legitimate 0 or empty string. The same distinction applies to optional chaining: user?.address?.city short-circuits to undefined instead of throwing.
Bindings, scope and closures
let and const are block-scoped and live in a "temporal dead zone" from the top of the block until the declaration executes, so touching them early throws a ReferenceError instead of quietly yielding undefined. var is function-scoped and hoisted, which is the source of a long list of classic bugs. Default to const; it prevents reassignment of the binding, though it does not freeze the object it points at.
A closure is a function together with the scope it was created in. Because the inner function keeps a live reference to the outer variables — not a copy — closures give JavaScript private state:
function createCounter(start = 0) {
let value = start; // captured, not copied
return {
increment: () => ++value,
read: () => value,
};
}
const counter = createCounter(10);
counter.increment();
console.log(counter.read()); // 11
Nothing outside can reach value. This pattern underpins module state, memoisation, event handlers that remember their context, and every "factory" function you will read. The historical gotcha — a loop that created handlers all sharing one var i — disappears with let, which creates a fresh binding per iteration.
Functions, and what decides this
Functions are values: you can pass them, return them and store them. A regular function's this is not determined by where it was written but by how it is called. Called as obj.method(), this is obj. Called bare, this is undefined in strict mode, which module code always is. Called with call, apply or bind, it is whatever you supplied. Called with new, it is the freshly created object.
Arrow functions do not have their own this at all; they close over the one from the surrounding scope, permanently. That is exactly what you want for callbacks and exactly what you do not want for object methods that need a receiver.
const timer = {
seconds: 0,
startBroken() {
setInterval(function () { this.seconds++; }, 1000); // this is not timer
},
startWorking() {
setInterval(() => { this.seconds++; }, 1000); // arrow keeps timer
},
};
Default parameters, rest parameters (...args) and the spread syntax cover almost everything the old arguments object was used for, and unlike it they work in arrow functions and are real arrays.
Objects, destructuring and immutable updates
Object literals support shorthand properties, computed keys and methods. Destructuring pulls values out with defaults and renaming, and spread copies:
const settings = { theme: "dark", locale: "en", retries: 3 };
const { theme, retries = 1, missing = "fallback" } = settings;
const [first, ...rest] = ["a", "b", "c"];
const updated = { ...settings, theme: "light" }; // new object, old untouched
function connect({ host, port = 5432, ssl = true } = {}) { /* ... */ }
Spread is a shallow copy: nested objects are still shared. For a deep clone of plain data, structuredClone(value) is now built in and handles cycles, Maps, Sets and typed arrays, which JSON.parse(JSON.stringify(x)) does not. Preferring new objects to in-place mutation is what makes change detection work in modern frameworks and what makes state easy to reason about generally.
Two collection types deserve more use than they get. Map accepts keys of any type, preserves insertion order and reports its size directly, which makes it better than a plain object for a dictionary with dynamic keys. Set gives cheap membership tests and deduplication — [...new Set(items)] is the idiomatic unique.
Arrays and the methods that replace loops
Array methods express intent, chain cleanly and avoid off-by-one errors.
| Method | Returns | Typical use |
|---|---|---|
map | new array, same length | Transform each element |
filter | new, shorter array | Keep matching elements |
reduce | single value | Fold into a total, object or grouping |
find / findIndex | element or index | First match |
some / every | boolean | Existence and universal tests |
flatMap | flattened new array | Map then flatten one level |
sort | the same array, mutated | Ordering — pass a comparator |
toSorted / toReversed / with | new array | Non-mutating equivalents |
const orders = [
{ id: 1, region: "north", total: 120 },
{ id: 2, region: "south", total: 80 },
{ id: 3, region: "north", total: 45 },
];
const northTotal = orders
.filter((o) => o.region === "north")
.reduce((sum, o) => sum + o.total, 0); // 165
const byRegion = Object.groupBy(orders, (o) => o.region);
const highestFirst = orders.toSorted((a, b) => b.total - a.total);
sort mutates and, without a comparator, compares elements as strings — the reason [10, 9, 1].sort() yields [1, 10, 9]. The newer toSorted, toReversed, toSpliced and with return copies instead, which is usually what you meant. Object.groupBy and Map.groupBy remove the most common hand-written reduce.
Modules and classes
ES modules are the standard unit of code. Each file has its own scope, imports are resolved statically, and everything runs in strict mode:
// money.js
export const CURRENCY = "EUR";
export function format(cents) {
return new Intl.NumberFormat("fr-FR", { style: "currency", currency: CURRENCY })
.format(cents / 100);
}
export default class Money { /* ... */ }
// checkout.js
import Money, { format, CURRENCY } from "./money.js";
const lazy = await import("./heavy-chart.js"); // dynamic, code-split
Prefer named exports: they are greppable, refactorable and give better autocompletion than a default export whose local name every importer invents afresh. Dynamic import() returns a promise and is the mechanism behind lazy-loaded routes.
Classes are syntax over the prototype chain, with real private fields prefixed # that are inaccessible from outside:
class Account {
#balance = 0;
static from(cents) { return new Account(cents); }
constructor(cents = 0) { this.#balance = cents; }
get balance() { return this.#balance; }
deposit(cents) {
if (cents <= 0) throw new RangeError("deposit must be positive");
this.#balance += cents;
return this;
}
}
Composition with plain functions and objects remains a perfectly good alternative; classes earn their place when identity and encapsulated mutable state matter.
The event loop, promises and async/await
JavaScript runs your code on a single thread with a queue. Synchronous work runs to completion; anything asynchronous — a timer, a network response, a click — is scheduled and handled afterwards. Promise callbacks go on the microtask queue, which is drained completely after the current task and before the next timer or rendering step, so a .then() always runs before a setTimeout(..., 0) registered earlier. Blocking the thread with a long loop freezes rendering and input; move that work to a Web Worker.
A promise is a placeholder for a value that is pending, fulfilled or rejected. async/await is syntax over promises: an async function always returns a promise, and await suspends it until the awaited promise settles.
async function loadDashboard(userId) {
// Independent work — start both, then wait once.
const [profile, orders] = await Promise.all([
fetchJson(`/api/users/${userId}`),
fetchJson(`/api/users/${userId}/orders`),
]);
return { profile, orders };
}
The combinators matter: Promise.all rejects as soon as any input rejects, Promise.allSettled waits for all and reports each outcome, Promise.any resolves with the first success, and Promise.race settles with the first to finish — the basis of a timeout. Awaiting inside a loop serialises requests that could have run concurrently, which is the most common avoidable slowdown in async code.
Errors in async functions are ordinary exceptions, so try/catch/finally works, and throw inside one becomes a rejection. Throw Error objects rather than strings so you keep a stack trace, subclass Error for domain failures, and use the cause option to preserve the original when you rewrap. An unhandled rejection is a real defect: attach a catch or let a top-level handler log it.
The DOM, events and fetch
The DOM is the browser's object model of the document. Query it with querySelector and querySelectorAll, build nodes rather than concatenating HTML strings, and remember that assigning to innerHTML with untrusted input is how cross-site scripting happens — textContent is the safe default.
const list = document.querySelector("#orders");
const row = document.createElement("li");
row.textContent = `Order ${order.id}`;
row.dataset.orderId = order.id;
list.append(row);
// One delegated listener instead of one per row.
list.addEventListener("click", (event) => {
const item = event.target.closest("li[data-order-id]");
if (item) openOrder(item.dataset.orderId);
});
Events bubble from the target up through its ancestors, which is what makes delegation work: attach a single handler to a stable parent and it keeps working for rows added later. event.preventDefault() stops the browser's default action; stopPropagation() halts the bubbling and should be used sparingly, because it breaks other listeners. When you add listeners to long-lived objects from a component, keep the AbortController signal so you can remove them all at once.
fetch returns a promise that rejects only on network failure — an HTTP 404 or 500 still resolves, which surprises everyone once:
async function fetchJson(url, options = {}) {
const response = await fetch(url, {
headers: { Accept: "application/json" },
...options,
});
if (!response.ok) {
throw new Error(`${response.status} ${response.statusText} for ${url}`);
}
return response.json();
}
Always check response.ok, and decide what each status means for your caller — the HTTP status code reference covers which ones are worth retrying. Use AbortController to cancel in-flight requests when a component unmounts or a search box changes. When you are debugging a payload by hand, the JSON formatter and the URL encoder/decoder are quicker than a console session, and the ideas here carry straight into a framework — see Angular fundamentals for how the same primitives appear behind a component model.
Key takeaways
- Seven primitives are copied by value and everything else is a reference; use
===, memorise the falsy list, and prefer??and?.to defensive boilerplate. constandletare block-scoped; closures capture live bindings, which is how the language provides private state.- A regular function's
thisdepends on the call site, while an arrow function captures it lexically — that single rule explains most callback surprises. - Transform data with
map,filter,reduceand the newer non-mutatingtoSorted/withmethods, and copy with spread while remembering it is shallow. - The event loop drains microtasks before timers; use
async/awaitfor sequential logic andPromise.allfor independent work rather than awaiting in a loop. - In the browser, prefer
textContenttoinnerHTML, delegate events to a stable ancestor, and always checkresponse.okbecausefetchdoes not reject on HTTP errors.
Sources and further reading
Frequently asked questions
- Should I ever use var?
- In new code, no. var is function-scoped and hoisted as an initialised binding, so it leaks out of blocks and silently allows redeclaration. let and const are block-scoped and stay in the temporal dead zone until the declaration runs, which turns a class of subtle bugs into an immediate error. Default to const, switch to let only when you genuinely reassign, and leave var for reading old code.
- What is the difference between == and ===?
- Strict equality compares type and value with no conversion. Loose equality applies the abstract comparison algorithm first, so a string can equal a number and null equals undefined. The conversion rules are large enough that few people recall them correctly under pressure, so use === everywhere. The one idiom worth keeping is value == null, which tests for null or undefined in a single comparison.
- Why does my this become undefined inside a callback?
- In a normal function, this is decided by how the function is called, not where it was written. Passing a method as a callback detaches it from its receiver, so this becomes undefined in strict mode and module code. Define the callback as an arrow function, which captures this lexically from the enclosing scope, or bind the method explicitly when you hand it over.
- When should I use async/await instead of .then()?
- Prefer async/await for sequential logic: it reads top to bottom, works with ordinary try/catch, and keeps stack traces meaningful. Reach for the promise combinators when the shape is not sequential — Promise.all to run independent work concurrently, Promise.allSettled when you need every outcome regardless of failure, Promise.race for timeouts. Awaiting in a loop that could have been parallel is a common performance mistake.