JavaScript Interview Question #43: Object.toString vs Array.toString

coderslang

Coderslang: Become a Software Engineer

Posted on May 28, 2021

JavaScript Interview Question #43: Object.toString vs Array.toString

coderslang javascript interview question #43

What's the difference between Object.toString and Array.toString in JavaScript? What’s the output?

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

A regular behavior of the JavaScript function Object.prototype.toString in a browser — is a string that looks like [object "TYPE"]. The part "TYPE" is substituted with the type of the Object that toString is called on. In our case, it's Array.

console.log(toStringObj.call(arr)); // [object Array]
Enter fullscreen mode Exit fullscreen mode

In the second instance, we call toString from Array. It’s not the same function as it overrides the standard implementation of Object.prototype.toString.

Array.prototype.toString returns a string that consists of all the array elements separated with commas.

console.log(toStringArr.call(arr)); // 1,2,3
Enter fullscreen mode Exit fullscreen mode

ANSWER: 2 strings will appear on the screen:

[object Array]
1,2,3
Enter fullscreen mode Exit fullscreen mode

Learn Full-Stack JavaScript

💖 💪 🙅 🚩

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related