My FeedDiscussionsHashnode Enterprise
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Understanding Coercion in JavaScript

Anurag Nema's photo
Anurag Nema
·Oct 17, 2021·

4 min read

JavaScript may seem to behave strangely for beginners, one of the strange things they may encounter is Coercion. Unlike programming languages like C/C++, we don't need to declare a variable with data types like int, char, etc. JavaScript can determine the type of the variable by itself. That's cool, right? But it's also true that - "With Great Power Comes Great Responsibility". Have you ever seen that 1+'1' = 11 in javascript, how? In this article, we will talk about all this in detail.

jscoercion.jpeg

What is exactly Coercion? Coercion actually refers to the implicit conversion or simply say automatic conversion of one data type to another. Like the conversion of a number to a string, a string to a number, and so on.

coercion.png Let's understand them by following -

1. Number to String

When any non-string value is added to a string, it always converts the non-string value to the string value data type implicitly/automatically. Let's understand this by the code below.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Coercion in Javascript</title>
  </head>
  <body>
    <h1>Type-1 Coercion: Implicit conversion from Number to String</h1>
    <h2 id="heading"><h2>
    <h2 id="coercion_display1"></h2>
    <h2 id="coercion_display2"><h2>
    <script>  
     var head= "Type: "+1; // javascript converts number(1) to string implicitly
      var x = 20 + "21";       // javascript converts number(20) to string implicitly
      var y = "20" + 21;      // javascript converts number(21) to string implicitly
      document.getElementById("heading").innerHTML = head;
      document.getElementById("coercion_display1").innerHTML = x;
      document.getElementById("coercion_display2").innerHTML = y;
    </script>
  </body>
  </html>

Result:

2021-10-17.png

2. String to Number

When we perform operations like subtraction, multiplication, division, etc. all non-number variables written as numbers are converted to numeric data type. Let's understand this with example code below:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Coercion in Javascript</title>
  </head>
  <body>
    <h1>Type-2 Coercion: Implicit conversion from String to Number</h1>
    <h2 id="coercion_display1"></h2>
    <h2 id="coercion_display2"></h2>
    <h2 id="coercion_display3"></h2>
    <h2 id="coercion_display4"></h2>
    <script>
      var a = 5 - "2";    // "2"(String) will convert to 2(number) so 5-2 = 3
      var b = 5 * "2";   // "2"(String) will convert to 2(number) so 5*2 = 10
      var c = 5 / "2";  // "2"(String) will convert to 2(number) so 5/2 = 2.5
      var d = 5 % "2"; // "2"(String) will convert to 2(number) so 5%2 = 1
      document.getElementById("coercion_display1").innerHTML = a;
      document.getElementById("coercion_display2").innerHTML = b;
      document.getElementById("coercion_display3").innerHTML = c;
      document.getElementById("coercion_display4").innerHTML = d;
    </script>
  </body>
</html>

Result:

2021-10-17 (1).png

3. Boolean to Number

When the boolean number is added to the number, the boolean number is converted to a number and then add up with it. Lets's understand this with the code below:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Coercion in Javascript</title>
  </head>
  <body>
    <h1>Type-3 Coercion: Implicit conversion from Boolean to Number</h1>
    <h2 id="coercion_display1"></h2>
    <h2 id="coercion_display2"><h2>

    <script>  
      var p = true+1; // javascript convert true i.e. 1 to number so 1+1 = 2
      var q = false+1;// javascript convert false i.e. 0 to number so 0+1 = 1
      document.getElementById("coercion_display1").innerHTML = p ;
      document.getElementById("coercion_display2").innerHTML = q;
    </script>
  </body>
</html>

Result

2021-10-17 (2).png

4. Equality Operator

In this type, equality operator(==) used to compare their values irrespective of their data type unlike (===) which strictly compare values in addition to data type. Let's understand how coercion is there in this case by the following example -

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Coercion in Javascript</title>
  </head>
  <body>
    <h1>Type-4 Coercion: Equality operator</h1>
    <h2 id="coercion_display1"></h2>
    <h2 id="coercion_display2"></h2>

    <script>
      var x = "2";
      // == operator
      if (2 == x) {
        // x= "2" is a string but as when it is compared to 2 that is non-string(number) are equal
        document.getElementById("coercion_display1").innerHTML =
          "This is true, both are equal";
      } else {
        document.getElementById("coercion_display1").innerHTML =
          "This is false";
      }
      // === operator
      if (2 === x) {
        // x= "2" is a string and 2 that is non-string(number) are not equal as different data type
        document.getElementById("coercion_display2").innerHTML =
          "This is true, both are equal";
      } else {
        document.getElementById("coercion_display2").innerHTML =
          "This is false";
      }
    </script>
  </body>
</html>

Result

2021-10-17 (3).png

So that was all about Coercion in Javascript, i hope it will help you. Kindly give your feedback so I can improve.

Made with Love ❤️