Nearby lessons
2 of 22JavaScript Variable Declarations: var, let, and const
📌 What are Variable Declarations?
JavaScript provides three ways to declare variables: var, let, and const. While var is function-scoped and allows redeclaration, let and const were introduced in ES6 and provide block scoping, with additional restrictions to enhance code clarity and reduce bugs.
🟡 var Example
var is function-scoped and allows re-declaration and reassignment. It can leak outside of block-level code.
Code Example
🔵 let Example
let is block-scoped and does not allow re-declaration in the same block, but reassignment is allowed.
Code Example
🔴 const Example
const is block-scoped and does not allow re-declaration or reassignment. It must be initialized during declaration.
Code Example
📦 Scope Comparison: Global vs Block
var is function- or globally-scoped, while let and const are block-scoped.
🌐 var is Global/Function Scoped
var is either globally scoped or function scoped. It is accessible outside of block statements like if, for, etc.
Code Example
📦 let is Block Scoped
let is block-scoped. It cannot be accessed outside the block in which it's defined.
Code Example
🔐 const is Block Scoped
const is also block-scoped like let. It cannot be accessed outside its defining block.