0
0
JavascriptComparisonBeginner · 4 min read

Var vs Let vs Const in JavaScript: Key Differences and Usage

In JavaScript, var declares variables with function scope and allows redeclaration, let declares block-scoped variables that can be reassigned but not redeclared in the same scope, and const declares block-scoped variables that cannot be reassigned after initialization.
⚖️

Quick Comparison

Here is a quick table comparing var, let, and const on key factors:

Featurevarletconst
ScopeFunction-scopedBlock-scopedBlock-scoped
HoistingYes, initialized as undefinedYes, but in temporal dead zoneYes, but in temporal dead zone
ReassignmentAllowedAllowedNot allowed
Redeclaration in same scopeAllowedNot allowedNot allowed
Use caseLegacy code, function variablesVariables that change valueConstants that never change
⚖️

Key Differences

var is function-scoped, meaning it is visible throughout the entire function it is declared in, even before the declaration due to hoisting, where the variable is moved to the top and initialized as undefined. This can cause bugs if you use the variable before assigning a value.

let and const are block-scoped, so they only exist inside the nearest curly braces {}. They are hoisted but not initialized, causing a "temporal dead zone" where accessing them before declaration throws an error.

The main difference between let and const is that let allows you to reassign the variable later, while const does not allow reassignment after the initial value is set. However, objects declared with const can still have their properties changed.

⚖️

Code Comparison

javascript
function testVar() {
  console.log(x); // undefined due to hoisting
  var x = 5;
  x = 10; // reassignment allowed
  var x = 20; // redeclaration allowed
  console.log(x); // 20
}
testVar();
Output
undefined 20
↔️

let and const Equivalent

javascript
function testLetConst() {
  // console.log(y); // ReferenceError: Cannot access 'y' before initialization
  let y = 5;
  y = 10; // reassignment allowed
  // let y = 20; // SyntaxError: Identifier 'y' has already been declared
  console.log(y); // 10

  const z = 15;
  // z = 20; // TypeError: Assignment to constant variable.
  console.log(z); // 15
}
testLetConst();
Output
10 15
🎯

When to Use Which

Choose const by default for variables that should not change, which helps prevent bugs and makes your code easier to understand. Use let when you need to reassign a variable, such as counters or values that update. Avoid var in modern code because its function scope and hoisting behavior can cause unexpected bugs; it is mainly kept for legacy support.

Key Takeaways

const is best for values that never change and improves code safety.
let is for variables that need reassignment within a block scope.
var is function-scoped and allows redeclaration, which can lead to bugs.
Avoid using var in new code; prefer let and const.
Accessing let or const before declaration causes errors due to temporal dead zone.