We know that both String() and .toString() can be converted to string types, but there are still differences between String() and .toString()
1. .toString() can convert all data as a string, but exclude null and undefined
For example, convert false to string type
<script> var str = false.toString(); console.log(str, typeof str); </script>
The returned result is false, string
See if null and undefined can be converted to string
<blockquote style="margin-right: 0px;" dir="ltr"><pre class="html" name="code"><script> var str = null.toString(); console.log(str, typeof str); </script>
As a result, the program reported an error
<script> var str = undefined.toString(); console.log(str, typeof str); </script>
The program also reported an error
.toString() You can write a number in the brackets, representing the base, corresponding to the base string
Binary: .toString(2);
Octal: .toString(8);
Decimal: .toString(10);
Hex: .toString(16);
2. String() can convert null and undefined into strings, But there is no way to convert into a string
For example, if you convert null to a string
<script> var str = String(null); console.log(str, typeof str); </script>
, the result returned is null, string
convert undefined to a string
<script> var str = String(undefined); console.log(str, typeof str); </script>
The result returned is undefined, string