Home » javascript » Type Conversion in JavaScript

Type Conversion in JavaScript

JavaScript data type or variables can be converted into a different variable and/or different data type by the following ways:

  • Using JavaScript methods
  • By JavaScript itself (automatically)

Converting Numbers to Strings

Using JavaScript method

The JavaScript function String() can convert numbers into strings.

String() can take any numbers, literals, variables or expressions. Consider the examples given below:

The Number method toString() also does the same.

  • Automatically by JavaScript

Consider the following example:

Converting Booleans to Strings

The JavaScript global function String() can also convert booleans into strings.

The Boolean method toString() acts similarly.

Converting Dates to Strings

The global JavaScript method String() also converts dates into strings. Follow the example below:

The Date method toString() does exactly the same.

Converting Strings to Numbers

The JavaScript global method Number() can convert string into number.

Empty strings are converted to numeric 0.

Anything else is converted into NaN (Not a number).

Converting to Boolean

The conversion rule is as follows:

  • Values that are empty like 0, an empty string, null, undefined and NaN are converted to false.
  • Anything other than these values become true.

For example:

Managed by MochaHost - Fast & Easy WordPress Hosting