JavaScript Type Conversion

JavaScript Type Conversion

·

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

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
Data TypesNumeric Conversion
true and false1 and 0
stringNaN
' ', ''0, 0
null, undefined, and NaN0, NaN, NaN

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

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
Data TypesBoolean Conversion
1 and 0true and false
string and ''true and false
' 'true
null, undefined, and NaNfalse, false, 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.