In this tutorial, I will explain the difference between let and var and const in Javascript.
In JavaScript, let, var, and const are used to declare variables, but they have different characteristics and behaviors. Let’s breakdown of the differences:
Let’s understand difference between let and var and const in Javascript
Var:
- Scope: var is a function-scoped or local variable. If a variable is declared with var inside a function, it’s accessible within the entire function but outside the function, it’s not accessible.
- Hoisting: Variables declared with var are hoisted, which means they can be accessed before they are declared.
- Re-declaration: You can re-declare variables using var within the same scope without causing an error means variables declared with var can be reassigned.
function exampleOfVar() {
console.log(a); // undefined due to hoisting
var a = 10;
console.log(a); // 10
}
exampleOfVar();
Let:
- Scope: let is block-scoped. A variable declared with let is only accessible within the block, statement, or expression where it is declared.
- Hoisting: Variables declared with let are also hoisted, but they are not initialized. They are in a “temporal dead zone” from the start of the block until the declaration is encountered.
- Re-declaration: You cannot re-declare a variable using let within the same scope.
function exampleOfLet() {
// console.log(b); // ReferenceError: b is not defined (due to temporal dead zone)
let b = 20;
console.log(b); // 20
}
exampleOfLet();
Const:
- Scope: Similar to let, const has a block-level scope as well.
- Hoisting: Variables declared with const are also hoisted but are not initialized and are in a temporal dead zone until the declaration is encountered.
- Re-declaration: You cannot re-declare a variable using const within the same scope.
- Immutability: Variables declared with const cannot be reassigned. However, if the variable is an object or an array, the contents of the object or array can be modified.
function exampleOfConst() {
const c = 30;
// c = 40; // TypeError: Assignment to constant variable.
const obj = { key: "value" };
obj.key = "new value"; // Allowed
console.log(obj.key); // "new value"
}
exampleOfConst();
Abstract:
- Scope: var is function-scoped, while let and const are block-scoped.
- Hoisting: All three are hoisted, but let and const have a temporal dead zone.
- Re-declaration: var allows re-declaration, but let and const do not.
- Reassignment: var and let can be reassigned, but const cannot be reassigned (though objects and arrays declared with const can have their contents modified).
I hope this blog clearly explains Difference between Var, Let and Const variables. If I missed anything or you need additional information, please feel free to leave a comment on this blog. I will respond with a proper solution.