JavaScript Variables: var, let and const Explained with Examples

A variable is a named box that holds a value, such as a user name, a price or the number of failed tests. Every program you write, and every Playwright test, uses variables. In this lesson you will learn how to create variables with let, const and the older var, how scope and hoisting work, why var causes bugs, and the simple rule professionals follow to choose between them.

📖 What You’ll Learn: declaring, assigning and initialising variables, let versus const versus var, block and function scope, redeclaration, hoisting and the temporal dead zone, the classic var-in-a-loop bug, global variables and globalThis, naming rules and best practices.


📦 What Is a Variable?

Definition: a variable is a name that refers to a value stored in memory. You declare a variable to create the name, assign a value with =, and can then read the value by using the name.

📄 variables.js

let userName;            // declaration: the variable exists, value is undefined
console.log(userName);

userName = "Asha";       // assignment
console.log(userName);

let attempts = 3;        // declaration + initialisation in one step
console.log(`${userName} has ${attempts} attempts left`);

⌨️ Terminal

node variables.js

🖥️ Output

undefined
Asha
Asha has 3 attempts left
  • A declared variable that has not been given a value holds undefined.
  • = means “store this value”. It does not mean “equals”; comparison uses ===.
  • Giving a value at declaration time is called initialisation, and is the usual style.

🔑 let, const and var

JavaScript has three keywords for declaring variables:

constletvar
Can be reassignedNoYesYes
Must be initialisedYesNoNo
ScopeBlockBlockFunction
Can be redeclared in the same scopeNoNoYes
Use before declarationReferenceError (TDZ)ReferenceError (TDZ)undefined
Introduced inES2015ES2015ES1 (1997)

let declares a variable whose value can change:

📄 let.js

let score = 0;
score = score + 10;
score += 5;          // shorthand for score = score + 5
console.log("Score:", score);

⌨️ Terminal

node let.js

🖥️ Output

Score: 15

const declares a constant binding: the name cannot be pointed at a new value. Trying to reassign it throws a TypeError:

📄 const.js

const BASE_URL = "https://sqatools.in";
console.log(BASE_URL);

BASE_URL = "https://example.com";

⌨️ Terminal

node const.js

🖥️ Output

https://sqatools.in
/home/you/js-course/const.js:4
BASE_URL = "https://example.com";
         ^

TypeError: Assignment to constant variable.
    at Object.<anonymous> (/home/you/js-course/const.js:4:10)

Node.js v26.13.0

⚠️ Watch out: const does not make objects and arrays read-only. It only stops you from assigning a new value to the name. You can still change what is inside:

📄 const-object.js

const user = { name: "Asha", role: "tester" };
user.role = "lead";          // allowed: changing a property
console.log(user);

const tags = ["smoke"];
tags.push("regression");     // allowed: changing the array
console.log(tags);

⌨️ Terminal

node const-object.js

🖥️ Output

{ name: 'Asha', role: 'lead' }
[ 'smoke', 'regression' ]

To make an object truly read-only, use Object.freeze(), covered in the Object Methods lesson.


🧱 Scope: Block Scope vs Function Scope

Definition: the scope of a variable is the part of the code where the name can be used. let and const are block-scoped: they exist only inside the nearest { }. var is function-scoped: it ignores blocks such as if and for and belongs to the whole function.

📄 scope.js

function checkStatus(code) {
  if (code === 200) {
    var viaVar = "passed (var)";
    let viaLet = "passed (let)";
  }
  console.log(viaVar);              // var leaks out of the if block
  console.log(typeof viaLet);       // let does not exist here
}

checkStatus(200);

⌨️ Terminal

node scope.js

🖥️ Output

passed (var)
undefined

Using the block-scoped variable outside its block is an error:

📄 block.js

if (true) {
  let message = "inside";
}
console.log(message);

⌨️ Terminal

node block.js

🖥️ Output

/home/you/js-course/block.js:4
console.log(message);
            ^

ReferenceError: message is not defined
    at Object.<anonymous> (/home/you/js-course/block.js:4:13)

Node.js v26.13.0

💡 Tip: Block scope is a feature, not a limitation. Variables that live only as long as they are needed cannot be changed by accident somewhere else in the program.


♻️ Redeclaration

var lets you declare the same name twice, which can silently overwrite a value you still need. let and const refuse:

📄 redeclare-var.js

var env = "qa";
var env = "prod";     // allowed with var: the first value is lost
console.log(env);

⌨️ Terminal

node redeclare-var.js

🖥️ Output

prod

📄 redeclare-let.js

let env = "qa";
let env = "prod";
console.log(env);

⌨️ Terminal

node redeclare-let.js

🖥️ Output

/home/you/js-course/redeclare-let.js:2
let env = "prod";
    ^

SyntaxError: Identifier 'env' has already been declared

Node.js v26.13.0

Because this is a SyntaxError, the file does not run at all. You find the mistake immediately instead of debugging a wrong value later.


⏳ Hoisting and the Temporal Dead Zone (TDZ)

Definition: hoisting means that JavaScript registers every declaration in a scope before running any code in it. var variables are created and set to undefined at that moment. let and const are created but stay uninitialised until their declaration line runs. The period before that line is the temporal dead zone (TDZ).

📄 hoist-var.js

console.log(total);   // var is hoisted with the value undefined
var total = 100;
console.log(total);

⌨️ Terminal

node hoist-var.js

🖥️ Output

undefined
100

📄 tdz.js

console.log(count);   // let is in the temporal dead zone here
let count = 5;

⌨️ Terminal

node tdz.js

🖥️ Output

/home/you/js-course/tdz.js:1
console.log(count);   // let is in the temporal dead zone here
            ^

ReferenceError: Cannot access 'count' before initialization
    at Object.<anonymous> (/home/you/js-course/tdz.js:1:13)

Node.js v26.13.0

The error message is precise: the variable exists (so it is not “not defined”), but you cannot access it yet. This catches order-of-code bugs that var would hide behind an undefined.


🔁 The Classic var-in-a-Loop Bug

This bug appears in interviews and in real code that schedules work in a loop. With var there is only one i for the whole loop, so every callback sees its final value:

📄 loop-var.js

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log("var i =", i), 0);
}

⌨️ Terminal

node loop-var.js

🖥️ Output

var i = 3
var i = 3
var i = 3

With let, every loop iteration gets its own copy of i:

📄 loop-let.js

for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log("let i =", i), 0);
}

⌨️ Terminal

node loop-let.js

🖥️ Output

let i = 0
let i = 1
let i = 2
  • setTimeout(fn, 0) runs fn after the loop has finished (you will learn why in the Event Loop lesson).
  • By then the single var i has become 3; the three let i bindings still hold 0, 1 and 2.

🌍 Global Variables and globalThis

A variable declared outside every function and block is global to its file. Where it ends up depends on how the file is loaded:

  • In a classic browser <script>, top-level var becomes a property of window; top-level let/const are global but not on window.
  • In Node.js and in ES modules, each file has its own scope, so top-level variables are not shared with other files.
  • globalThis is the standard name for the global object everywhere (window in browsers, global in Node.js).

📄 globals.js

var appName = "sqatools";
let version = 2;

console.log(appName, version);           // usable in this file
console.log(globalThis.appName);         // undefined: Node.js files have their own scope
console.log(typeof globalThis.setTimeout); // built-in globals live on globalThis

⌨️ Terminal

node globals.js

🖥️ Output

sqatools 2
undefined
function

⚠️ Watch out: Avoid global variables for test data. Tests that share and change globals affect each other and fail randomly when run in parallel. Pass values as function arguments or use test fixtures instead.


🏷️ Naming Rules and Best Practices

  • Names may contain letters, digits, _ and $, must not start with a digit and must not be reserved words (see the Syntax lesson).
  • Use camelCase: orderTotal, isLoggedIn.
  • Use UPPER_SNAKE_CASE for fixed configuration values: MAX_RETRIES, BASE_URL.
  • Choose descriptive names: retryCount beats rc or x.

The rule professionals use

  1. Use const by default.
  2. Switch to let only when the variable must be reassigned (counters, totals, values that change in a loop).
  3. Do not use var in new code. You still need to understand it, because you will meet it in older code and interviews.

📄 retry.js

// Test configuration and a retry loop written with the rule above
const MAX_RETRIES = 3;
const endpoint = "/api/orders";

let attempt = 0;
let success = false;

while (!success && attempt < MAX_RETRIES) {
  attempt++;
  success = attempt === 2; // pretend the second attempt succeeds
  console.log(`Attempt ${attempt} on ${endpoint}: ${success ? "ok" : "failed"}`);
}

⌨️ Terminal

node retry.js

🖥️ Output

Attempt 1 on /api/orders: failed
Attempt 2 on /api/orders: ok

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Declare a constant COURSE with the value "JavaScript" and a variable lesson starting at 1. Increase lesson to 6 and print JavaScript lesson 6.

Show answer

📄 practice1.js

const COURSE = "JavaScript";
let lesson = 1;
lesson = 6;
console.log(`${COURSE} lesson ${lesson}`);

🖥️ Output

JavaScript lesson 6

Q2. Predict the output, then run it.

var a = 1;
{
  var a = 2;
}
let b = 1;
{
  let b = 2;
}
console.log(a, b);
Show answer

📄 practice2.js

var a = 1;
{
  var a = 2;
}
let b = 1;
{
  let b = 2;
}
console.log(a, b);

🖥️ Output

2 1

var ignores the block, so the inner var a = 2 replaces the outer value. The inner let b is a new variable that exists only inside its block.

Q3. Swap the values of first = "login" and second = "logout" using a temporary variable.

Show answer

📄 practice3.js

let first = "login";
let second = "logout";

let temp = first;
first = second;
second = temp;

console.log(first, second);

🖥️ Output

logout login

Later in the course you will see the shorter destructuring version: [first, second] = [second, first];.

Q4. This code throws an error. Explain why and fix it while still adding "api" to the tags.

const tags = ["ui"];
tags = [...tags, "api"];
Show answer

Assigning a new array to a const name throws TypeError: Assignment to constant variable. Either change the array in place, or use let if you really need a new array.

📄 practice4.js

const tags = ["ui"];
tags.push("api");
console.log(tags);

🖥️ Output

[ 'ui', 'api' ]

Q5. Rewrite this loop so it prints 0, 1 and 2 instead of 3, 3 and 3.

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}
Show answer

📄 practice5.js

for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}

🖥️ Output

0
1
2

let creates a new binding for every iteration, so each callback keeps its own value.

Q6. Write a test-run summary: use constants for the suite name and total tests (20), and let counters for passed and failed. Record 17 passes and 3 failures with loops or assignments, then print Checkout suite: 17 passed, 3 failed of 20.

Show answer

📄 practice6.js

const SUITE = "Checkout";
const TOTAL = 20;
let passed = 0;
let failed = 0;

for (let i = 1; i <= TOTAL; i++) {
  if (i <= 17) passed++;
  else failed++;
}

console.log(`${SUITE} suite: ${passed} passed, ${failed} failed of ${TOTAL}`);

🖥️ Output

Checkout suite: 17 passed, 3 failed of 20

🧠 MCQ Quiz: Variables: var, let, const

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Which keyword should you use by default for a new variable?
  2. What happens with const x = 1; x = 2;?
  3. Is this allowed?
    const list = [1];
    list.push(2);
  4. What is the scope of a var declared inside an if block in a function?
  5. What does this print?
    console.log(x);
    var x = 5;
  6. What does this throw?
    console.log(y);
    let y = 5;
  7. What does let a = 1; let a = 2; in the same scope cause?
  8. Why does a for (var i...) loop with setTimeout print 3, 3, 3?
  9. Which declaration is invalid?
  10. What is globalThis?

💼 Interview Questions and Answers

Q1. What is the difference between var, let and const?

var is function-scoped, can be redeclared, and is hoisted with the value undefined. let and const are block-scoped, cannot be redeclared in the same scope, and are in the temporal dead zone until declared. const must be initialised and cannot be reassigned, though objects it points to can still change. In modern code use const by default, let when reassignment is needed, and avoid var.

Q2. What is the temporal dead zone?

It is the time between entering a scope and running the let, const or class declaration in it. The binding already exists (it is hoisted), but accessing it throws ReferenceError: Cannot access 'x' before initialization. The TDZ exists to catch code that uses a variable before it has a meaningful value.

Q3. Are let and const hoisted?

Yes. All declarations are hoisted to the top of their scope. The difference is initialisation: var is initialised to undefined immediately, while let and const remain uninitialised (TDZ) until their line runs. That is why reading them early throws an error instead of returning undefined.

Q4. Can you change an object declared with const? How do you prevent it?

Yes, its properties can be added, changed or deleted, because const only fixes which object the name refers to. To prevent changes, use Object.freeze(obj), which makes the object’s own properties read-only (shallow). For nested objects you need a deep-freeze helper.

📄 freeze.js

const config = Object.freeze({ retries: 2 });
config.retries = 5;          // ignored outside strict mode
console.log(config.retries);

⌨️ Terminal

node freeze.js

🖥️ Output

2

Q5. Predict the output and explain it.

📄 interview-loop.js

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i));
}
for (let j = 0; j < 3; j++) {
  setTimeout(() => console.log(j));
}

⌨️ Terminal

node interview-loop.js

🖥️ Output

3
3
3
0
1
2

The callbacks run after both loops finish. The var loop shares one i, which ends at 3, so it prints 3 three times. The let loop creates a fresh j per iteration, so it prints 0, 1, 2.

Q6. Why are shared global variables a problem in test automation?

Tests should be independent. If tests read and change a global (for example a shared let currentUser), the result depends on which test ran first, and parallel workers can overwrite each other’s values. This creates flaky tests. Keep data inside each test, create it in hooks or fixtures, and use const for configuration that never changes.


❓ Frequently Asked Questions

🤔 Should I ever use var in 2026?

Not in new code. let and const fix var’s scope and hoisting problems. Learn var so you can read older code and answer interview questions.

🤔 Is const faster than let?

Not in any way you will notice. Choose const because it communicates that the value will not be reassigned and prevents accidental reassignment.

🤔 Can a variable change its type in JavaScript?

Yes. JavaScript is dynamically typed, so let x = 5; x = "five"; is valid. TypeScript can prevent this if you want type safety.

🤔 What is the default value of a declared variable?

A variable declared with let or var but not assigned holds undefined. A const must always be given a value.


🏁 Summary

  • Variables are named references to values; declare them with const, let or var.
  • const cannot be reassigned (but object contents can change); let can.
  • let/const are block-scoped; var is function-scoped and can be redeclared.
  • All declarations are hoisted, but let/const stay in the temporal dead zone until declared.
  • Rule of thumb: const by default, let when you must reassign, never var in new code.

Next, continue with Lesson 7: Data Types. For extra practice, solve the JavaScript variables practice programs.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in