+ 22
What is the explanation of this output?
Code: var x = [1] + [2] - [3]; console.log(x); Output: 9 How to explain this?
2 Respuestas
+ 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 ^^
+ 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