data type conversion - Addition on two blank objects or blank arrays in javascript -


i playing around javascript when found following console outputs:

  1. [] + [] // output: ""
  2. [] + {} // output: [object object]
  3. {} + [] // output: 0
  4. {} + {} // 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

what {} + {} in javascript?


Comments

Popular posts from this blog

IF statement in MySQL trigger -

c++ - What does MSC in "// appease MSC" comments mean? -

javascript - Blogger related post gadget image Resize s72-c [ Need Expert Help ] -