Type Conversions in Javascript With Working Examples

javascript type casting

Type conversion is nothing but converting a variable from one data type to another. This process is also termed type casting. There are 2 types of type conversion in javascript:

  1. Implicit conversion – This happens automatically by javascript
  2. Explicit conversion – This is a manual type of conversion
ValueString ConversionNumber ConversionBoolean Conversion
‘ ‘” “0true
Javascript Type Conversion Table

Let’s see Javascript type conversion in detail:

Implicit Conversion to String

See the Pen Untitled by Code Topology (@codetopology) on CodePen.

You can see when number is added with string, it gets concatenated automatically. This means, number is get converted to string.

Implicit Conversion to Number

See the Pen Implicit Type Conversion Of Numbers by Code Topology (@codetopology) on CodePen.

When number is used with number with any of -, /, * these operator, it returns number.

Implicit Boolean Conversion to Number

See the Pen Implicit Conversion with Boolean by Code Topology (@codetopology) on CodePen.

 JavaScript considers 0 as false and all non-zero number as true. And, if true is converted to a number, the result is always 1.

Undefined with Number, Boolean or null

See the Pen Undefined with Number Boolean or null by Code Topology (@codetopology) on CodePen.

Explicit Conversion

You can transform one data type into another according to your requirements. The manual process of converting types is referred to as explicit type conversion. In JavaScript, you can perform explicit type conversions through built-in methods.

Convert to Number Manually

You can use Number() method to convert string numbers and boolean to number. null and blank string return 0. If you pass invalid string to this method, it will return NaN.

You can also use parseInt() method to convert string to number. It will return the string before the decimal point if its a string with decimal number.

Let’s see this in a working example:

See the Pen Explicit Conversion to Number by Code Topology (@codetopology) on CodePen.

Convert to String Manually

You can use String() or toString() method to convert to string data type. There is one major difference between these two methods – String() can convert null and undefined to string but toString() will return an error when null is passed.

See the Pen Explicit Conversion to String by Code Topology (@codetopology) on CodePen.

Convert to boolean manually

To convert variable to boolean data type, you need to use Boolean() method. In Javascript type conversion undefinednull0NaN'' converts to false where as rest all values are converted to true.

See the Pen Untitled by Code Topology (@codetopology) on CodePen.

Leave a Reply

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