DEV Community

loading...
Cover image for JavaScript Interview Question #22: How `toString` works in JavaScript?

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

coderslang profile image Coderslang: Become a Software Engineer Originally published at learn.coderslang.com on ・1 min read

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

Discussion (0)

Forem Open with the Forem app