Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objects and arrays addition

Tags:

Can anyone explain to me how the results of the following was evaluated?

{} + {} // NaN [] + {} // "[object Object]" {} + [] // 0 [] + [] // "" 
like image 647
Hilmi Avatar asked Aug 13 '12 08:08

Hilmi


People also ask

How do you sum an array of objects?

To sum a property in an array of objects:Call the reduce() method to iterate over the array. On each iteration increment the sum with the specific value. The result will contain the sum of the values for the specific property.

Can we add object in array?

There are 3 popular methods which can be used to insert or add an object to an array. The push() method is used to add one or multiple elements to the end of an array. It returns the new length of the array formed. An object can be inserted by passing the object as a parameter to this method.


1 Answers

Here is a full explanation of this, check it.

And note {} + {} be NaN if you execute it directly in the console because {} is thought of a block rather than an object.

({}+{}) should be '[object Object][object Object]'

The real result is:

console.log({}+{}) // '[object Object][object Object]' console.log([]+{}) // '[object Object]' console.log({}+[]) // '[object Object]' console.log([]+[]) // '' 
like image 171
xdazz Avatar answered Sep 25 '22 23:09

xdazz