About
In this code snippet, we’ll learn how to check and convert data types in Javascript.
Let’s see the code example below.
Code:
//Check data types.//////////////////////////////////////////////////
let var1 = "5";
let var2 = 5;
let var3 = false;
let var4 = { property: "I'm a property" };
//...
checkDataType(var1);
checkDataType(var2);
checkDataType(var3);
checkDataType(var4);
function checkDataType(variable){
//Using typeof to checking the data type.
switch(typeof variable){
case "string": console.log("It's a string!");
break;
case "number": console.log("It's a number!");
break;
case "boolean": console.log("It's a boolean!");
break;
case "object": console.log("It's an object!");
break;
case "function": console.log("It's a function!");
break;
case "undefined": console.log("It's undefiend!");
break;
}
}
/////////////////////////////////////////////////////////////////////
//Data type conversions./////////////////////////////////////////////
//Convert string to int.
let intVar = parseInt("5"); //The Number() function does the same.
//convert int to string.
let stringVar = intVar.toString(); //The String() function does the same.
//Convert string to float.
let floatVar = parseFloat("5.5"); //The Number() function does the same.
/////////////////////////////////////////////////////////////////////





