LearnFrenzy
Sign in Take a free test
JS

JavaScript Programming · Topic 2 of 25

Variables: var, let and const Questions and Concepts

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Variables: var, let and const · Study material

"What is the difference between var, let and const?" is the most asked JavaScript interview question – and it is really four questions: scope, hoisting, redeclaration and reassignment. Behind them sit the ideas that output questions test again and again: the temporal dead zone, why const objects can still change, and why a var loop with setTimeout prints 3, 3, 3. This topic explains all of them with runnable examples. Then test yourself with 60 practice questions – 15 MCQs, 20 predict-the-output puzzles, 15 debugging questions and 10 coding problems – every one run on Node.js.

var vs let vs const at a glance

varletconst
Scopefunction (or global)block { }block { }
Hoistedyes, initialised to undefinedyes, but uninitialised (TDZ)yes, but uninitialised (TDZ)
Redeclare in the same scopeallowedSyntaxErrorSyntaxError
ReassignallowedallowedTypeError
Must be initialisednonoyes
Top-level in a browser scriptbecomes a window propertynot on windownot on window
Use it?avoid in new codewhen the value changesby default

Function scope vs block scope

A var belongs to the whole function it is declared in (or to the global scope), so it is visible outside the if, for or { } block where it was written. let and const exist only inside their block.

function demo() {
  if (true) {
    var a = "var";       // function-scoped: belongs to demo()
    let b = "let";       // block-scoped: belongs to the if-block
    const c = "const";   // block-scoped too
  }
  console.log(a);                 // var leaks out of the block
  console.log(typeof b, typeof c); // b and c do not exist here
}
demo();

Output

var
undefined undefined

Hoisting and the temporal dead zone

Before running a scope, the engine registers all its declarations – this is hoisting. A var is created and set to undefined, so reading it early gives undefined. A let or const is created but left uninitialised: from the start of the block until its declaration line runs, it is in the temporal dead zone (TDZ), and any access – even typeof – throws a ReferenceError.

console.log(city);        // var is hoisted and set to undefined
var city = "Pune";
console.log(city);

try {
  console.log(country);   // let is hoisted too, but stays uninitialised (TDZ) until its line runs
  let country = "India";
} catch (e) {
  console.log(e.name);
}

Output

undefined
Pune
ReferenceError

Redeclaring and reassigning

Declaring the same var twice is silently allowed; declaring a let or const twice in the same scope is a SyntaxError found before the script runs. Assigning a new value works for var and let; for const it throws a TypeError at run time.

var x = 1;
var x = 2;            // var: redeclaring is allowed (and hides mistakes)
console.log(x);

let y = 1;
y = 5;                // let: reassigning is fine, redeclaring in the same scope is a SyntaxError
console.log(y);

const z = 1;
try {
  z = 2;              // const: the binding can never be reassigned
} catch (e) {
  console.log(e.name);
}

Output

2
5
TypeError

const does not make objects immutable

const fixes the binding – the variable always points to the same object – but the object's properties and an array's elements can still change. To stop changes to the object itself, use Object.freeze(), which is shallow: nested objects stay writable unless you freeze them too. Writing to a frozen property is ignored in normal scripts and throws a TypeError in strict mode.

const user = { name: "Asha", skills: ["JS"] };
user.name = "Asha Rao";        // allowed: const protects the variable, not the object
user.skills.push("React");
console.log(user);

const settings = Object.freeze({ theme: "dark" });
try {
  settings.theme = "light";    // frozen object: throws in strict mode, ignored silently otherwise
} catch (e) {
  console.log(e.name);
}
console.log(settings.theme);

Output

{ name: 'Asha Rao', skills: [ 'JS', 'React' ] }
TypeError
dark

Shadowing

An inner scope may declare a variable with the same name as an outer one; inside the inner scope the new variable shadows the outer one. Shadowing a let with a var inside a block is not allowed – the var would be hoisted into the same scope as the let – and is a SyntaxError.

let level = "global";
function show() {
  let level = "function";     // shadows the outer level inside show()
  {
    let level = "block";      // shadows again inside this block
    console.log(level);
  }
  console.log(level);
}
show();
console.log(level);

Output

block
function
global

The classic loop question

A for loop with var has one variable shared by every iteration, so callbacks that run later (timers, event handlers) all see its final value. With let, each iteration gets a new binding holding that iteration's value. Before ES6 the fix was an IIFE (see Coding Techniques).

// var: ONE i shared by every callback – they run after the loop, when i is already 3
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log("var:", i), 0);
}
// let: a NEW j for every iteration – each callback remembers its own value
for (let j = 0; j < 3; j++) {
  setTimeout(() => console.log("let:", j), 0);
}

Output

var: 3
var: 3
var: 3
let: 0
let: 1
let: 2

Implicit globals

In a normal (non-strict) script, assigning to a name that was never declared – total = 5 – silently creates a property on the global object, visible everywhere. In strict mode and in modules it throws a ReferenceError. Always declare variables, and keep loop counters declared with let.

Common mistakes

  • Using a let/const before its line – ReferenceError (TDZ), not undefined.
  • A local var hoisted over a global – reading it before its assignment gives undefined.
  • var in loops with callbacks – every callback sees the last value.
  • Thinking const freezes objects – only the binding is constant.
  • Forgetting let in a loop – the counter becomes a shared global.
  • Shadowing by accident – a let inside the loop hides the total you meant to update.

Key points to remember

  • var is function-scoped; let and const are block-scoped.
  • All three are hoisted; only var is initialised (to undefined).
  • The TDZ runs from the start of the block to the declaration line.
  • let/const cannot be redeclared in the same scope; const cannot be reassigned.
  • const objects can be mutated; Object.freeze is shallow.
  • let in a for loop creates a new binding per iteration.
  • Prefer const, use let when the value changes, avoid var.

Frequently asked questions

Are let and const hoisted?

Yes. They are registered when the scope starts – that is why they can shadow an outer variable from the very first line of the block – but they cannot be used until their declaration runs.

Should I ever use var?

Not in new code. You still need to read it: older code, interview questions and some libraries use var, and its hoisting and function scope explain many output puzzles.

Is const faster than let?

Not measurably. Use const because it tells the reader the variable will not be reassigned, and lets tools catch accidental reassignment.

Where can I learn more?

Read let, const and var and JavaScript Closures in the JavaScript tutorial, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About JavaScript Programming

Why it matters

  • JavaScript runs every web page and, with Node.js, servers, tools and APIs – it is the most used language in the world
  • Front-end, full-stack and MERN roles test JavaScript first, and many campus coding rounds allow it
  • "Predict the output" questions on hoisting, closures, this, coercion and the event loop are interview favourites
  • Modern ES6+ – let/const, arrow functions, destructuring, promises and async/await – is what companies expect from freshers

Who it is for

  • College students (B.Tech, BCA, MCA, B.Sc CS) learning web development and preparing for semester exams and viva
  • Freshers preparing for campus placements, online assessments and front-end interviews
  • Developers moving to React, Angular, Vue or Node.js who need strong core JavaScript
  • Anyone revising ES6 and asynchronous JavaScript before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs on concepts and ES6 features
  • "Predict the output" puzzles – hoisting, coercion, closures, promises and timers
  • "Find the error" debugging: SyntaxError, ReferenceError, TypeError and silent logic bugs
  • Coding problems with solutions and real output, every one run on Node.js – run any study example in your browser

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture, Cognizant tests
  • Front-end developer interviews
  • MERN / full-stack interviews
  • Online coding assessments
  • University practicals

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, debugging, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links