Why push() Doesn’t Work as Expected Here? – JavaScript Question from a Capgemini Interview

Why push method Does not Work as Expected Here JavaScript Question from a Capgemini Interview

Our Javascript Code:

let newList = [1].push(2);
console.log(newList.push(3));

Step-by-Step Breakdown

Step 1: Understand .push()

The Array.prototype.push() method:

  • Adds one or more elements to the end of an array.
  • Returns the new length of the array not the updated array itself.

Example :-
let arr = [1];
let result = arr.push(2);
console.log(arr); // [1, 2] console.log(result); // 2 (new length of array)

Step 2: Apply It to Your Code

let newList = [1].push(2);

Here’s what’s really happening:

  • [1] is your original array.
  • .push(2) adds the number 2 to that array, so it becomes [1, 2].
  • But .push() returns 2 (the new length of the array), not the array itself.

So now:

newList = 2; // NOT an array

Step 3: Second Line

console.log(newList.push(3));

You're trying to call .push() on newList, but:

newList = 2

And 2 is a number, not an array.

So you get:

TypeError: newList.push is not a function

Because numbers don’t have a .push() method.


✔ Final Answer:

D) TypeError

This question appeared in the Capgemini 2nd round of interview, testing the candidate’s knowledge of array methods in JavaScript.



Post a Comment

Previous Post Next Post