5 differences between var, let and const in JavaScript
Damilola Bakare
?? Front-End Engineer | WordPress Developer ?? Crafting Pixel-Perfect, High-Performance Websites for Businesses & Professionals ??
1.????? Scope
·?????? Var : This is a function scope, and it is accessible within the function, regardless of the block boundaries. For example, inside if, for.
·?????? Let: This is a blocked-scope, and it is only accessible within the block {} in which it’s defined.
·?????? Const: Blocked-Scoped, like let, but also ensures the variable is read-only after assignment.
2.????? Re-declaration
Var: This can be re-declared within the same scope without error.
let: This cannot the re-declared within the same scope.
const: ?it cannot be re-declared within the same scope, similar to let.
3.????? Initialization
·?????? Var: Variables declared with var are initialized as undefined during hoisting.
·?????? Let: Variables declared with let ?are not initialized until their declarations is evaluated.
·?????? Const: it must be initialized during declarations, otherwise, an error is thrown
4..????? Hoisting
·?????? Var: Variables declared with var are hoisted to the top of their scope and initiated with undefined.
·?????? let: Variables are hoisted but are not initialized, leading to a “Temporal Dead Zone”(TDZ) until their declaration.
·?????? const: This is similar to let, const is hoisted but not initialized, and also has a TDZ.
5. ????? Re-assignment
·?????? Var: This can be re-assigned.
?·?????? Let: This is be re-assigned.
·?????? Const: This can not be re-assigned. Once it is assigned, the value cannot change.