Data Type Coercion in js

 

 


What is Type Coercion in JavaScript ?

Type Coercion refers to the process of automatic or implicit conversion of values from one data type to another. This includes conversion from Number to String, String to Number, Boolean to Number etc. when different types of operators are applied to the values.

In case the behavior of the implicit conversion is not sure, the constructors of a data type can be used to convert any value to that datatype, like the Number(), String() or Boolean() constructor.

1. String to Number Conversion: When any string or non-string value is added to a string, it always converts the non-string value to a string implicitly. When the string ‘Rahul’ is added to the number 10 then JavaScript does not give an error. It converts the number 10 to string ’10’ using coercion and then concatenates both the strings. Some more examples are shown below.

 

 

 

      let x = 5;
       let y = "5";
       console.log(typeof(x));
       console.log(typeof(y));

    // comparison
       console.log(x == y);  
       console.log(3 < 2 < 1);

       // solution to avoid data type Coercion
       console.log(x === y);  // use strict equality
       console.log(3 < (2 < 1));  // use parantheses  ()

    //plus
       // let sum = x + y;
       //console.log(sum);

       // solution use number() method
       let sum = x + Number(y);
       console.log(sum);

    // minius
    let sub = x - y;
    console.log(sub);


    /*   The Unary + Operator
       The unary + operator can be used to convert a variable to
        a number   */
    y = + x;
     console.log(typeof(y));  

 

 

 

The Unary + Operator

The unary + operator can be used to convert a variable to a number:

et y = "5";      // y is a string
let x = + y;      // x is a number  

 

If the variable cannot be converted, it will still become a number, but with the value NaN (Not a Number):

 

et y = "John";   // y is a string
let x = + y;      // x is a number (NaN)
 

 

Comments

Popular posts from this blog

Variable Scope in javascript

Shadowing

Hoisting