Type Conversion in JavaScript

What is the definition of type conversion?

Type conversion refers to the process of changing a value from one data type to another.

JavaScript encompasses a wide array of value types. Values can be numerical, strings, objects, Booleans, or even a mixture of these types. At times, you may need to change data from one type to another in order to meet the requirements of a specific operation. Below are the methods for achieving such conversions.

  • Implicit type conversion (automatically executed during code runtime)
  • Explicit type conversion (carried out by the programmer)
  • Note: While explicit type conversion is also called type casting, implicit type conversion is more often called coercion.

Let us examine these two conversions in greater detail.

Implicit type conversion

This form of conversion executes type conversion on its own. For example, when the "+" operator is utilized in JavaScript, it changes a number into a string and then concatenates it with another string.

The phenomenon of implicit type conversion is illustrated through the following examples.

Making an implicit conversion to a string

In the diagram presented below, the '+' operator is utilized, which automatically converts various types of values into the 'string' data type.

Code snippet

Example

"100" + 24; // It will convert 24 to string datatype
'100' + false; // It will convert the false Boolean value to the string datatype
"100" + null; // It will convert the null keyword to a string datatype

It is important to understand that in order to convert a value into a string by utilizing the "+" operator, at least one of the operands must be a string.

Let us explore the subsequent example and analyze the outcomes.

Code:

Example

<html>
<head>
   <title>Example for Implicit conversion from number to string </title>
</head>
<body>
   <script>
      document.write("20" +  24 + "<br/>");
      document.write('20' +  true + "<br/>");
      document.write("20" +  null+ "<br/>");
      document.write("20" +  undefined+ "<br/>");
   </script>
</body>
</html>

Output:

Converting to number (Implicit conversion)

The following example demonstrates how arithmetic operations are performed, along with the automatic conversion of operands into numeric values when string representations containing digits are utilized with arithmetic operators, excluding the '+' operator. Furthermore, Boolean values are similarly transformed into numbers.

Code snippet

Example

'200' / 50; // It converts '200' to 200
'200' - '20'; // It converts '200' and '20' to 200 and 20 and then subtracts each.
'200' * true; // It will convert true to 1
'200' - false; // It will convert false to 0
'tp' / 50 // converts 'tp' to NaN

Code:

Example

<html>
<head>
    <title>Illustration for Implicit conversion to Number </title>
</head>
<body>
    <script>
        document.write(('20' / 50) + "<br>");
        document.write(('20' - '50') + "<br>");
        document.write(('20' * true) + "<br>");
        document.write(('20' - false) + "<br>");
        document.write(('ex' / 50) + "<br>");
      </script>
</body>
</html>

Output:

Implicit Boolean conversion to number

The process of Boolean conversion involves the transformation of an expression into its Boolean equivalent.

Code:

Example

let answer;
answer = '9' - true;
console.log(answer); // 8
answer = 10 + true;
console.log(answer); // 11
answer = 14 + false;
console.log(answer); // 14

Output:

Implicitly converting null to number

When null is employed implicitly in a numerical setting, such as during comparisons or arithmetic operations, it is converted to the value 0. This ensures that operations that include null will consistently yield predictable results in numerical contexts.

Code snippet

Example

let num = 100 + null; // Converts null to 0
num = 100 * null;  // Converts null to 0

Code:

Example

let answer = null + 10;
console.log(answer); // Output: 10

Output:

Undefined with Number and Boolean (Implicit conversion)

When 'undefined' is combined with either a 'number' or a 'Boolean' value, the outcome consistently results in NaN, which signifies "not a number."

Code:

Example

<html>
<head>
   <title> Utilizing undefined with a number and boolean value </title>
</head>
<body>
   <script>
      let num = 100 + undefined; // Prints NaN
      document.write("The value of the num is: " + num + "<br>");
      num = false * undefined; // Prints NaN
      document.write("The value of the num is: " + num + "<br>");
   </script>
</body>
</html>

Output:

Explicit Type Conversion

Developers often find it necessary to manually alter the data type of a variable. This process is referred to as explicit type conversion.

In JavaScript, you can alter the type of a variable by employing either the constructor or various built-in functions.

Explicit conversion: Converting to String

The String constructor can be utilized to transform Booleans, Numbers, and various other data types into strings.

Code snippet

Example

String(null); // converts null to string
String(100); // transforms number to string
String(true); // converts boolean to string

Example 1

To convert a value into a string, make use of the String constructor. Additionally, you can employ the typeof operator to ascertain the type of the resulting value.

Code:

Example

<html>
<head>
    <title>Example for converting number to string explicitly </title>
</head>
<body>
    <script>
        document.write(typeof String(100) + "<br/>");
        document.write(typeof String(null)+ "<br/>");
        document.write(typeof String(true) + "<br/>");	
    </script>
</body>
</html>

Output:

Example 2

We can make use of the toString method available on the Number object, which converts a numerical value into a string format.

Code:

Example

<!DOCTYPE html>
<html>
<body>
<h3>Example for JavaScript toString()</h3>
<p id="example"></p>
<script>
let text = "Welcome";
let result = text.toString();
document.getElementById("example").innerHTML = result; 
</script>
</body>
</html>

Output:

Explicit conversion to Boolean

This involves employing the Boolean function to explicitly convert a value into a boolean type. It enables logical operations and Boolean evaluations by ensuring that the value is recognized as either true or false.

Code snippet

Example

Boolean(0); // 0 is a false value (false)
Boolean(100); // It will recast number to boolean (true)
Boolean(""); // It is an empty string is a false value (false)
Boolean(null); // null is a false value (false)
Boolean("Hello"); // It will recast string to boolean (true)

Example

Values can be converted to Boolean using the Boolean constructor. In this conversion process, all values that are considered truthy are transformed to true, whereas all falsy values, including 0, an empty string, null, undefined, and others, are converted to false.

Code:

Example

<html>
<head>
   <title>Example for converting boolean to string explicitly </title>
</head>
<body>
   <script>
      document.write(Boolean(20) + "<br/>");
      document.write(Boolean(0) + "<br/>");
      document.write(Boolean("") + "<br/>");
      document.write(Boolean("Hello") + "<br/>");
      document.write(Boolean(null) + "<br/>");
   </script>
</body>
</html>

Output:

Date conversion to string/number

The date string can be converted into a numeric format by utilizing the getTime method or by employing the Number constructor of the Date object. This numeric representation of the date yields the cumulative total of milliseconds.

To convert a date into a numerical format, employ the following syntax.

Example

Number(date);
OR
date.getTime();

You can transform a date into a string by utilizing the toString method or by employing the String constructor.

To convert a date into a string format, apply the syntax illustrated below.

Example

String(date);
OR
date.toString();

Let's try utilizing a software application to demonstrate this concept.

Code:

Example

<html>
<head>
   <title>Example for converting date to string/number </title>
</head>
<body>
   <script>
      let date = new Date();
      let numberDate = date.getTime();
      document.write("The date in numeric format is: " + numberDate + "<br/>");
      let dateString = date.toString();
      document.write("The date in string format is: " + dateString + "<br/>");
   </script>
</body>
</html>

Output:

According to the previously mentioned output, the date represented in string format will yield the present date and time.

Using the method parseFloat

In order to transform a string into a floating-point number, we utilize the parseFloat method, which is a built-in function in JavaScript. When applied, if the string contains no numeric characters or if the initial character of the string is not a digit, it will return NaN, which stands for "not a number."

Code:

Example

<!DOCTYPE HTML>
<head>
   <title>Example for converting string to number using parseFloat </title>
</head>
<body>
<script>
function convert_to_float(b) {
var floatValue = parseFloat(b);
return floatValue;
}
var q = "100.8";
q = convert_to_float(q);
document.write("Converted value = " +
q + "</br> Type of " + q + " = "
+typeof q + "<br>");
var q = "-765.89";
q = convert_to_float(q);
document.write("Converted value = " +
q + "</br> Type of " + q + " = "
+typeof q + "<br>");
</script>
</body>
</html>

Output:

Conclusion

In JavaScript, type conversion involves altering a data type to ensure that a function operates correctly. Unlike explicit type conversion, which is performed manually by developers, implicit conversions automatically modify the values without any direct intervention.

Explicit conversion plays a crucial role in altering data types to meet the requirements of a specific function.

Input Required

This code uses input(). Please provide values below: