Skip to contentPlayForge

What is the difference between let, const and var?

Written by Jatin Thacker, Automation Architect · Updated

const declares a block-scoped binding that cannot be reassigned. let declares a block-scoped variable that can be reassigned. var declares a function-scoped variable that hoists its declaration with undefined and ignores blocks.

This answer is one piece of Chapter 1: Values and Variables.

let and const were introduced in modern JavaScript (ES6) to eliminate scoping bugs caused by var. Understanding how they differ in scoping, reassignment, and hoisting is fundamental to writing clean test code.

Both const and let are strictly block-scoped: variables declared inside curly braces { ... }, such as an if block or loop, do not exist outside that block. Attempting to access them outside throws a ReferenceError. const prevents reassignment, throwing a TypeError if reassigned. let allows reassignment, making it appropriate for counters, accumulators, and retry attempts.

In contrast, var is function-scoped and completely ignores block boundaries, leaking outside enclosing blocks into the parent scope. Furthermore, var hoists its declaration to the top with an initial value of undefined. In modern test automation, var is avoided completely in favor of const by default and let when reassignment is needed.

var-let-const.mjs(node)
// 1. var hoists declaration with value undefined console.log('hoistedVar:', hoistedVar); var hoistedVar = 'assigned later'; // 2. var ignores block scope and leaks outside { var blockLeaked = 'leaked outside'; } console.log('blockLeaked:', blockLeaked); // 3. let is reassignable let attemptCount = 1; attemptCount = 2; console.log('attemptCount:', attemptCount); // 4. const prevents reassignment const maxAttempts = 3; try { maxAttempts = 4; } catch (err) { console.log('const error:', err.message); } // 5. let is block-scoped (throws ReferenceError outside) { let insideBlock = 'scoped value'; } try { console.log(insideBlock); } catch (err) { console.log('let error:', err.message); }
Output
hoistedVar: undefined
blockLeaked: leaked outside
attemptCount: 2
const error: Assignment to constant variable.
let error: insideBlock is not defined
Test yourself
You declare const attempts = 1; in your test. On the next line, you write attempts = 2;. What happens?

AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.

163 lessons · 226 drills · start free

← All questions

Training a team? Talk to us.