Introduction
In JavaScript, variables are declared using the keywords var, let, and const. Although all three are used to declare variables, they differ in terms of scope, hoisting, reassignment, and redeclaration.
Understanding these differences is essential for writing clean, maintainable, and bug-free JavaScript code.
-
varis the traditional way of declaring variables and has been available since the early versions of JavaScript. -
letandconstwere introduced in ES6 (ECMAScript 2015) to address many of the issues associated withvar.
In modern JavaScript development, let and const are preferred over var.
For automation engineers, choosing the correct variable declaration improves test reliability, reduces unexpected bugs, and makes automation scripts easier to maintain.
Variable Declaration Keywords
JavaScript provides three keywords for declaring variables:
-
var -
let -
const
Each behaves differently.
Declaring Variables with var
var name = "John";
console.log(name);
Output
John
Declaring Variables with let
let city = "Bengaluru";
console.log(city);
Output
Bengaluru
Declaring Variables with const
const country = "India";
console.log(country);
Output
India
Scope Differences
var is Function Scoped
function demo() {
var message = "Hello";
console.log(message);
}
demo();
Output
Hello
The variable exists throughout the function.
let is Block Scoped
if (true) {
let age = 25;
console.log(age);
}
Output
25
The variable exists only inside the if block.
const is Block Scoped
if (true) {
const company = "OpenAI";
console.log(company);
}
Output
OpenAI
Like let, const is block-scoped.
Redeclaration
var Allows Redeclaration
var language = "JavaScript";
var language = "Python";
console.log(language);
Output
Python
let Does Not Allow Redeclaration
let language = "JavaScript";
let language = "Python";
Output
SyntaxError: Identifier 'language' has already been declared
const Does Not Allow Redeclaration
const language = "JavaScript";
const language = "Python";
Output
SyntaxError: Identifier 'language' has already been declared
Reassignment
var Can Be Reassigned
var score = 80;
score = 95;
console.log(score);
Output
95
let Can Be Reassigned
let score = 80;
score = 95;
console.log(score);
Output
95
const Cannot Be Reassigned
const score = 80;
score = 95;
Output
TypeError: Assignment to constant variable.
const with Objects and Arrays
const prevents reassignment of the variable, not modification of the object’s or array’s contents.
const user = {
name: "John"
};
user.name = "Alice";
console.log(user);
Output
{ name: 'Alice' }
The object can still be modified.
Hoisting Behavior
var
console.log(message);
var message = "Hello";
Output
undefined
var declarations are hoisted and initialized with undefined.
let
console.log(message);
let message = "Hello";
Output
ReferenceError: Cannot access 'message' before initialization
let is hoisted but remains in the Temporal Dead Zone (TDZ) until its declaration.
const
console.log(message);
const message = "Hello";
Output
ReferenceError: Cannot access 'message' before initialization
const also remains in the Temporal Dead Zone (TDZ) until its declaration.
Real-World Example
Store application configuration.
const baseUrl = "https://example.com";
let currentUser = "admin";
console.log(baseUrl);
console.log(currentUser);
Output
https://example.com
admin
baseUrl never changes, while currentUser may change during program execution.
Another example:
Update a shopping cart.
let totalItems = 2;
totalItems++;
console.log(totalItems);
Output
3
Automation Testing Example
Playwright Example
Store a browser name.
const browser = "Chromium";
console.log(browser);
Output
Chromium
Selenium Example
Update the page title.
let pageTitle = "Login";
pageTitle = "Dashboard";
console.log(pageTitle);
Output
Dashboard
Cypress Example
Loop through test cases.
for (let i = 1; i <= 3; i++) {
console.log("Running Test " + i);
}
Output
Running Test 1
Running Test 2
Running Test 3
API Testing Example
Store an API endpoint.
const apiEndpoint = "/users";
console.log(apiEndpoint);
Output
/users
Data-Driven Testing Example
Store a temporary username.
let username = "admin";
console.log(username);
Output
admin
Comparison Table
| Feature | var |
let |
const |
|---|---|---|---|
| Introduced | Before ES6 | ES6 | ES6 |
| Scope | Function | Block | Block |
| Redeclaration | Yes | No | No |
| Reassignment | Yes | Yes | No |
| Hoisted | Yes | Yes (TDZ) | Yes (TDZ) |
| Initialized During Hoisting | undefined |
No | No |
| Recommended for Modern Code | No | Yes | Yes |
Common Mistakes
Using var Inside Loops
for (var i = 1; i <= 3; i++) {
}
console.log(i);
Output
4
The variable i is still accessible because var is function-scoped.
Reassigning a const
const pi = 3.14;
pi = 3.14159;
Output
TypeError: Assignment to constant variable.
Redeclaring a let
let count = 5;
let count = 10;
Output
SyntaxError
Best Practices
Use const by Default
Declare variables with const unless you know the value will change.
const appName = "Inventory System";
Use let for Changing Values
Use let when reassignment is expected.
let total = 0;
total += 10;
Avoid Using var
Modern JavaScript development recommends avoiding var because its function scope and hoisting behavior can lead to confusing bugs.
Keep Variable Scope as Small as Possible
Declare variables only where they are needed to improve readability and reduce unintended side effects.
Conclusion
Although var, let, and const all declare variables, they have important differences in scope, redeclaration, reassignment, and hoisting.
In modern JavaScript, const should be your first choice for values that do not change, while let is ideal for variables that need to be updated. The use of var is generally discouraged because it can introduce unexpected behavior due to function scope and hoisting.
For automation engineers, using let and const helps create cleaner, safer, and more maintainable automation scripts.
Frequently Asked Questions (FAQs)
What is the difference between let and var?
let is block-scoped, while var is function-scoped.
What is the difference between let and const?
Both are block-scoped, but let allows reassignment, whereas const does not.
Can a const object be modified?
Yes. The object’s properties can be modified, but the variable itself cannot be reassigned.
Which keyword should I use in modern JavaScript?
Use const by default and let when the value needs to change. Avoid var unless maintaining legacy code.
Are let and const hoisted?
Yes, but they remain in the Temporal Dead Zone (TDZ) until their declarations are executed.
Why are let and const important in automation testing?
Automation engineers use const for fixed values such as URLs, API endpoints, browser names, and configuration settings, while let is used for values that change during test execution, such as counters, responses, and user input.
Key Takeaways
-
JavaScript provides three variable declaration keywords:
var,let, andconst. -
varis function-scoped, whileletandconstare block-scoped. -
varallows redeclaration and reassignment. -
letallows reassignment but not redeclaration. -
constallows neither redeclaration nor reassignment. -
constobjects and arrays can have their contents modified. -
varis initialized withundefinedduring hoisting. -
letandconstare hoisted but remain in the Temporal Dead Zone until declared. -
Prefer
constby default andletwhen reassignment is needed. -
Avoid using
varin modern JavaScript unless working with legacy code.
