This tutorial will define various methods for declaring variables in JavaScript.
How to Declare Multiple Variables in JavaScript?
For declaring multiple variables in JavaScript, there are different ways as follows:
- Variable declaration in separate line
- Variable declaration in a block
- Variable declaration in one line
- Variable declaration in array notation
Let’s discuss all the mentioned ways one by one.
Method 1: Declare Variables in Separate Line in JavaScript
The most popular method to define and initialize JavaScript multiple variables is to write each variable in a separate line, such as:
let a;
const str;
In this situation, you can declare variables with different data types like in the above example, three variables “num”, “a”, and “str” are declared as three different data types “var”, “let”, and “const”.
Let’s see an example to initialize and declare variables at the same time:
let a = '11';
const str = "Hello";
Then, print the assigned values to the variables:
console.log("Variable 'str' contains "+ str);
console.log("Variable 'num' contains "+ num);
The corresponding output will be:
Method 2: Declare Variables in One Line in JavaScript
The next way is to declare comma-separated variables in the same line:
It is the most simple and easiest way, but the limitation is that all variables should belong to the same data type. No other data type or related variable can be added to the same line.
Now, we will declare multiple variables “name”, rollNo” and “age” and initialize them with “john”, “11”, and “19” values in one line:
Print any one of the variables using the “console.log()” method:
Output
Method 3: Declare Variables in Block in JavaScript
To overcome the readability issue of the above method, declare and initialize the variables in the block form separated by comma such as:
rollNo = 11,
age = 19;
Print any of the variable by passing it in the “console.log()” method:
Output
Method 4: Declare Variables in Array Notation in JavaScript
Variable declaration can also be done using the Destructuring assignment syntax or in array notation:
It is a JavaScript expression that separates values from arrays or objects into various variables.
In the given example, we will define and initialize three variables in array notation format:
Print the value of variable “name” using the “console.log()” method:
Output
We have compiled all the solutions for declaring multiple variables in JavaScript.
Conclusion
To declare multiple variables in JavaScript, you can use the different ways including, variable declaration in a separate line, in block, in one line or declare in array notation. The declaration of multiple variables in a single line is easy but it is advised to declare each variable separately to maintain the readability of the code. In this tutorial, we have defined the different ways of declaring multiple variables in JavaScript.