ES6(short for ECMAScript 6) is a set of advanced JavaScript techniques. ECMAScript was proposed by the European Computer Manufacturers Association as the standard of the Javascript language. You would think that nowadays there are quite a few Browsers, and if each browser has a different way of running Javascript, websites cannot work on all browsers, so there needs to be a standard. generic to force browsers to develop against that standard.- One of the standout features of ES6 is the addition of permission and const for data variable declarations. So why do we need let and const even though we already have var to declare variables, in this article we will learn the reasons for each type of variable declaration.
-
var:- Scope:
varhas function scope. It is visible throughout the entire function in which it is declared, regardless of block scope. - Hoisting: Variables declared with
varare hoisted to the top of their scope. This means that you can use a variable before it is declared, but its value will beundefined. - Mutability: Variables declared with
varcan be reassigned and redeclared within the same scope.
- Scope:
-
let:- Scope:
lethas block scope. It is visible only within the block in which it is declared, such as within loops or conditional statements. - Hoisting: Variables declared with
letare not hoisted to the top of their scope. They are not accessible before the line of code where they are declared. - Mutability: Variables declared with
letcan be reassigned, but they cannot be redeclared within the same scope.
- Scope:
-
const:- Scope:
constalso has block scope likelet. It is visible only within the block in which it is declared. - Hoisting: Variables declared with
constare not hoisted to the top of their scope. They are not accessible before the line of code where they are declared. - Mutability: Variables declared with
constare read-only and cannot be reassigned or redeclared once they are assigned a value. However, if the variable is an object or an array, its properties or elements can still be modified.
- Scope:
-
Picture:
