How to Declare Multiple Variables in JavaScript?
JavaScript variables are used as container to store values, and they can be of any data type. You can declare variables using the var, let, or const keywords. JavaScript provides different ways to declare multiple variables either individually or in a single line for efficiency and readability.
Declaring Multiple Variables Individually
The most simple way to declare variables is to declare them one by one using var, let, or const keyword. You can directly assign values and can access them using the variable name.
Syntax
let x = 20;
let y = 30;
let z = 40;
Example: Declaring three different variables using let keyword.
let x = 20;
let y = 'G';
let z = "GeeksforGeeks";
console.log("x: ", x);
console.log("y: ", y);
console.log("z: ", z);
Output
x: 20 y: G z: GeeksforGeeks
Table of Content
Declaring Multiple Variables in a Single Line
You can declare multiple variables in one line using a comma-separated list with var, let, or const keyword. This approach can make the code more concise.
Syntax
let x = 20, y = 30, z = 40;
Example: Declaring and assigning three different variables at once.
let x = 20, y = 'G',
z = "GeeksforGeeks";
console.log("x: ", x);
console.log("y: ", y);
console.log("z: ", z);
Output
x: 20 y: G z: GeeksforGeeks
Using Destructuring Assignment
Destructuring assignment is a modern feature in JavaScript that allows you to unpack values from arrays or properties from objects into distinct variables in a single line. This is especially useful when dealing with arrays or objects.
Syntax
const [var1, var2, var3] = [val1, val2, val3];
Example: Declaring three different variables by destructuring them at once.
const [x, y, z] = [20, 'G', "GeeksforGeeks"];
console.log("x: ", x);
console.log("y: ", y);
console.log("z: ", z);
Output
x: 20 y: G z: GeeksforGeeks