How to Use the toString method in JavaScript

  • 6 min read
  • November 3, 2020
linkedin twitter facebook reddit
linkedin twitter facebook reddit

JavaScript’s toString() method receives an argument, returning the object’s text representation as a string.

The string value returned depends on the type of the argument that is being converted. This article covers applying toString() to the following data-types: Number, Array and Object.

We’ll use the following function to explore how the toString() method interacts with various object types:

function stringing(arg) {
    console.log(arg.toString(), '- Type of arg is: ', typeof (arg));
}

The usage of this method depends on the return value, for as will be shown below, toString() produces very different results for different types of arguments.

num.toString()

Let’s begin by using toString() on a number:

const num = 3;
stringing(num);  // expected output: 3 - Type of arg is:  number

When using toString() on a number, a string of that number is returned.

toString() has a lot of extra functionality when working with numbers. See the Parameters section below.

array.toString()

What happens if we try to apply toString() to an array? The following examples illustrate the function’s behavior.

 

1.     Applying toString() to an array of numbers

Applying toString() to an array returns only the values of the array as a string.

const numArray= [6, 5, 4];
stringing(numArray);  // expected output: 6,5,4 - Type of arg is:  object

Note: the square brackets are not included in the output.

Note: The reported type of an array is object, yet, the result of applying toString() to an object is different. See the section object.toString() below for more information.

 

2.     Array of strings

The same rule applies for an array of strings – applying toString() to the array returns only the values of the array as a string:

const strArray= ['a', 'b', 'c'];
stringing(strArray);  // expected output: a,b,c - Type of arg is:  object

 

3.     Array of both numbers and strings (mixed arrays)

We see the same behavior yet again when applying toString() to a mixed array:

const mixArray= ['5', 32, 'Daniel'];
stringing(mixArray); // expected output: 5,32,Daniel - Type of arg is:  object

Tip: You can use the split() method to get an array back from the output string.

In the above example, each value is separated by a comma. As such, the comma should be passed as a parameter for the split() method as seen in the following example:

const str = mixArray.toString();
const backToArr = str.split(',');
console.log('backToArr: ', backToArr);
// expected output: ["5", "32", "Daniel"]

Note: In the original array, const mixArray contained 32 as a Number. Though 32 is contained in the new array backToArr, it is now of type String!

If you fail to include a parameter for the split() method, the result will be an array with a single value – the result of mixedArray.toString(), including the commas:

const str = mixArray.toString();
const backToArr = str.split();
console.log('backToArr: ', backToArr);
// expected output: ["5,32,Daniel"]

You can learn more about the split() method here.

 

4.     Array inside an array

The below example shows what happens when we provide an array that contains an array to the toString() method:

const arrInArr= [ '5', 32, [ 'Daniel', 4 ] ];
stringing(arrInArr); // expected output: 5,32,Daniel,4 - Type of arg is:  object

Both arrays are “flattened” and returned as a string with all of the values separated by commas.

If the array element is replaced with an object, the result will be [object, object] as we see below:

const objInArr = ['5', 32, { name: 'Ariel', age: 40 } ];
stringing(objInArr );  // expected output: 5,32,[object Object] - Type of arg is:  object

Although arrays are of type object and, as was shown earlier, produce a meaningful result when the toString() method is applied, this is not the case with objects.

 

object.toString()

The default behavior of applying toString() to an object returns the string [object, object], as seen in the following example:

const obj = { name: 'Ariel', age: 40 };
stringing(obj); // expected output: [object Object] - Type of arg is:  object

To overcome this issue, we need to modify the object’s “prototype.toString” method. By default, the toString() method returns [object, object] for any object. However, it is possible to modify the prototype method, thus overriding the default settings. After modification, the return value will be obtained as specified by the new method that was added. This applies only to that specific object – in the above case, only const obj will exhibit this behavior.

For more information about Object.prototype, check out this link.

The common way to convert an object to a string in JavaScript is by applying the JSON.stringify() method.

 

Parameters

When applying toString() to Numbers and BigInts, an optional parameter – radix – can be provided. Radix specifies the mathematical base for the number being converted to a string (i.e. radix of 2 means binary, 8 octal, 10 decimal, 16 hexadecimal and so forth). The return value for that number will be the representation of that number according to the base defined by the radix.

const num2 = 10;
console.log(num2.toString(2));  // expected output: 1010

In the above example, the radix is 2, therefore, the result is a string representation of the integer 10 in binary – “1010”.

Note: In many cases the first digit(s) in binary representations can be zero(s).

const num = 3;
console.log(num.toString(2));  // expected output: 11

The binary representation of 3 is “0011”, the zeros are not being printed.

Note: The return value will always be a string starting with a digit or a character associated with the specific radix provided. Radices higher than 10 use English alphabet characters to indicate numerals greater than 9. For example, when using base 16 (hexadecimal numbers), “A” through “F” are used to specify the numbers 10-15 (A = 10, F = 15).

The sample below demonstrates this behavior by converting a number into its hexadecimal representation:

const num2 = 15;
console.log(num2.toString(16));  // expected output: f

In the output above, the return value is ‘f’. The character “f” represents a value of 15 in the hexadecimal numeral system.

Tip: Both Microsoft Windows and macOS provide a programmer’s calculator as an option. This programmer’s calculator allows you to see the result of an expression in different numerical bases.

 

Related Articles

JavaScript – How to Use JSON.stringify

JavaScript – How to Use parseInt()

JavaScript – How to Change The Page URL

 

Related Posts

How to Change CSS Using JavaScript

How to Change CSS Using JavaScript

Cascading Style Sheets (CSS) is used to design the layout of a webpage. CSS is a set of structured rules describing the layout of elements in

How to Use the for…in Statement in JavaScript

How to Use the for…in Statement in JavaScript

The for…in statement is used to loop through an object’s properties. Basic for…in loop example The following code demonstrates a basic example using the for…in statement

How to use the for…of Statement in JavaScript

How to use the for…of Statement in JavaScript

The for…of statement was introduced in ECMAScript2015 (ES6) and adds a powerful new type of loop to JavaScript. JavaScript offers many different types of loops, each