+ 1

Can you set a variable equal to multiple values without creating an array?

https://code.sololearn.com/WYPQFFs2T0Qo/?ref=app I found code on Stack Overflow that had a lot of upvotes that contained a variable that was set equal to multiple values. This was puzzling because I thought this wasn’t valid syntax and that an array would work better. In the code above is that line of code which is: var frag = document.createDocumentFragment, node, childNode; I ran the variable and a similar one in Sololearn above and it only returns the 1st value. What is the use in this?

14th Dec 2018, 5:52 AM
Thomas Czernek
Thomas Czernek - avatar
5 Answers
+ 2
In js and many other language you can declare more than 1 variable in one line, like this var frag = document.createDocumentFragment, node, childNodes; That is means create variable frag then put the value in, then create the other vars without initial value. Read them like this var (frag = document.createDocumentFragment), (node), (childNodes); Each parenthesis is a new variable. not a single variable with multiple value like this var frag = (document.createDocumentFragment, node, childNodes);
14th Dec 2018, 7:15 AM
Taste
Taste - avatar
+ 5
One Statement, Many Variables You can declare many variables in one statement. Start the statement with var and separate the variables by comma: var frag = document.createDocumentFragment, node, childNode; https://www.w3schools.com/js/js_variables.asp
14th Dec 2018, 6:16 AM
ODLNT
ODLNT - avatar
+ 4
Lets do this var firstName = "Timmy", lastName, age; There are three separate declared variables firstName, lastName, and age. The variable firstName has the value "Timmy" assigned to it, the other two variables, lastName and age are undefined because they were not assigned any value when they were initially declared.
14th Dec 2018, 7:08 AM
ODLNT
ODLNT - avatar
+ 3
In addition to the other good answers here, try this... Replace the var keyword with the let keyword. When you attempt to run this again, you'll see an error explaining you can't declare the y variable multiple times or something to that effect.
14th Dec 2018, 7:57 AM
David Carroll
David Carroll - avatar
0
Yes, but how would you call the 2nd value of the variable?
14th Dec 2018, 6:34 AM
Thomas Czernek
Thomas Czernek - avatar