In JavaScript, users can declare a variable using 3 keywords that are var, let, and const. In this article, we will see the differences between the var, let, and const keywords. We will discuss the scope and other required concepts about each keyword.
var
The var is the oldest keyword to declare a variable in JavaScript.
Scope: Global scoped or function scoped. The scope of the var keyword is the global or function scope. It means variables defined outside the function can be accessed globally, and variables defined inside a particular function can be accessed within the function.
let
The let keyword is an improved version of the var keyword.
Scope: block scoped: The scope of a let variable is only block scoped. It can’t be accessible outside the particular block ({block}).
const
The const keyword has all the properties that are the same as the let keyword, except the user cannot update it.
Scope: block scoped: When users declare a const variable, they need to initialize it, otherwise, it returns an error. The user cannot update the const variable once it is declared.
Differences between var, let, and const
var | let | const |
The scope of a var variable is functional scope. | The scope of a let variable is block scope. | The scope of a const variable is block scope. |
It can be updated and re-declared into the scope. | It can be updated but cannot be re-declared into the scope. | It cannot be updated or re-declared into the scope. |
It can be declared without initialization. | It can be declared without initialization. | It cannot be declared without initialization. |
It can be accessed without initialization as its default value is “undefined”. | It cannot be accessed without initialization otherwise it will give ‘referenceError’. | It cannot be accessed without initialization, as it cannot be declared without initialization. |
Hoisting is done, with initializing as the ‘default’ value | Hoisting is done, but not initialized (this is the reason for the error when we access the let variable before declaration/initialization) | Hoisting is done, but not initialized (this is the reason for the error when we access the const variable before declaration/initialization) |
Source: GeeksforGeeks