Computer >> Computer tutorials >  >> Programming >> Javascript

Explain typecasting in Javascript?


Converting a data type into another is known as type casting. Sometimes there is a need to convert the data type of one value to another. Under some circumstances JavaScript will perform automatic type conversion.

Types of conversions

Automatic Type Conversion

JavaScript expects a boolean in a conditional expression. So JavaScript will temporarily convert the value in parentheses to a boolean to evaluate the if expression −

if (val) {
   console.log( 'yes, val exists' );
}

The following values evaluate to false: 0, -0, '' (empty string), NaN, undefined, and null. All other values evaluate to true, even empty arrays and objects.

Type conversion is also performed when comparing values using the equal (==) and not equal (!=) operators. So when you compare the number 125 with a string '125' using the equals (==) operator, the expression evaluates to true −

console.log( 125 == '125' );

Type conversion is not performed when using the identical (===) and not identical (!==) operators.

Explicit Type Conversion

parseInt and parseFloat

The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN.

The parseFloat() function parses an argument (converting it to a string first if needed) and returns a floating point number.

toString

The toString() method returns a string representing the object, ie, it tries to convert object to string.

Example

let a = 1.015
console.log(a)
console.log(typeof a)
console.log(a.toString())
console.log(typeof a.toString())

Output

1.015
number
1.015
string