Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ({}+{}).length equal to 30?

Tags:

javascript

{} to String?

Anyone can tell me why this is 30?

({}+{}).length //  = 30?

But this is 0?

([] + []).length //  = 0?
like image 797
Jack Pu Avatar asked May 11 '16 01:05

Jack Pu


People also ask

Is empty array length 0?

length property. If the length of the object is 0, then the array is considered to be empty and the function will return TRUE.

Why array length is not working?

Though arrays are objects in Java but length is an instance variable (data item) in the array object and not a method. So, we cannot use the length() method to know the array length.

How do you define the length of an array?

Description. The length property of an array is always one larger than the index of the highest element defined in the array. For traditional “dense” arrays that have contiguous elements and begin with element 0, the length property specifies the number of elements in the array.

What is the maximum length of a string in JavaScript?

The language specification requires strings to have a maximum length of 253 - 1 elements, which is the upper limit for precise integers.


1 Answers

This is the expected behavior. When you use the + operator on 2 arrays, both arrays are cast to a string, which is basically the same as calling .join(','). If the arrays are both empty, you will get two empty strings concatenated, resulting in one empty string which has 0 length.

([] + []) = ""

However with objects, the way they are cast to a string is different. By default, the + operator will cast the objects to strings, which will result in the string "[object Object]" Do that twice, and you will get a 30 character long string.

({}+{}) = "[object Object][object Object]"
like image 120
Alexander O'Mara Avatar answered Oct 05 '22 08:10

Alexander O'Mara