Javascript Data Types Conversions

JS Code Snippets Data Types And Conversions
Share:

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.

/////////////////////////////////////////////////////////////////////

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger