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.

Code Example
PREVIEW READY
Loading Editor...
Live Preview

🔵 let Example

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

Code Example
PREVIEW READY
Loading Editor...
Live Preview

🔴 const Example

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

Code Example
PREVIEW READY
Loading Editor...
Live Preview

📦 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
PREVIEW READY
Loading Editor...
Live Preview

📦 let is Block Scoped

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

Code Example
PREVIEW READY
Loading Editor...
Live Preview

🔐 const is Block Scoped

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

Code Example
PREVIEW READY
Loading Editor...
Live Preview

🧠 Test Your Knowledge

3 Questions

Progress: 0 / 3
Keep Going!AJS - Template Strings