How to declare variables in different ways in JavaScript?
Last Updated :
20 Dec, 2023
In JavaScript, we can declare a variable in different ways by using different keywords. Each keyword holds some specific reason or feature in JavaScript. Basically, we can declare variables in three different ways by using var, let and const keywords. Each keyword is used in some specific conditions.
JavaScript var
This keyword is used to declare variables globally. If you use this keyword to declare a variable then the variable can be accessible globally and changeable also. It is good for a short length of codes, if the codes get huge then you will get confused.
Syntax:
var variableName = "Variable-Value;"
Example: This example shows the use of var.
javascript
var geeks = "GeeksforGeeks" ;
console.log(geeks);
|
JavaScript let
This keyword is used to declare variables locally. If you use this keyword to declare a variable then the variable can be accessible locally and it is changeable as well. It is good if the code gets huge.
Syntax:
let variableName = "Variable-Value;"
Example: This example shows the use of let.
javascript
if ( true ) {
let geeks = "GeeksforGeeks" ;
console.log(geeks);
}
console.log(geeks);
|
JavaScript const
This keyword is used to declare variable locally. If you use this keyword to declare a variable then the variable will only be accessible within that block similar to the variable defined by using let and difference between let and const is that the variables declared using const values can’t be reassigned. So we should assign the value while declaring the variable.
Syntax:
const variableName = "Variable-Value;"
Example: This example shows the use of const.
javascript
const geeks = "GeeksforGeeks" ;
console.log(geeks);
|
Difference Between var, let, and const
Can be redeclared |
Cannot be redeclared |
Cannot be redeclared |
Can be reassigned a value |
Can be reassigned a value |
Cannot reassign the value |
Only have global and function scope |
Can have a block scope |
Can have a block scope |
Variables are hoisted on top and can be used anywhere |
Variables must be initialized before use |
Variables must be initialized before use |
Can be redeclared anywhere in the program |
Can be redeclared inside a block |
Can never be redeclared |
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...