Why does javascript change objects into other things when added? -
something interesting adding empty arrays in javascript pointed out me, , have no idea why works way does.
adding empty arrays results in string.
in other terms, [] + []
returns ""
i booted console test it, , sure enough, works. further discovered behavior not limited empty arrays. arrays of numbers, strings, arrays, , objects turn strings when added other array. examples are:
[1] + [] //returns "1" [1] + [2] //returns "12" [1,2,3] + [2] //returns "1,2,32" [{foo:'bar'},'foo','bar'] + [] //returns "[object object],foo,bar"
it occurs other objects, when added else, if object on right hand side. if it's on left hand side, object turned 0.
'foo' + {foo:'bar'} //returns "foo[object object]" 1 + {foo:'bar'} //returns "1[object object]" {foo:'bar'} + 1 //returns 1 {foo:'bar'} + 'foo' //returns nan
this happens unless assign object variable. if use x = {foo:'bar'}
,
x + 'foo' //returns "[object object]foo"
and object turning string.
i can understand why sort of casting might happen in ==
operator, why addition this? why addition change arrays , objects (and yes, know arrays objects, too) other things?
that operator adding numbers or concatenating strings, if use other types, cast number or string, depending on case (that part bit complicated...).
from language specification:
the addition operator either performs string concatenation or numeric addition.
as why language designed way, can guess, shadow creeper shows plausible reason in answer: there several possibilities behavior on each different type, confusing.
Comments
Post a Comment