Array and String Concatenation in JavaScript: How It Works? Infosys interview question. Javascript interview prepration.


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([] + []);

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] + []);

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

[1] + [] → "1" + """1"

Output

"1"

🔹 Third Expression: console.log([1] + "abc");

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

[1] + "abc""1" + "abc""1abc"

Output

"1abc"

Final Outputs

ExpressionEvaluated ResultFinal Output
[] + []"" + """"
[1] + []"1" + """1"
[1] + "abc""1" + "abc""1abc"

Remember key points:

  1. Arrays are objects, and when used with +, they are converted to strings.
  2. [].toString() returns "" (empty string).
  3. [1].toString() returns "1", and the + operator performs string concatenation.
  4. If one operand is a string, the entire expression is treated as a string operation.
  5. 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.

Post a Comment

Previous Post Next Post