JavaScript ToString Operation Tutorial

In this section, we will learn what the ToString operation is and how to use it in JavaScript.

Note: In this section, we’re assuming you already familiar with the type coercion as well as the ToPrimitive operations.

What is ToString Operation in JavaScript?

When there’s a non-String type value involved in an operation that needs values of type String, the execution engine will run the `ToString` operation on it to coerce that value into a String data type.

The ToString operation is the process of turning a non-string value into string. This operation is different for each datatype, as the list in the table below shows.

Example: running ToString operation in JavaScript

const res = "10" + 10;

console.log(res);

Output:

1010

In an addition-operation, when either of operands that are involved in the operation is of type String, the other operand will be coerced into type String as well.

In the statement:

const res = "10" + 10;

The first operand is of type `String`. This means the second operand should be of type string as well. So the execution engine will use the `ToString` operation and coerce the second operand into String data type.

List of Primitive and Object Values and the Result of Applying ToString Operation

In the table below you can see a list of primitive values and the result of applying `ToString` operation on them:

Primitive value After ToString operation
null “null”
undefined “undefined”
true “true”
false false
3.14159 “3.14159”
0 “0”
-0 “0”

JavaScript Object to String

Applying the `ToString` operation to values of type object (including arrays) will cause the `toString()` method of that target object to be invoked. Or, to be more specific, the execution engine will run the `ToPrimitive` operation on that object. The details are explained in the ToPrimitive section.

In the table below you can see a list of objects and the result of applying the `ToString` operation on them:

Object value After ToString operation
{} “[object Object]”
{a:2} “[object Object]”
{toString(){return “John Doe”;}} “John Doe”
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies