DEV Community

Cover image for JavaScript Interview Question #22: How `toString` works in JavaScript?
Coderslang: Become a Software Engineer
Coderslang: Become a Software Engineer

Posted on • Originally published at learn.coderslang.com on

8 4

JavaScript Interview Question #22: How `toString` works in JavaScript?

js-test-22

Let's try to apply a generic toString function to a regular JavaScript array. What’s the output?

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

In the first line, we’ve saved the function Object.prototype.toString into the constant toString. This function is called whenever the object has to be converted to a string.

Most objects provide an overridden implementation of the toString function. For example, an array will look like a comma-separated list of all values it holds.

The default behavior of Object.prototype.toString is to return a string of the format [object "TYPE"]. The "TYPE" is substituted with the actual type of the object. In our case, it’s Array.

So, with toString.call(arr) we call the original implementation of Object.prototype.toString.


ANSWER: the string [object Array] will be printed to the console.

Learn Full Stack JavaScript

Top comments (0)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay