JavaScript Type Conversion

Type casting in JavaScript is to convert one type to another.

  • Implicit Conversion: Automatic
  • Explicit Conversion: Manual, using built-in functions

Implicit Conversion

The compiler automatically converts one type to another. This is called Implicit Type Casting. Let us see how this works and converts boolean to number implicitly.

Let us see an example that converts boolean to number implicitly i.e., automatically:

Output

Implicit Conversion in JavaScript

Explicit Conversion

When the compiler will not be able to convert the type, the developer will do it on its own using some built-in methods. This is called Explicit Type Casting.

Let us now see how to explicitly:

  • Convert boolean to number
  • Convert number to string
  • Convert boolean to string
  • Convert number to boolean
  • Convert string to number

Convert boolean to number

The Number() method is used to convert boolean to number in JavaScript. Let us see an example:

Output

Convert boolean to number Explicit type conversion JavaScript

Convert number to string

The String() is used to convert number to string in JavaScript. Let us see an example:

Output

Convert number to string Explicit type conversion JavaScript

Convert boolean to string

The String() is used to convert boolean to string in JavaScript. Let us see an example:

Output

Convert boolean to string Explicit type conversion JavaScript

Convert number to boolean

The Boolean() is used to convert number to boolean in JavaScript. Let us see an example:

Output

Convert number to boolean Explicit type conversion JavaScript

Convert string to number using parseInt()

The parseInt() method parses a string and returns a number in JavaScript. Let us see an example:

Output

Convert string to number using parseInt() Explicit type conversion JavaScript

Convert string to number using parseFloat()

The parseFloat() method parses a string and returns a float in JavaScript. Let us see an example:

Output

Convert string to float using parseFloat() Explicit type conversion JavaScript

JavaScript - Run First Script
JavaScript Functions
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading