DEV Community

Cover image for Data types conversion in JavaScript
Edeke Emmanuel
Edeke Emmanuel

Posted on • Updated on


Data types conversion in JavaScript

*Changing value from one data types to another *

conversion of the value of the declare variable to a different data types can be done by ensuring that the data type to be converted to, is the one used and begins with a Capital letter. For example:

let year = String(1980); 
console.log(year);  //"1980"
Enter fullscreen mode Exit fullscreen mode


Generally: let x = Data-types(value);

List of Data-types

  1. Number
  2. String
  3. Boolean e.t.c

JavaScript has some in built conversion one can explore without the use of methods:

let result;
//For example =>
// String conversion
result = '3' + 2;  // "32"
result = '10' + true;  //"10true"

//Number conversion
result = '10' - '2'; // 8 
result = '10' - 2; //8

//NaN conversion
result = 'hello' - 'world'; // NaN 
result = '4' - 'hello'; //NaN

//Boolean conversion
result = '8' - true;  // 7 
result = 4 + true; //5

//Null conversion
result = 15 + null;  // 15
result = 4 - null; //4
Enter fullscreen mode Exit fullscreen mode

To check what type of data type, make use of typeof

console.log(typeof(num)); //Number

Enter fullscreen mode Exit fullscreen mode

while with method

/* convert to number */

string can be converted to number using Number keyword even other data types such as boolean and null in JavaScript.
for example:
true is known as 1 while false, empty string "" and null is 0 or empty value.
A text, NaN and undefined will return Not a number NaN
Number Conversion

/* method in Number*/

some specific method can be used to convert one data types to a number. Method like:

1. parseInt()
2. parseFloat()
3. /*unary operator*/ +"" 
4. Math.floor()
Enter fullscreen mode Exit fullscreen mode

Number Conversion using methods

/* convert to string */

conversion to string is done with String /*or*/ toString(). example:
String Conversion

/* convert to boolean */

empty string, 0, undefined, NaN and null return false when passed with boolean but others return true.
Boolean Conversion

Let us connect with each other

connection between two or more parties bring solution to a problem






Top comments (0)