Differing var, let, and const in JavaScript
Prior to ES6 (published in 2015), JavaScript only supported one method for declaring variables: the var
keyword. In an effort to solve a number of issues with var
, two new keywords were added: let
and const
. Knowing the differences between these three methods of declaring variables is crucial for writing clean, error-free JavaScript code.
Scope Differences
The most significant difference between these keywords is the way they deal with scope:
var
is function-scoped or globally-scopedlet
andconst
are block-scoped
What this looks like in practice
Variables declared with var
can be accessed from anywhere within their enclosing function or globally if declared outside a function. let
and const
variables, on the other hand, can only be accessed within the block where they're declared.
Example using var:
console.log(a); // undefined (not null) due to hoisting
{
var a = 10;
console.log(a); // 10
}
console.log(a); // 10 - still visible outside the block
Example with let:
{
let b = 20;
console.log(b); // 20
}
console.log(b); // Error: b is not defined - not visible outside the block
var
introduces bugs in an unpleasant way due to its global context. let
and const
promote more predictable behavior as they impose stricter scope rules.
Hoisting
Hoisting is a JavaScript effect in which variable declarations are moved to the top of their scope at execution time. That being said, there are huge differences in how each of these keywords handles hoisting:
var
variables are moved to the top of their scope and are assigned the valueundefined
let
andconst
variables are hoisted but not assigned (they remain in the "temporal dead zone" until their line of declaration)
This is technically feasible with var
variables before they're declared (though they'll be undefined
), but trying to do the same thing with let
or const
variables before declaration will result in a ReferenceError
.
Reassignment
Another difference:
var
andlet
allow reassignment of variablesconst
does not allow reassignment after initialization
When to use each
- Use
const
(by default) for those variables which won't be reassigned - Use
let
when you do need to reassign values - Use
var
in modern JavaScript only when you have certain compelling reasons
Real-world usage of const
const
is particularly useful in many situations:
1. For such values which are supposed to stay constant
const PI = 3.14159;
const API_URL = 'https://api.example.com';
const MAX_ATTEMPTS = 5;
2. For object and arrays declarations
While the content might be altered, the reference can't be re-allocated:
const user = {
name: 'John',
age: 30
};
user.age = 31; // Valid - modifying a property
// user = {} // Invalid - not allowed to reassign the object itself
const numbers = [1, 2, 3];
numbers.push(4); // Valid - modifying array contents
// numbers = [5, 6] // Invalid - not allowed to reassign the array
3. For function declarations
const calculateArea = (radius) => {
return Math.PI * radius * radius;
};
4. In loops like forEach and map
const items = ['apple', 'banana', 'orange'];
items.forEach(item => {
const capitalized = item.charAt(0).toUpperCase() + item.slice(1);
console.log(capitalized);
});
Using const
by default helps to avoid reassignments by accident and makes your code more deterministic, which means less bugs and maintainable JavaScript code.