Type Conversion in JavaScript

Type Conversion in JavaScript means converting one data type to another.

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

In JavaScript, you can convert dates to strings using the toString() method or the toDateString() method. Both methods return a string representation of the date.

Here is an example:

You can also use the toLocaleString() method or toLocaleDateString() method to format the date string according to the user’s locale settings.

Here is an example:

You can also use other options for the toLocaleString() and toLocaleDateString() methods to format the date string according to different locales and styles.

Converting Strings to Numbers

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

Empty strings are converted to a numeric 0.

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

Converting to Boolean

In JavaScript, you can convert other data types to Boolean using the Boolean() function.

Here are the rules for how other data types are converted to Boolean:

  • Strings: An empty string (“”) is converted to false, while all other strings are converted to true.
  • Numbers: 0, NaN, and -0 are converted to false, while all other numbers are converted to true.
  • Null and Undefined: Both null and undefined are converted to false.
  • Objects and Arrays: All objects and arrays are converted to true.

Here are some examples:

We can also use the double negation (!!x) to convert a value to Boolean, which is equivalent to using the Boolean() function.

Hope you understand Type Conversion in JavaScript.