string - How [1,2] + [4,5,6][1] = 1,25 in JavaScript -
this question has answer here:
- why [1,2] + [3,4] = “1,23,4” in javascript? 13 answers
i got question interview,
[1,2] + [4,5,6][1]
javascript giving answer 1,25.
how it's happening? please explain clearly.
lets start last part , write more verbose
var arr = [4,5,6]; var value = arr[1];
is same as
[4,5,6][1]
and arrays 0 based, gives 5
, have
[1,2] + 5;
the first part equal to
[1,2].tostring(),
and returns string "1,2"
because array converted string when trying use in expression that, arrays can't added numbers, , have
"1,2" + 5
concatenating strings numbers gives strings, , adding strings get
"1,25"
Comments
Post a Comment