16

1st Part:

Because When you are adding two arrays, everything works as expected:

 [] + []     //output:''

Adding an array and an object also conforms to our expectations:

 [] + {}
output:'[object Object]'

{} + {} in JavaScript is NaN ?
and this is unexpected result so what is the reason behind this?

2nd part:

In string comparison without prefix 0, 3 is greater than 12:

"3" > "12"
: true

With padding, everything works correctly:

 "03" > "12"
: false

Is prefix 0 compulsory for string comparision?What is the reason for adding prefix 0 ?

Maizere Pathak.Nepal
  • 2,383
  • 3
  • 27
  • 41

3 Answers3

14
  1. {} + {} is interpreted as the empty block {} followed by the expression + {}. {} has no numerical value, so it yields NaN. If you force it to be evaluated as an expression like ({} + {}), you'll get [object Object][object Object].

  2. They're strings, so they'll be compared lexicographically. If you want to compare them as numbers, parse them first using parseInt or parseFloat.

icktoofay
  • 126,289
  • 21
  • 250
  • 231
12

the first part

1-

when you add two arrays you take the primitive value for each and arrays can be converted to strings like the following [1,2,3,4].toString() //=> 1,2,3,4 so the two emty arrays generates to empty strings and the concatenation between them generates empty string.

2- when for the second when you add empty string with object, you are converting the object to string and as shown the string value of an object is [object Object]

3-

when you add two objects, in the way shown you are just converting an object to number by the + check this question

Part Two

String compare is made letter by letter from left to right and as soon as there is a deference the return value is determined ignoring the string length like the following

"3" > "12"

"3" in ASCII is bigger than "1" so the return is TRUE

"03" > "12"

"0" in ASCII is smaller than "1" so the return is False

Community
  • 1
  • 1
Hilmi
  • 3,411
  • 6
  • 27
  • 55
0

I tried the following in the latest Firefox, Safari and Chrome: a = []; b={};console.log(a+a);console.log(a+b);console.log(b+b);

Firefox

(an empty string)
[object Object]
[object Object][object Object]

Chrome

[object Object]
[object Object][object Object]
undefined   

Safari

[object Object]
[object Object][object Object]

The string "3" is greater, lexicographically, than the string "12". If you really want strings to be compared as number, you have to tell JavaScript that's how you want it done.

parseInt("3") > parseInt("12");
Carl
  • 446
  • 2
  • 7