Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Assign multiple variables to the same value in JavaScript?
JavaScript allows you to assign the same value to multiple variables in a single statement using the assignment operator chaining technique.
Syntax
var variable1, variable2, variable3; variable1 = variable2 = variable3 = value;
You can also declare and assign in one line:
var variable1 = variable2 = variable3 = value;
Example: Assigning Same Value to Multiple Variables
var first, second, third, fourth, fifth;
first = second = third = fourth = fifth = 100;
console.log("first:", first);
console.log("second:", second);
console.log("third:", third);
console.log("fourth:", fourth);
console.log("fifth:", fifth);
console.log("Sum of all values:", (first + second + third + fourth + fifth));
first: 100 second: 100 third: 100 fourth: 100 fifth: 100 Sum of all values: 500
How It Works
Assignment operators work from right to left. The expression a = b = c = 10 is evaluated as a = (b = (c = 10)), where each assignment returns the assigned value.
var x, y, z;
console.log("Assignment result:", (x = y = z = 42));
console.log("x:", x, "y:", y, "z:", z);
Assignment result: 42 x: 42 y: 42 z: 42
Using Different Variable Declaration Keywords
// With let
let a, b, c;
a = b = c = "hello";
console.log("a:", a, "b:", b, "c:", c);
// With const (declare and assign together)
const num1 = num2 = num3 = 25;
console.log("num1:", num1, "num2:", num2, "num3:", num3);
a: hello b: hello c: hello num1: 25 num2: 25 num3: 25
Important Note About Objects and Arrays
When assigning objects or arrays, all variables point to the same reference:
var arr1, arr2, arr3;
arr1 = arr2 = arr3 = [1, 2, 3];
arr1.push(4);
console.log("arr1:", arr1);
console.log("arr2:", arr2);
console.log("arr3:", arr3);
arr1: [ 1, 2, 3, 4 ] arr2: [ 1, 2, 3, 4 ] arr3: [ 1, 2, 3, 4 ]
Conclusion
Use chained assignment (a = b = c = value) to assign the same value to multiple variables efficiently. Be careful with objects and arrays as they share the same reference.
Advertisements
