DEV Community

Cover image for Datatype Conversion in Js!!!
Himanshupal0001
Himanshupal0001

Posted on

Datatype Conversion in Js!!!

Hi folks, Today we gonna talk about datatype conversion.
Datatype conversion is basically converting one datatype in another. For example: String -> number or vice-versa.

//type conversion and coercion

let myVar = 34;
console.log(myVar, (typeof myVar));
myVar = String(34); //datatype conversion
console.log(myVar, (typeof myVar));

let booleanVar = true;
console.log(booleanVar, (typeof booleanVar));
booleanVar = Number(true); //this will give 1 as return value because true = 1, false = 0 by default
console.log(booleanVar, (typeof booleanVar));

let arr = [1,2,3,4,5];
console.log(arr, arr.length, (typeof arr) );
arr = String([1,2,3,4,5]);
console.log(arr, arr.length, (typeof arr));


//also can use toString() funtion to convert any datatype to string
let i = 20;
console.log(i, (typeof i));
console.log(i.toString(), (typeof i));//idk why in console it still giving datatype number
//But as you can see in console line 22 already converted to string
//Note* purple color in console shows number value while white color is for string

//Converting to number
let str = "3454";
console.log(str, (typeof str));
str = Number(str);//also pass the variable instade of value
console.log(str, (typeof str));

let str1 = "3456f"
console.log(str1, (typeof str1));
str1 = Number(str1);
console.log(str1, (typeof str1));//This line will give "NaN" as aoutput means not a number


//parseInt
let number = 34.141;
console.log(number, (typeof number));
number = parseInt(number); //parsing number in integer
console.log(number, (typeof number));



//parseFloat
let number1 = 34.434;
console.log(number1, (typeof number1));
number = parseFloat(number1); //parsing number in float
console.log(number1, (typeof number1));

//toFixed function

let numberVar = 30.087;
console.log(numberVar.toFixed(), (typeof numberVar));//by default 0 decimal number will show
console.log(numberVar.toFixed(6), (typeof numberVar)); //six decimal number will show


//Coercion

let mystr = "3454";
let mynum = 45;

console.log(mystr + mynum);

Enter fullscreen mode Exit fullscreen mode

Type conversion is very important part of programming that every developer should know about this.

For example you created a form which is accepting only integer values from frontend but you want everything in string from backend. In such scenarios type conversion would be very useful.

Top comments (0)