Nearby lessons

2 of 22

JavaScript 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.

Example02
🚀Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

🔵 let Example

let is block-scoped and does not allow re-declaration in the same block, but reassignment is allowed.

Example03
🚀Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

🔴 const Example

const is block-scoped and does not allow re-declaration or reassignment. It must be initialized during declaration.

Example04
🚀Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

📦 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.

Example06
🚀Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

📦 let is Block Scoped

let is block-scoped. It cannot be accessed outside the block in which it's defined.

Example07
🚀Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

🔐 const is Block Scoped

const is also block-scoped like let. It cannot be accessed outside its defining block.

Example08
🚀Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3