In JavaScript, variables are essential for storing data. The keywords var
, let
, and const
provide different ways to declare these variables.
var
- Scope: Function scope.
- Hoisting: Variables are hoisted.
- Re-assignment: Allowed.
- Re-declaration: Allowed.
function testVar() {
var x = 1;
if (true) {
var x = 2; // same variable!
console.log(x); // 2
}
console.log(x); // 2
}
testVar();
let
- Scope: Block scope.
- Hoisting: Hoisted but not initialized.
- Re-assignment: Allowed.
- Re-declaration: Not allowed.
function testLet() {
let y = 1;
console.log(y); // 1
if (true) {
let y = 2; // different variable
console.log(y); // 2
}
y = 5
console.log(y); // 5
}
testLet();
const
- Scope: Block scope.
- Hoisting: Hoisted but not initialized.
- Re-assignment: Not allowed.
- Re-declaration: Not allowed.
- Initialization: Required during declaration.
function testConst() {
const z = 1;
// z = 2; // Error: Uncomment this see error
console.log(z);
}
testConst();
Exercise: Try This To Practise Using Variables
-
Var Scope: Use
var
in a loop, then access it outside. -
Let Block Scope: Try
let
in a loop and access it outside the block. -
Const Immutability: Attempt re-assigning a
const
variable.
Good luck!
Top comments (0)