0

What will be the output of the following code, and why does overriding toString() affect the result?

author
subina kallyani
hard
2
40
let a = [1, 2, 3];
a.toString = function() {
return "overridden";
};
console.log(String(a));
Answer

"overridden"

  • By default, calling String(a) would invoke Array.prototype.toString(), which returns the array elements joined by commas: "1,2,3".
  • However, in this case, the toString() method is overridden:
a.toString = function() { return "overridden"; };

Therefore, when String(a) is called, it internally calls the overridden toString() method, resulting in the string "overridden".

Click to Reveal Answer

Tap anywhere to see the solution

Revealed

Comments0