Assign Same Value to Multiple Variables in JavaScript
When working with JavaScript, you may need to assign the same value to multiple variables. This article explains how to do this using two different methods:
(1) Using the assignment operator (=
)
You can assign the same value to multiple variables simultaneously by using the assignment operator (=
) in a consecutive manner.
For example:
var a = b = c = 10;
The above code is equivalent to
var c = 10;
var b = c;
var a = b;
You can also declare the variables first and assign the value later.
For example:
var a, b, c;
a = b = c = 10;
You can also use let
or const
instead of var
.
For example:
let a = b = c = 10;
const a = b = c = 10;
You can also create an undeclared variable without using any keywords, although this is not recommended.
For example:
a = b = c = 10;
You can also assign different values to variables in the same line of code.
For example:
var a = 2, b = 3;
Non-primitive Values
Be cautious when assigning non-primitive values (e.g. arrays, objects) this way, as they are mutable. Updating one will affect all others since they reference the same object.
For example:
var a = b = [1, 2, 3];
b[0] = 44;
console.log("a: " + a); // Output: a: 44,2,3
console.log("b: " + b); // Output: b: 44,2,3
To avoid this, assign them separately.
var a = [1, 2, 3];
var b = [1, 2, 3];
b[0] = 22;
console.log("a: " + a); // Output: a: 1,2,3
console.log("b: " + b); // Output: b: 22,2,3
(2) Using destructuring assignment
Destructuring assignment allows you to unpack values from arrays or objects into distinct variables.
For example:
var name = ["John", "Doe"];
var [firstName, lastName] = name;
// Above destructuring syntax sets
// firstName = name[0];
// lastName = name[1];
console.log(firstName); // Output: John
console.log(lastName); // Output: Doe
Assign the same value to multiple variables
You can combine destructuring assignemnt with the fill()
method to assign the same value to multiple variables.
For example:
var [a, b, c] = Array(3).fill(50);
console.log("a: " + a); // Output: a: 50
console.log("b: " + b); // Output: b: 50
console.log("c: " + c); // Output: c: 50