Table of contents
No headings in the article.
There is just one way to declare a variable in JavaScript at first, and that is by using the var keyword. Let and const, two new methods for defining variables, were added with ES6. The let and const keywords are currently supported by all the major browsers, and the majority of developers use them these days.
What distinguishes them from var, which we were initially utilizing, is the question. What's the main concept? Why are there three different keywords for defining a variable? Let's see the differences.
With ES6, users can declare variables in JavaScript by using the keywords var, let, and const. The differences between the keywords var, let, and const will be covered below briefly. We will go through each keyword's scope and other necessary ideas.
- JavaScript var keyword: The var keyword is the first one used in JavaScript to declare a variable.
Scope (Global scoped): The global or function scope is the scope of the var keyword. It implies that variables defined external to the function can be accessed worldwide and that variables defined inside a specific function can be accessed internally.
- JavaScript let keyword: The var keyword has been upgraded into the let keyword.
Scope (Block scoped): A let variable's scope is exclusively block scoped. It cannot be reached from outside the designated function (block).
- JavaScript const keyword: The only difference between the let and const keywords is that the const keyword cannot be updated by the user.
Scope (Block scoped): Const variables must be initialized after being declared by users in order to avoid an error. Once declared, a const variable cannot be updated by the user.
In summary, variables declared using let or const are not permitted to be redeclared in the same scope in strict mode, whereas variables declared with var are.