Learn JavaScript: The Difference Between var, let, and const
A practical guide to understanding the crucial difference between var
, let
, and const
in JavaScript, the pillars of modern variable declaration.
Why Understand This Difference?
The way you declare a variable impacts its **scope**, **hoisting**, and whether it can be **reassigned**. Mastering these concepts is fundamental to avoiding bugs and writing cleaner, more predictable code. In short, variables are boxes for holding values, but each type of "box" has its own rules.
var โ The Old Way
Introduced in the early days of JavaScript, var
has **function scope**. This means a variable declared with var
is accessible anywhere within the function where it was created, ignoring code blocks like `if` or `for`. Furthermore, it undergoes **hoisting**, where its declaration is moved to the top of its scope, but its assignment is not. This can lead to unexpected behaviors.
let โ The Modern Choice for Reassignment
Introduced in ES6, let
has **block scope**. This makes it safer and more predictable. A `let` variable only exists within the code block (delimited by curly braces `{}`) where it was declared. It also undergoes hoisting, but into a temporary state known as the **"temporal dead zone,"** where it cannot be accessed until it is declared. This prevents common hoisting bugs that occur with var
.
const โ The Modern Choice for Constants
Also introduced in ES6, const
has **block scope** and is the most strict way to declare a variable. As the name suggests, it creates a constant, which means the value **cannot be reassigned**. Use const
whenever you are sure the variable will not change. Like let
, it also has a temporal dead zone and is the preferred choice for variables that don't need to be changed.
const
prevents the variable from being reassigned (e.g., `myArray = anotherArray` is forbidden), but it does not prevent the internal content from being modified (e.g., `myArray.push()` is allowed).
Quick Comparison Table
Characteristic | var |
let |
const |
---|---|---|---|
Scope | Function | Block | Block |
Hoisting | Yes, with `undefined` value | Yes, but with "Temporal Dead Zone" | Yes, but with "Temporal Dead Zone" |
Can be Reassigned? | Yes | Yes | No |
Can be Redeclared? | Yes, in the same scope | No, in the same scope | No, in the same scope |
Interactive Examples ๐งช
var
โ Hoisting and Function Scopelet
โ Block Scope and ReferenceErrorconst
โ Immutability of the BindingConclusion & Best Practices โจ
In short, the era of var
is in the past. To write safer, cleaner code without surprises, the JavaScript community has adopted the following rule:
const
. Only use let
when you are certain the variable needs to be reassigned. Avoid var
completely.
This simple practice reduces the chance of bugs and makes the intent of your code clear to other developers and your future self.