String Function –
The String Function (
String() ) is used to convert the value of an object to String, So even if you pass number, string, boolean, and even date object gets converted to a string. Its syntax is,
For more info about String Function Click Here.
toString Method –
The toString Method (
toString() ) is used to return the value of the object. The returning value is in string format. So, it can also convert a number, string, and boolean to a string. Its syntax is,
For more info about toString() Method Click Here.
First we create a variable str using let keyword and assign a null value to it.
let str = null;
Now, we are using a String() function and pass an str variable as a parameter to it. And it converts a null value to string.
console.log(String(str)); // ‘null’
Finally, we came to the main step, Now we are using the toString() method to an str variable. Any guess, what should be the output.
Now, you the answer is ‘TypeError’ but why this happen as we mostly use toString() method and it can not able to convert null value to string.
So, when we console log the value return from String() function it give ‘null’ as string and it can also work on undefined too.
String(null); // ‘null’
String(undefined); // ‘undefined’
But, that’s not same case happen with toString() method as it not work on null and undefined. As, it give TypeError.
(null).toString(); // ‘TypeError’
(undefined).toString(); // ‘TypeError’
As, You need a valid object in order to execute a method.
That’s why we get an answer “TypeError“.
I hope you understand the concept and logic behind it.
But wait, i have something more for you –
- JS Quiz – what really spread syntax with array pushing
- JS Quiz – Did really the reference pass using Array.from() method
And last but not the least, don’t forget to like, comment and share. It gives us a morale boost to remain to continue. Also, join our Facebook Page
If you have any questions, please feel free to ask me in the comment section and also let me know if you have any suggestions. As suggestions are always welcome.