JavaScript Variables
5.1 JavaScript Variables
A variable is a container that stores data which you can use and manipulate later.
It is to be understood as a labelled box.
Example of VariableHere Hello, World! is stored in a box labelled message.
Declaration and Scope of Variables
var
- Reassign: Yes ✅
- Scope: Function-scoped
- Hoisting: Yes ✅
- Best Use: Avoid (legacy code) ❌
let
- Reassign: Yes ✅
- Scope: Block-scoped
- Hoisting: No ❌
- Best Use: Use for changeable variables ✅
const
- Reassign: No ❌
- Scope: Block-scoped
- Hoisting: No ❌
- Best Use: Use when value should not change ✅
We generally use let and const in modern JavaScript.
Usage of let
Usage of const
It is to be understood as a labelled box.
Example of Variable
variable.js
1let message = "Hello, World!"
Declaration and Scope of Variables
var
- Reassign: Yes ✅
- Scope: Function-scoped
- Hoisting: Yes ✅
- Best Use: Avoid (legacy code) ❌
let
- Reassign: Yes ✅
- Scope: Block-scoped
- Hoisting: No ❌
- Best Use: Use for changeable variables ✅
const
- Reassign: No ❌
- Scope: Block-scoped
- Hoisting: No ❌
- Best Use: Use when value should not change ✅
We generally use let and const in modern JavaScript.
Usage of let
letKeyword.js
1let score = 10
2score = 20 // allowed
Usage of const
constKeyword.js
1const pi = 3.14
2pi = 3.14159 // error