Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How [1,2] + [4,5,6][1] = 1,25 in JavaScript [duplicate]

I got this question from Interview,

[1,2] + [4,5,6][1]

JavaScript giving answer 1,25.

How it's happening? Please explain clearly.

like image 922
KarSho Avatar asked Apr 25 '15 16:04

KarSho


1 Answers

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"
like image 144
adeneo Avatar answered Oct 04 '22 20:10

adeneo