Explain Codes LogoExplain Codes Logo

Assign multiple variables to the same value in Javascript?

javascript
variable-declaration
variable-assignment
javascript-basics
Alex KataevbyAlex Kataev·Jan 30, 2025
TLDR

To assign multiple variables to the same value in JavaScript, chain them in a single assignment expression using the = operator:

let a = b = c = 5; // Look ma, no hands!

Just like that, a, b, and c are all holding the number 5.

Scope and declaration : a primer

In chaining assignments, understanding variable scopes is paramount. With let or const, you preemptively stave off global scope pollution:

let a, b, c; a = b = c = 5; // Triple threat!

These declarations ensure a, b, and c stick within their own Playpen — their scope. So, declare before you maintain!

The right-to-left rule: sequence matters

In JavaScript, chaining assignments follow a right-to-left evaluation rule:

let a = b = c = 5; // Pass the parcel!

5 is passed on to c, then c (holding 5) is assigned to b, and finally, b (also holding 5) is assigned to a. Just like a game of 'Pass the Parcel', the value gets passed to each variable in sequence.

Destructuring and Array.fill: partners in initialization

If you're looking to initialize many variables, think Array.fill() teamed with destructuring assignment:

let [a, b, c] = Array(3).fill(5); // Like a magic trick!

Here a, b, and c are all initialized to 5 in one fell swoop.

Copy or Reference: Understanding object assignments

For object values, the plot thickens with reference copying instead of cloning:

let a = b = c = { count: 5 }; // Sharing is caring?

Changes to a.count influences b and c. If independent objects are your goal, clone away:

let a = { ...{ count: 5 } }; let b = { ...{ count: 5 } }; let c = { ...{ count: 5 } }; // Independent folks!

Now, a, b, and c are individual entities — same faces, different places.

Code corner: watch out for pitfalls

Don't forget to stay vigilant for potential gotchas:

  • Infinite generators inside loops, that's like an all-you-can-eat buffet, but you're the food!
  • Performance can swing between Array.fill() and manual assignments, especially for longer variable lists.
  • Legacy browsers might frown at some methods like Array.fill(). Keep those transpilation tools ready!

Balancing simplicity and readability

Too little salt, and your dish is bland. Too much, it's unbearable. Readability and simplicity should walk the tightrope in your code. Whilst one-liners may look smart, they could blur the intent, making your code harder to maintain.