JavaScript- var, let, const
Difference between var, let and const
Feature |
Var |
let |
|
Scope |
Function/Global |
Block |
|
Hoisting |
Yes, initialized with undefined |
Yes, not initialized |
|
Reassignment |
Allowed |
Allowed |
|
Initialization |
Optional |
Optional |
|
Here are examples demonstrating the use of var, let, and const in JavaScript:
var
The var keyword is function-scoped or globally scoped if declared outside a function. Variables declared with var can be re-declared and updated.
var name = “Alice”;
console.log(name); // Output: Alice
var name = “Bob”; // Re-declared
console.log(name); // Output: Bob
name = “Charlie”; // Updated
console.log(name); // Output: Charlie
let
The let keyword is block-scoped, meaning it is only accessible within the block it is declared in. Variables declared with let can be updated but not re-declared within the same scope.
let age = 25;
console.log(age); // Output: 25
age = 26; // Updated
console.log(age); // Output: 26
// Block scope
if (true) {
let age = 30;
console.log(age);// Output: 30 (inside block)
}
console.log(age); // Output: 26 (outside block)
const
The const keyword is also block-scoped. Variables declared with const cannot be updated or re-declared. However, if the variable is an object or array, the properties or elements can
be modified.
const pi = 3.14;
console.log(pi); // Output: 3.14
pi = 3.14159; // Error: Assignment to constant variable.
// Block scope
if (true) {
const pi = 3.14159;
console.log(pi);// Output: 3.14159 (inside block)
}
console.log(pi); // Output: 3.14 (outside block)
- var: Function or globally scoped, can be re-declared and updated.
- let: Block-scoped, can be updated but not re-declared within the same scope.
- const: Block-scoped, cannot be updated or re-declared, but object properties and
array elements can be modified.
Each keyword has its own specific use case depending on the scope and mutability requirements of the variable.