let a = [1, 2, 3];
a.toString = function() {
return "overridden";
};
console.log(String(a));
0
What will be the output of the following code, and why does overriding toString() affect the result?
subina kallyani
hard
2completed
40
Answer
"overridden"
- By default, calling
String(a)would invokeArray.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