One of the most fundamental yet frequently misunderstood topics in JavaScript is the difference between var
, let
, and const
. While they all declare variables, their behaviors differ in ways that can significantly affect the clarity and reliability of your code. In this post, we’ll break down their key differences, explore when you might intentionally use var
, and offer best practices for modern JavaScript development.
Feature | var | let | const |
---|---|---|---|
Scope | Function-scoped | Block-scoped | Block-scoped |
Hoisting | Yes (initialized as undefined ) | Yes (TDZ applies) | Yes (TDZ applies) |
Reassignment allowed | ✅ Yes | ✅ Yes | ❌ No |
Redeclaration | ✅ Yes (in same scope) | ❌ No | ❌ No |
Temporal Dead Zone | ❌ No | ✅ Yes | ✅ Yes |
var
– Function Scope & Hoistingfunction testVar() {console.log(a); // undefined (hoisted)var a = 5;}
undefined
.{}
blocks.let
– Block Scope & Safer Hoistingfunction testLet() {// console.log(b); // ReferenceError (TDZ)let b = 10;}
if
, for
, while
blocks).const
– Immutable Bindingsconst c = 20;c = 30; // ❌ TypeError
let
.const
:const user = { name: "Dan" };user.name = "Daniel"; // ✅ allowed
var
?Although var
has mostly been replaced by let
and const
, there are still a few use cases:
Older JavaScript codebases often use var
. When modifying or extending such code, sticking with var
may help maintain consistency.
In rare cases, you might want a variable that exists throughout the entire function regardless of block scope.
function hoistMe() {hoisted(); // works due to hoistingfunction hoisted() {console.log("I’m hoisted!");}}
Using var
in the global scope adds the variable to the window
object in browsers:
var globalVar = "I’m global";console.log(window.globalVar); // "I’m global"
This is generally discouraged in modern development.
const
by default. It makes your code safer by preventing reassignment.let
when you need to reassign values, such as in loops or conditional logic.var
unless you have a specific reason, like supporting legacy environments or working in function scope on purpose.Modern JavaScript encourages clean, predictable, and block-scoped variable declarations. Understanding the nuances of var
, let
, and const
is essential for writing robust and maintainable code. Stick to const
and let
in your everyday work, and use var
sparingly when it truly serves a purpose.
Up next: We’ll explore how let
and const
behave in loops, and how closures interact with variable declarations. Stay tuned!
Quick Links
Legal Stuff
Social Media