Gloria Harrison
Posted on Fri Aug 19 2022
javascript
Updated on : Fri Aug 19 2022
Array.prototype.toString()
The toString() method gives us the string representation of array,number,strings and booleans.The ArrayObjectjoin()Object.prototype.toString
object overrides the
toString
method of
. The
toString
method of arrays calls
internally, which joins the array and returns one string containing each array element separated by commas. If the
join
method is unavailable or is not a function,
is used instead, returning
[object Array]
.
Code Example
const number = 12345;const string = "Javascript";const boolean = trueconst array = [1,2,3];const mixedArray = [1,2,3,"HTML","CSS"]let nestedArray = [1, 2, 3, ["Html", "JS"]];const numberToString = number.toString()const stringToString = string.toString()const booleanToString = boolean.toString()const arrayToString = array.toString()const mixedToString = mixedArray.toString()const nestedToString = nestedArray.toString()console.log(typeof numberToString)console.log(typeof stringToString)console.log(typeof booleanToString)console.log(typeof arrayToString)console.log(typeof mixedToString)console.log(typeof nestedToString)console.log(numberToString)console.log(stringToString)console.log(booleanToString)console.log(arrayToString)console.log(mixedToString)console.log(nestedToString)
Output -
string
string
string
string
string
string
12345
Javascript
true
1,2,3
1,2,3,HTML,CSS
1,2,3,Html,JS
- As you can see we have converted the array,number,strings and booleans to string.
Exceptions -
const Null = nullconst Undefined = undefinedconst object = {name:"shubham",age:21}const undefinedToString = Undefined.toString()const nullToString = Null.toString()const objectToString = object.toString()console.log(objectToString)
Output -
TypeError: Cannot read properties of undefined (reading 'toString')
TypeError: Cannot read properties of null(reading 'toString')
[object Object]
- As you can see it can't read the undefined and null.
- For the object , it returns the [object,object] because it is the default string representation of object datatype.To solve this ,we will use another method which is JSON.stringify().
JSON.stringify() -
const object = {name:"shubham",age:21}const objectToString = JSON.stringify(object)console.log(objectToString)
Output -
{"name":"shubham","age":21}
- Now it returns the string representation of our object.
Using in comparison -
const number = 12345;const string = "12345";const compare = number === string;//false due to different datatypeconst compare = number.toString() === string;//true due to same datatype
- You can see we can convert the number to string and then compare with strict equality operator and it returned true due to same datatype