data type conversion - Addition on two blank objects or blank arrays in javascript -
this question has answer here:
i playing around javascript when found following console outputs:
[] + []// output: ""[] + {}// output: [object object]{} + []// output: 0{} + {}// output: nan
could please explain me logic behind these output. feel strange behaviour guess maybe has logic.
thanks in advance.
expected results
when adding 2 arrays, works expected:
[] + []//output'' converting [] primitive first tries valueof() returns array (this):
var arr = []; arr.valueof() === arr true as result not primitive, tostring() called next , returns empty string (which primitive). therefore, result of [] + [] concatenation of 2 empty strings.
{} + [] // output: 0 adding array , object conforms our expectations:
[] + {}//output '[object object]' explanation: converting empty object string yields following result.
string({})//output: '[object object]' the previous result created concatenating "" , "[object object]".
unexpected results
things weird if first operand of + empty object literal (results seen on firefox console):
{} + {}//output: nan what going on here? problem javascript interprets first {} empty code block , ignores it. nan therefore computed evaluating +{} (plus followed second {}). plus see here not binary addition operator, unary prefix operator converts operand number, in same manner number(). example:
+"3.65" 3.65 the following expressions equivalent:
+{} number({}) number({}.tostring()) // {}.valueof() isn’t primitive number("[object object]") nan why first {} interpreted code block? because complete input parsed statement , curly braces @ beginning of statement interpreted starting code block. hence, can fix things forcing input parsed expression:
({} + {})//output: '[object object][object object]' arguments of functions or methods parsed expressions:
console.log({} + {})//output: [object object][object object] after previous explanations, should not surprised following result, more:
{} + []//output: 0 again, interpreted code block followed +[]. following expressions equivalent:
+[] number([]) number([].tostring()) // [].valueof() isn’t primitive number("") 0 interestingly, node.js repl parses input differently either firefox or chrome (which uses same v8 javascript engine node.js). following input parsed expressions , results less surprising:
{} + {}//output: '[object object][object object]' {} + []//output '[object object]' this has advantage of being more results when using input arguments of console.log(). less using input statements in programs.
references
Comments
Post a Comment