What exactly is Type Coercion in Javascript?

前端 未结 10 1319
后悔当初
后悔当初 2020-11-22 04:36

What exactly is type coercion in Javascript?

For example, on the use of == instead of ===?

10条回答
  •  滥情空心
    2020-11-22 05:17

    What is coercion:

    Type coercion in javascript occurs when the Javascript engine has to perform a certain operation for which it needs data to be in a certain type. When the engine encounters data in a certain type that is not applicable for the operation it then coerces the data into a certain type. This is needed because variables in javascript are dynamically typed, which means that a given variable can be assigned a value of any type.

    Example:


    if(1){
      // 1 gets coerced to true
    }
    
    
    if(4 > '3') {
      // 3 gets coerced into a number
    }
    
    
    44 == "44"  // true, the string 44 gets converted to a nr
    

    Boolean coercion:

    In javascript coercion, all values are converted to true except for the following values which are coerced to false:

    console.log(!!"");         // false
    console.log(!!0);          // false
    console.log(!!null);       // false
    console.log(!!undefined);  // false
    console.log(!!NaN);        // false
    console.log(!!false);      // false

    Also notice that in the above example that the double ! operator is used. The ! mark operator coerces a value into a boolean with the opposite value. We can use this operator twice to convert any value into a boolean.

提交回复
热议问题