+ 22

What is the explanation of this output?

Code: var x = [1] + [2] - [3]; console.log(x); Output: 9 How to explain this?

11th Jan 2017, 7:27 PM
Igor Makarsky
Igor Makarsky - avatar
2 ответов
+ 9
I try to explain, but I'm not sure of that: Litteral notation with squared brackets ( [ ] ) is for array, so your 'var x = [1] + [2] + [3]' is evaluate as: > [1] + [2], which result to '12'... at this point my explain is that JS not knowing how to add two arrays, try to cast them as string, so concatenate '1' and '2' > then previous result '12' - [3]... again JS don't know how to retrieve an array from a string, so it seems this time he cast the two value to number... > finally result is 12 - 3 == 9 ^^
11th Jan 2017, 8:38 PM
visph
visph - avatar
+ 1
so in js sometimes when u add numbers it adds them next to each other unless you do "1*1 + 2*1" just without the quotes. So then it's 1+2 which makes 12 - 3 = 9
3rd Aug 2018, 4:55 AM
Emperor Bob
Emperor Bob - avatar