DEV Community

Cover image for JavaScript Type Conversion
Bello Osagie
Bello Osagie

Posted on • Edited on

JavaScript Type Conversion


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 Media | 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.

Top comments (1)

Collapse
 
bello profile image
Bello Osagie

Thanks a lot.