About a month ago I posted how it is possible to assign multiple variables with the same value in PHP and have since learned that this is also possible to do with Javascript. This can be useful if initializing multiple variables with the same initial value or if needing to make multiple copies of a value and then manipulate each separately.
Assigning multiple variables
Using the same set sort of examples as in the PHP post, but this time with Javascript, multiple variables can be assigned by using = multiple times on the same line of code like so:
var c = b = a;
The above is a more compact equivilent of this:
var b = a; var c = b;
Here’s an example where all three variables are assigned initially with the string "AAA" and then the values of each are written out to the current page using document.write:
var c = b = a = 'AAA'; document.write("a: " + a + "<br />" + "b: " + b + "<br />" + "c: " + c + "<br />");
The resulting output on the page would look like this:
a: AAA b: AAA c: AAA
Any subsequent updates to any of the variables will not affect the other assigned variables. In the next example a, b and c are again initialised with "AAA" and then b is changed to "BBB".
var c = b = a = 'AAA'; b = 'BBB'; document.write("a: " + a + "<br />" + "b: " + b + "<br />" + "c: " + c + "<br />");
The output from this example would be:
a: AAA b: BBB c: AAA