JavaScript101:Variable Declaration
01:Types of Variables
var keyword is used to declare variables in JavaScript that are mutable and have function scope.
Here is an example of using the var keyword in JavaScript:
var x = 5;
console.log(x); // Output: 5
x = 7;
console.log(x); // Output: 7
In this example, the variable x is declared using the var keyword and is assigned the value of 5. Later, the value of x is changed to 7. Since var variables are mutable, this is allowed.
let is a keyword used to declare variables in JavaScript that are block-scoped and can be reassigned.
let x = 5;
console.log(x); // Output: 5
x = 7;
console.log(x); // Output: 7
In this example, the variable x is declared using the let keyword and is assigned the value of 5. Later, the value of x is changed to 7. Since let variables are mutable, this is allowed. However, unlike var variables, let variables are block-scoped, meaning they only exist within the block they are defined in.
The const keyword in JavaScript is used to declare variables that cannot be reassigned.
const x = 5;
console.log(x); // Output: 5
x = 7; // This will result in an error
console.log(x);
In this example, the variable x is declared using the const keyword and is assigned the value of 5. Since const variables cannot be reassigned, attempting to change the value of x to 7 will result in an error. const variables are also block-scoped, like let variables, and only exist within the block they are defined in.
Difference between Let/Const/Var
Mail Your Articles on JavaScript to get featured