DEV Community

loading...
Cover image for JavaScript Type Conversion

JavaScript Type Conversion

bello profile image Bello Updated on ・2 min read


Type Conversion

Type conversion is the conversion from one data type to another.

Below are the data type conversions:

String Conversion

Conversions from one data type to a string are possible with the String() function in use.

For example, conversion from a boolean to a string:

script.js

const bool = true; // try undefined, null, NaN, etc
console.log(typeof bool); // boolean

const toStr = String(bool);
toStr; // 'true'
console.log(typeof toStr); // string
Enter fullscreen mode Exit fullscreen mode

Number Conversion

Conversions from one data type to a number are possible with the Number() function in use.

For example, conversion from a boolean to a number:

script.js

const bool = true; // try undefined, null, NaN, etc
console.log(typeof bool); // boolean

const toNumber = Number(bool);
toNumber; // 1;
console.log(typeof toNumber); // number
Enter fullscreen mode Exit fullscreen mode
Data Types Numeric Conversion
true and false 1 and 0
string NaN
' ' NaN
null, undefined, and NaN number

script.js

const notNum = NaN; // try undefined, null, NaN, etc
console.log(typeof notNum); // number

const toNumber = Number(notNum);
toNumber; // NaN;
console.log(typeof toNumber); // number
Enter fullscreen mode Exit fullscreen mode

Boolean Conversion

Conversions from one data type to a boolean are possible with the Boolean() function in use.

For example, conversion from a number to a boolean:

script.js

const num = 0; // try undefined, null, NaN, etc
console.log(typeof num); // number

const toBoolean = Boolean(num);
toBoolean // false;
console.log(typeof toBoolean); // boolean
Enter fullscreen mode Exit fullscreen mode
Data Types Boolean Conversion
1 and 0 true and false
string and '' true and false
' ' true
null, undefined, and NaN false

Happy Coding!!!


Buy me a Coffee


TechStack | Bluehost

  • Get a website with a free domain name for 1st year and a free SSL certificate.
  • 1-click WordPress install and 24/7 support.
  • Starting at $3.95/month.
  • 30-Day Money-Back Guarantee.

Discussion (2)

pic
Editor guide
Collapse
bacloud14 profile image
bacloud14

nice one !

Collapse
bello profile image
Bello Author

Thanks a lot.