Anyone can tell me why this is 30?
({}+{}).length // = 30?
But this is 0?
([] + []).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.
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.
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.
The language specification requires strings to have a maximum length of 253 - 1 elements, which is the upper limit for precise integers.
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]"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With