I got this question from Interview,
[1,2] + [4,5,6][1]
JavaScript giving answer 1,25.
How it's happening? Please explain clearly.
I got this question from Interview,
[1,2] + [4,5,6][1]
JavaScript giving answer 1,25.
How it's happening? Please explain clearly.
Lets start with the last part and write it more verbose
var arr = [4,5,6];
var value = arr[1];
Is the same as
[4,5,6][1]
and as arrays are zero based, that gives 5
, so we really have
[1,2] + 5;
The first part is equal to
[1,2].toString(),
and that returns the string "1,2"
because the array is converted to a string when trying to use it in an expression like that, as arrays can't be added to numbers, and then we have
"1,2" + 5
Concatenating strings with numbers gives strings, and adding the strings together we get
"1,25"
It breaks down like this:
Starting with:
[1,2] + [4,5,6][1]
First, each side gets evaluated, and since the right-hand side is an array initializer and lookup, it comes out to 5
:
[1,2] + 5
Now the +
operator starts its work. It isn't defined for arrays, the first thing it does is try to convert its operands into either strings or numbers. In the case of an array, it'll be a string as though from Array#toString
, which does Array#join
, giving us:
"1,2" + 5
When you use +
where either side is a string, the result is string concatenation.
First, [4,5,6][1]
evaluates to the number 5
Then, the +
operator is being applied to a first argument which is an Array
and not a Number
, so javascript assumes you're doing a string concatenation, not addition. Your array [1,2]
becomes a string, which is "1,2"
. You can see this yourself with [1,2].toString()
.
The number 5
is now being appended to a string, so it to gets converted to a string, and appended together to get "1,25"
.