Differences between String () and. toString () in JS

Source: Internet
Author: User
String () and. the difference between toString () Is that String () and. toString () can be converted to the String type, but String () and. there are still differences between toString () and

1. toString () can convert all data into strings, 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

Check whether null and undefined can be converted into strings.

 
 
《script》  var str = null.toString();  console.log(str, typeof str);《script》

Result program error

《script》  var str = undefined.toString();  console.log(str, typeof str);《script》

The program also reports an error

You can write a number in the. toString () brackets to represent the hexadecimal string.

Binary:. toString (2 );

Octal:. toString (8 );

Decimal:. toString (10 );

Hexadecimal:. toString (16 );

2. String () can convert null and undefined into strings, but it cannot be converted into strings.

For example, convert null to a string

《script》  var str = String(null);  console.log(str, typeof str);《script》

The returned result is null, string

Convert undefined to a string

《script》  var str = String(undefined);  console.log(str, typeof str);《script》

The returned result is undefined, string

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.