Day 3 of 30 Days of Javascript Interview. In this article, we will learn how to convert the datatype one to another and what changes occurred on changing
Points we covered on the conversion of datatypes :
1) String conversion
2) Boolean conversion
3) Number conversion
4) Implicit Conversion
Number Conversion: You can convert strings or other types to numbers using the Number()
constructor or the parseInt()
or parseFloat()
functions.
let score = "234ab";
console.log(typeof (score))
let valueInNumber = Number(score);
console.log(valueInNumber) // Na N (not a number )
console.log(typeof (valueInNumber)) // Number
// when we convert in number
// "33" = 33
// "33abck" = NaN
// true = 1 ; false = 0
// null = 0
// undefined = NaN
let str = "123";
let num = Number(str); // using constructor
let num2 = parseInt(str); // parsing to integer
let num3 = parseFloat("3.14"); // parsing to float
String Conversion: We can convert other data types to strings using the String()
constructor or the .toString()
method.
let someNumber =10;
let stringNumber = String(someNumber);
console.log(typeof(stringNumber)); // string
console.log(stringNumber) //10
// when we convert in string
// 1 => string
// null => null
// undefined => undefined
// boolean true : true
let num = 123;
let strNum = String(num); // using constructor
let strNum2 = num.toString(); // using method
Boolean Conversion: we can convert other types to boolean using the Boolean()
constructor or by using a truthy/falsy check.
let isLoggedIn = 10 ;
let BooleanIsLoggedIn = Boolean(isLoggedIn);
console.log(BooleanIsLoggedIn) // true
// when we convert in boolean
// 1 => true ; 0=> false
// "" = false
// "alok " = true
// null = false
// undefined = false
Implicit Conversion: JavaScript also performs implicit type conversion when you use operators like +
, ==
, etc. This can lead to unexpected behavior, so it's often better to explicitly convert types when needed.
let strNum = "123";
let num = +strNum; // implicit conversion to number
console.log(typeof(num)) // number