JavaScript functions, scope, closures and this
Functions are where most JavaScript code lives, and the rules around them explain many of the language’s surprises. This page builds up in a deliberate order: how to write functions, which variables a function can see (scope), what happens to declarations before the code runs (hoisting), how a function keeps access to variables after its outer function has returned (closures), and how this gets its value. Each idea depends on the one before it, so read the sections in order the first time.
The samples follow an invented shop called OrdersPortal. Running the samples: save each complete sample as a .mjs file and run it with Node.js 22 (node sample.mjs). Files ending in .mjs are ES modules and always run in strict mode, which matters for this. The output shown under each sample was produced with Node.js 22.23.
Topics on this page
Section titled “Topics on this page”| Topic | What you learn |
|---|---|
| Functions | Declarations, expressions, arrow functions, parameters and first-class functions. |
| Scope | Global, module, function and block scope, and the scope chain. |
| Hoisting | What is available before its line runs, and the temporal dead zone. |
| Closures | Functions that remember the variables where they were created. |
| The this keyword | How the call decides this, and how arrow functions differ. |
Functions
Section titled “Functions”A function is a reusable block of code that takes inputs (parameters) and can return a value. JavaScript has three common ways to write one:
- Function declaration:
function total(lines) { ... }. It has a name and is hoisted, so it can be called before its line. - Function expression:
const total = function (lines) { ... };. The function is a value assigned to a variable. - Arrow function (ES2015):
const total = (lines) => ...;. A short form with an implicit return for single expressions and no ownthis; see Arrow functions.
Functions are first-class values: you can store them in variables, pass them as arguments (callbacks) and return them from other functions. A function that takes or returns a function is a higher-order function; array methods such as map, filter and reduce are the everyday examples.
Parameters can have default values (rate = 0.2, used when the argument is undefined), and a rest parameter ...codes collects remaining arguments into a real array. A function without a return statement returns undefined.
function lineTotal(line) { return line.price * line.qty;}
const withTax = function (amount, rate = 0.2) { return Math.round(amount * (1 + rate) * 100) / 100;};
const applyCoupons = (amount, ...codes) => codes.reduce((sum, code) => (code === "SAVE5" ? sum - 5 : sum), amount);
function orderTotal(lines, adjust) { const subtotal = lines.map(lineTotal).reduce((a, b) => a + b, 0); return adjust(subtotal); // a function passed in as a value}
const lines = [ { sku: "MUG-01", price: 9.5, qty: 2 }, { sku: "TEE-03", price: 18, qty: 1 },];
console.log(orderTotal(lines, (s) => s));console.log(orderTotal(lines, withTax));console.log(orderTotal(lines, (s) => withTax(applyCoupons(s, "SAVE5", "UNKNOWN"), 0.1)));console.log(typeof lineTotal, lineTotal.name, withTax.length, applyCoupons.name);
function logOnly() {}console.log(logOnly());Output:
3744.435.2function lineTotal 1 applyCouponsundefinedPitfalls:
- Forgetting
returnin a block body.(x) => { x * 2 }returnsundefined; either drop the braces or writereturn. - Calling instead of passing.
button.onclick = save()runssaveimmediately and assigns its result. Passsaveor() => save(order). lengthignores defaults and rest.withTax.lengthis1because counting stops at the first parameter with a default.
Scope decides where a name is visible. JavaScript uses lexical scope: what a function can see is decided by where it is written in the source code, not by where it is called.
The levels, from outermost to innermost:
- Global scope: visible everywhere. In browsers, top-level
varand function declarations in classic scripts become properties ofglobalThis. - Module scope: each ES module file has its own top-level scope, so modules do not leak names into each other.
- Function scope: parameters,
vardeclarations and inner functions belong to the function. - Block scope (ES2015):
let,constandclassdeclarations belong to the nearest{ ... }, such as anifbody or loop.
When code reads a name, JavaScript looks in the current scope, then the enclosing one, and so on up to the global scope: this is the scope chain. Inner scopes can read outer variables, never the reverse. A declaration in an inner scope with the same name shadows the outer one inside that scope. Reading a name that exists nowhere throws a ReferenceError.
const currency = "EUR"; // module scope
function invoice(lines) { let total = 0; // function scope for (const line of lines) { const amount = line.price * line.qty; // block scope: one per iteration total += amount; } if (total > 30) { const currency = "EUR (VAT incl.)"; // shadows the outer currency in this block console.log("inside block:", currency); } console.log("inside function:", currency, total); return total;}
invoice([{ price: 9.5, qty: 2 }, { price: 18, qty: 1 }]);
try { console.log(total);} catch (error) { console.log(error.name + ":", error.message);}
if (true) { var leaked = "var ignores blocks"; let contained = "let stays in the block";}console.log(leaked, "|", typeof contained);Output:
inside block: EUR (VAT incl.)inside function: EUR 37ReferenceError: total is not definedvar ignores blocks | undefinedPitfalls:
varleaks out of blocks. Avarin aniforforbelongs to the whole function. Useletorconst.- Accidental globals. In sloppy-mode scripts, assigning to an undeclared name creates a global. Modules and
"use strict"turn this into aReferenceError. - Shadowing by mistake. Reusing a name such as
totalin an inner block hides the outer one and makes code hard to follow.
Hoisting
Section titled “Hoisting”Before a scope’s code runs, JavaScript processes all of its declarations. Informally this is called hoisting, as if declarations moved to the top. Each kind behaves differently:
- Function declarations are created with their body, so you can call them before their line.
varis created and initialized toundefined, so reading it early givesundefinedinstead of an error.let,constandclassare created but not initialized. From the start of the block until the declaration line runs, the binding is in the temporal dead zone (TDZ), and any access throwsReferenceError: Cannot access 'x' before initialization.- Function expressions and arrow functions follow the rules of the variable that holds them. With
var, the variable isundefined, so calling it throwsTypeError: ... is not a function.
The TDZ is a feature: an early read of a let or const is almost always a bug, and the error points straight at it.
console.log(formatId(7)); // works: function declarations are fully hoistedfunction formatId(n) { return `A-${String(n).padStart(4, "0")}`;}
console.log("var before assignment:", status);var status = "open";
try { console.log(discount);} catch (error) { console.log(error.name + ":", error.message);}let discount = 0.1;
try { sendReceipt();} catch (error) { console.log(error.name + ":", error.message);}var sendReceipt = function () { return "sent";};
try { new Invoice();} catch (error) { console.log(error.name + ":", error.message);}class Invoice {}Output:
A-0007var before assignment: undefinedReferenceError: Cannot access 'discount' before initializationTypeError: sendReceipt is not a functionReferenceError: Cannot access 'Invoice' before initializationPitfalls:
- Reading
varearly silently givesundefined. The program keeps going with a wrong value.letandconstfail loudly instead. - Calling a function expression before its line. Only declarations are hoisted with their body.
- Thinking
letis not hoisted. It is, which is why an innerlet xmakes an outerxunreachable in the whole block, not only after the declaration.
Closures
Section titled “Closures”A closure is a function together with the variables from the scope where it was created. Because scope is lexical, an inner function keeps access to its outer function’s variables even after the outer function has returned. The variables are kept alive as long as the inner function is reachable.
Closures are everywhere in JavaScript: every callback that uses a variable from outside it is one. They are useful for:
- Private state: a counter or cache that only the returned functions can touch.
- Function factories: functions configured once and reused, such as a price formatter for one currency.
- Callbacks that remember context: an event handler that knows which order it belongs to.
Each call of the outer function creates a new scope, so each returned closure has its own copy of the state. A closure captures the variable, not a snapshot of its value: if the variable changes later, the closure sees the new value.
function createOrderNumbers(prefix) { let next = 1000; // private: only the returned functions can reach it return { issue: () => `${prefix}-${++next}`, peek: () => next, };}
const web = createOrderNumbers("WEB");const shop = createOrderNumbers("POS");console.log(web.issue(), web.issue(), shop.issue());console.log("web next:", web.peek(), "| shop next:", shop.peek());
function makeFormatter(currency) { const format = new Intl.NumberFormat("en-US", { style: "currency", currency }); return (amount) => format.format(amount);}const usd = makeFormatter("USD");console.log(usd(1234.5));
const callbacks = [];for (var i = 1; i <= 3; i++) callbacks.push(() => `var: retry ${i}`);for (let j = 1; j <= 3; j++) callbacks.push(() => `let: retry ${j}`);console.log(callbacks.map((f) => f()).join(" | "));Output:
WEB-1001 WEB-1002 POS-1001web next: 1002 | shop next: 1001$1,234.50var: retry 4 | var: retry 4 | var: retry 4 | let: retry 1 | let: retry 2 | let: retry 3Pitfalls:
- Loops with
var. All closures share one variable and see its final value. Aletin the loop head creates a new binding per iteration. - Capturing the variable, not the value. If the outer variable changes before the callback runs, the callback sees the change.
- Accidental memory retention. A long-lived closure (an event listener, a cache) keeps every variable it uses alive. Remove listeners you no longer need.
The this keyword
Section titled “The this keyword”In a regular function or method, this is decided by how the function is called, not where it is defined:
- Method call
order.describe():thisis the object before the dot. - Plain call
describe():thisisundefinedin strict mode (modules, classes and"use strict"code). In sloppy-mode scripts it is the global object instead, which hides bugs. - Explicit:
fn.call(obj, a, b),fn.apply(obj, [a, b])andfn.bind(obj)setthisyourself;bindreturns a new function withthisfixed. - Constructor call
new Order():thisis the new object.
Arrow functions have no this of their own. They use the this of the surrounding code, which is exactly what you want inside a callback within a method, and exactly what you do not want for a method defined directly on an object literal.
The classic bug is passing a method as a callback: setTimeout(order.describe, 0) passes only the function, so the call has no object before the dot and this is lost.
const order = { id: "A-1001", lines: [{ sku: "MUG-01" }, { sku: "TEE-03" }], describe() { return `Order ${this.id}`; }, skus() { return this.lines.map((line) => `${this.id}/${line.sku}`); // arrow keeps this }, arrowDescribe: () => typeof this, // arrow: uses the module top-level this (undefined)};
console.log(order.describe());console.log(order.skus());console.log("arrow method sees this as:", order.arrowDescribe());
const detached = order.describe;try { detached();} catch (error) { console.log(error.name + ":", error.message);}
const bound = order.describe.bind(order);console.log("bound:", bound());console.log("call:", order.describe.call({ id: "B-2002" }));Output:
Order A-1001[ 'A-1001/MUG-01', 'A-1001/TEE-03' ]arrow method sees this as: undefinedTypeError: Cannot read properties of undefined (reading 'id')bound: Order A-1001call: Order B-2002Pitfalls:
- Losing
thisin callbacks. Pass() => order.describe()ororder.describe.bind(order), or define the handler as an arrow-function class field. - Arrow functions as object methods. They do not get the object as
this. Use method shorthanddescribe() {}. - Relying on sloppy-mode
this. In classic scripts a detached call gets the global object and quietly readsundefinedproperties instead of throwing.
Choosing between them
Section titled “Choosing between them”| Need | Prefer |
|---|---|
| A named, reusable helper | Function declaration |
| A short callback | Arrow function |
A method that uses this |
Method shorthand or class method |
| Private state without a class | Closure returned from a factory function |
Fixing this for a callback |
Arrow wrapper or bind |
| A variable visible only inside a block | let or const |
Interview questions
Section titled “Interview questions”1. What is the difference between a function declaration and a function expression? A declaration is hoisted with its body, so it can be called before its line. An expression creates the function when that line runs and follows the hoisting rules of the variable that holds it.
2. What is a closure? Give a practical use. A function plus the variables from the scope where it was created. It lets a function keep private state, such as a counter or cache, or remember configuration, such as a currency formatter, after the outer function has returned.
3. What is the temporal dead zone?
The period from the start of a block to the line that declares a let, const or class binding. The binding exists (it shadows outer names) but reading or writing it throws a ReferenceError.
4. How is this determined in a regular function, and how do arrow functions differ?
By the call: the object before the dot, the argument to call/apply/bind, the new object with new, or undefined for a plain call in strict mode. Arrow functions ignore all of these and use the this of the enclosing scope.
5. Why does for (var i = 0; i < 3; i++) setTimeout(() => console.log(i)) print 3 three times?
var creates one function-scoped i, and all three closures share it. The callbacks run after the loop has finished, when i is 3. With let, each iteration gets its own binding.
6. Senior scenario: a dashboard page slows down and its memory grows every time a user opens and closes an order panel. Each panel adds window.addEventListener("resize", () => this.layout()). What is happening?
The arrow function is a closure over the panel, and the listener keeps it reachable from window, so closed panels are never garbage-collected and their handlers keep running. Keep a reference to the handler and call removeEventListener when the panel closes, or pass an AbortController signal to addEventListener and abort it on close.
Related pages
Section titled “Related pages”- Control flow, errors and async basics: the previous step.
- Objects, arrays and JSON: the next step.
- Core language features: arrow functions, default parameters and destructuring in depth.
- Block bindings: the full rules of block scope and the TDZ.
- Tail calls: recursion and the call stack.