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 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
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 Types | Boolean Conversion |
---|---|
1 and 0
|
true and false
|
string and ''
|
true and false
|
' ' |
true |
null , undefined , and NaN
|
false |
Happy Coding!!!
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)
Thanks a lot.