DEV Community

Cover image for JavaScript Interview Question #43: Object.toString vs Array.toString
Coderslang: Become a Software Engineer
Coderslang: Become a Software Engineer

Posted on • Originally published at learn.coderslang.com

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

Top comments (4)

Collapse
 
yohanchoidev profile image
YC John

I think this type of questions is not good interview question since mostly it tests a certain knowledge, not problem solving skill.

Collapse
 
coderslang profile image
Coderslang: Become a Software Engineer

Tests a certain knowledge (JS in this case) doesn't exclude questions related to problem solving.

For a skilled candidate it's equally important to have both.

Collapse
 
yohanchoidev profile image
YC John

Only if the knowledge is essential, then it makes sense. but I don't think so in this problem. That's very bad since these kind of test wastes developer's time. I can't find any point of this question. Probably, it would be better if the developer can ask himself when he is not sure. If he is not, then he will check reference.

Thread Thread
 
coderslang profile image
Coderslang: Become a Software Engineer • Edited

An interviewer can tell a lot about the candidate when they're presented with the question they're unfamiliar with.

Will they immediately tell you they don't know and try to use logic and a set of possible outcomes?
Will they try to blindly guess the result?
Will they just collapse and try to tell you don't anything about a proper interview?