var and Hoisting in JavaScript: Function Scope and Why let Replaced It
How the old var keyword works and why you still need to understand it: function scope instead of block scope, hoisting of var and function declarations (and what "hoisting" really means), redeclaration, var in loops and the classic closure bug, IIFEs, and how to modernize var code safely.
kvi5hnuCode Sprout team member6 min readOn this page
Before ES2015, var was the only way to declare a variable. Modern code uses let and const, but var is far from gone: it's in older codebases, Stack Overflow answers, libraries, and, very often, in interview questions. Understanding it also explains hoisting, a concept that applies to every declaration in JavaScript.
var looks like let, but scopes differently
The syntax is the same as let. The difference is scope: a var belongs to the whole enclosing function (or the global scope), not to the block it's written in.
function checkout(isMember) {
if (isMember) {
var discount = 0.1; // function-scoped: visible in all of checkout
let badge = "member"; // block-scoped: visible only inside the if
}
console.log(discount); // the var leaked out of the block
console.log(typeof badge); // the let didn't
}
checkout(true);
checkout(false); // the var exists even when the block never ran
0.1
undefined
undefined
undefined
In the second call the if block never runs, yet discount exists (as undefined) and reading it doesn't throw. That's hoisting at work.
Hoisting
When a function starts running (or a script starts), the engine first scans the scope for declarations and creates all of them before executing any line. This is called hoisting, because the effect is as if declarations were lifted to the top. What each declaration is set to initially depends on its kind:

| Declaration | Created at scope start? | Initial value | Using it before its line |
|---|---|---|---|
var x | yes | undefined | gives undefined |
function f() {} | yes | the whole function | works |
let, const, class | yes | uninitialized | throws ReferenceError (the temporal dead zone, article 27) |
import | yes | the imported binding | works |
function expressions, arrows in var/let/const | only the variable | follows the variable's rule | can't be called yet |
function visit() {
console.log(greeting); // var: exists, but not assigned yet
helper(); // function declaration: fully hoisted
try {
console.log(count); // let: in the temporal dead zone
} catch (err) {
console.log(err.name);
}
var greeting = "hi";
let count = 0;
function helper() { console.log("helper ran"); }
console.log(greeting, count);
}
visit();
undefined
helper ran
ReferenceError
hi 0
Only the declaration is hoisted, never the assignment. var greeting = "hi" behaves like var greeting; at the top of the function plus greeting = "hi"; where you wrote it.
Function declarations vs function expressions
Function declarations are hoisted completely, so you can call them before they appear. That lets you put the main logic at the top of a file and helpers below. Function expressions are just values assigned to variables, so they follow the variable's rules:
console.log(square(4)); // declaration: works before its line
try {
cube(2); // var holding a function: still undefined
} catch (err) {
console.log(err.name);
}
function square(n) { return n * n; }
var cube = function (n) { return n ** 3; };
console.log(cube(2));
16
TypeError
8
The error is a TypeError ("cube is not a function"), not a ReferenceError: the variable exists, but its value is undefined, and undefined can't be called. With const cube = ..., the same early call would throw a ReferenceError instead.
Redeclaration is allowed
var lets you declare the same name again in the same scope, silently:
var total = 10;
var total; // ignored: total keeps its value
console.log(total);
var total = 20; // just an assignment
console.log(total);
10
20
This made it easy to accidentally reuse a variable name from elsewhere in a long function. let and const make a duplicate declaration a SyntaxError.
Global var becomes a global object property
At the top level of a classic browser script, var creates a property on the global object (window.total), unlike let and const (article 20). In modules, var stays module-scoped like everything else.
The classic loop bug
This is the most famous var problem, and a very common interview question. Functions created in a loop capture the loop variable, but with var there's only one variable for the whole loop:
const withVar = [];
for (var i = 0; i < 3; i++) {
withVar.push(() => i); // every function shares the same i
}
console.log(withVar.map(fn => fn()));
const withLet = [];
for (let j = 0; j < 3; j++) {
withLet.push(() => j); // a fresh j for each iteration
}
console.log(withLet.map(fn => fn()));
[ 3, 3, 3 ]
[ 0, 1, 2 ]
By the time the functions run, the loop has finished and the single shared i is 3. With let, the specification creates a new binding for every iteration, copying the current value forward, so each function remembers its own j. The same bug appears with setTimeout(() => console.log(i), 100) inside a var loop, which logs 3 three times.
Before let, the fix was an IIFE (immediately invoked function expression) that creates a new function scope per iteration:
const fixed = [];
for (var k = 0; k < 3; k++) {
(function (captured) {
fixed.push(() => captured);
})(k);
}
console.log(fixed.map(fn => fn()));
[ 0, 1, 2 ]
IIFEs: function scope as a privacy tool
Because var only respected function boundaries, older code wrapped whole files or modules in an IIFE to keep variables out of the global scope:
const counter = (function () {
var count = 0; // private: nothing outside can touch it
return {
increment() { return ++count; },
reset() { count = 0; },
};
})();
counter.increment();
console.log(counter.increment(), typeof count);
2 undefined
You'll still see this "module pattern" in older libraries. Today, ES modules (part 10) give every file its own scope, and block scope with let/const handles smaller cases, so new code rarely needs IIFEs.
Modernizing var code
Converting var to let/const is usually safe, with a few things to check first:
- Uses before the declaration: with
let, they throw instead of readingundefined. Move the declaration up. - Variables used outside the block where they're declared: with
let, they're no longer visible. Move the declaration to the outer scope. - Redeclarations: merge them into one declaration.
- Globals: top-level
varin a classic script was awindowproperty; other scripts might rely onwindow.namestyle access. - Then choose
constfor everything not reassigned.
ESLint's no-var and prefer-const rules, with --fix, automate the easy cases.
Common questions
Does hoisting physically move code?
No. It's a mental model for what happens: before running a scope, the engine processes all declarations in it. Your code stays where it is; the effect is as if declarations were at the top.
Are let and const hoisted?
Yes, in the sense that they're created when the scope starts, which is why an inner let shadows an outer variable for the whole block, even above its declaration. But they aren't initialized until their declaration runs, so accessing them earlier throws a ReferenceError. Article 27 covers this temporal dead zone.
What happens if a var and a function have the same name?
The function declaration wins during hoisting (the name refers to the function at the start of the scope), and the var declaration is ignored, but a var assignment later replaces the value when it runs. Never reuse a name like this; it's confusing and linters flag it.
Should I ever use var today?
Practically never in new code. The only niche uses are rare: needing a variable that's deliberately visible across a whole function regardless of blocks, or code that must run in pre-2015 engines without a build step.
Summary
varis function-scoped (or global), ignores blocks, can be redeclared, and at the top level of classic scripts createswindowproperties.- Hoisting means declarations are processed before a scope runs:
varstarts asundefined, function declarations start fully defined, andlet/const/classstart uninitialized (accessing them throws). - Only declarations are hoisted, never assignments; function expressions follow their variable's rules.
- A
varloop variable is shared by all closures created in the loop;letcreates a new binding per iteration. - IIFEs were the pre-module way to create private scope. Replace
varwithlet/const, checking early uses, block leaks and redeclarations.
Practice Questions
What does this log?
console.log(a);
var a = 1;
console.log(a);
Answer
undefined then 1. The declaration is hoisted; the assignment happens on its line.
What does this log?
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i));
Answer
3, 3, 3. All three callbacks share one i, which is 3 when they run after the loop ends. Changing var to let logs 0, 1, 2.
Why does calling f() before var f = function () {} throw a TypeError rather than a ReferenceError?
Answer
The variable f is hoisted and initialized to undefined, so it exists; calling undefined throws "f is not a function", a TypeError.
In which scope is x visible?
function outer() {
if (true) {
var x = 1;
}
}
Answer
Throughout outer, both inside and after the if block, but not outside outer.
Write the var loop with closures so it logs 0, 1, 2 without using let.
Answer
Wrap the body in an IIFE that takes the current value as a parameter: the code below. Each call creates a new scope with its own n.
for (var i = 0; i < 3; i++) {
(function (n) { setTimeout(() => console.log(n)); })(i);
}
Previous: Declaring Variables in JavaScript: let, const and Naming
Next: Scope in JavaScript: Block, Function, Module and Global Scope and the Temporal Dead Zone

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.