Home >Web Front-end >JS Tutorial >Why Does JavaScript Produce Unexpected Results When Adding Arrays and Objects?
The "Wat" talk for CodeMash 2012 brought to light some puzzling behaviors in JavaScript. Here, we delve into the underlying mechanisms and explain the outcomes observed in the JSFiddle example.
[] + [] result: ""
The empty strings resulting from joining the arrays highlight that the operator converts both operands to primitives, calling toString() on arrays. For empty arrays, this conversion produces an empty string.
[] + {} result: [Object]
Like before, converting the empty array to a primitive gives us an empty string. However, the object is coerced into a string using its toString() method, resulting in "[Object]." This string is concatenated with the empty string, producing "[Object]."
{} + [] result: [Object]
The {} here is interpreted as an empty block, resulting in an empty primitive value. The operator then attempts to convert the object to a string via toString(), leading to "[Object]." However, this behavior is an anomaly, as the video suggests the result should be 0.
{} + {} result: [Object][Object]
Similar to the previous case, the objects are coerced into strings. However, since there is no unary operator, the result is not converted to a number. Instead, the concatenation of "[Object]" and "[Object]" is returned.
result: NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
Subtracting a number from a string results in NaN. When passed as an argument to Array.join, the conversion to string (via toString()) produces "NaN." The array's join() method then repeatedly concatenates this string, leading to the observed result.
These peculiar behaviors stem from the specific rules for converting values to primitives and the behavior of the operator in JavaScript. While some of them may seem counterintuitive, understanding the underlying mechanisms allows developers to better anticipate and handle these quirks in their own code.
The above is the detailed content of Why Does JavaScript Produce Unexpected Results When Adding Arrays and Objects?. For more information, please follow other related articles on the PHP Chinese website!