Understanding JavaScript Type Coercion in Array Operations
The given JavaScript expressions involve array addition (+
) with other values. Since arrays in JavaScript are objects, and the +
operator does not perform numeric addition on objects, JavaScript uses type coercion.
Let’s analyze each expression step by step.
🔹 First Expression: console.log([] + []);
Step 1: Understanding How Arrays Are Converted
-
In JavaScript, when objects (including arrays) are used with the
+
operator, they are converted to strings. - Arrays use their
.toString()
method to convert themselves to strings. [].toString()
returns an empty string (""
).
Step 2: Evaluating [] + []
Output
🔹 Second Expression: console.log([1] + []);
Step 1: Evaluating [1].toString()
and [ ].toString()
[1].toString()
converts the array to "1".[ ].toString()
converts the empty array to "".
Step 2: Performing String Concatenation
Output
🔹 Third Expression: console.log([1] + "abc");
Step 1: Evaluating [1].toString()
[1]
is converted to "1" using.toString()
."abc"
is already a string.
Step 2: Performing String Concatenation
Output
Final Outputs
Expression | Evaluated Result | Final Output |
---|---|---|
[] + [] | "" + "" | "" |
[1] + [] | "1" + "" | "1" |
[1] + "abc" | "1" + "abc" | "1abc" |
Remember key points:
- Arrays are objects, and when used with
+
, they are converted to strings. [].toString()
returns""
(empty string).[1].toString()
returns"1"
, and the+
operator performs string concatenation.- If one operand is a string, the entire expression is treated as a string operation.
- Numeric addition does not occur unless both operands are numbers.
✔ Final Answer:
C) 1 1abc
This question appeared in the Infosys 1st round of interview, testing the candidate’s knowledge of array type coercion and (+) operator in JavaScript.