Page 197 - JavaScript
P. 197

For example, this can be used to ensure that a nullable value is converted to a non-nullable value:


         var nullableObj = null;
         var obj = nullableObj || {};  // this selects {}

         var nullableObj2 = {x: 5};
         var obj2 = nullableObj2 || {} // this selects {x: 5}


        Or to return the first truthy value


         var truthyValue = {x: 10};
         return truthyValue || {}; // will return {x: 10}


        The same can be used to fall back multiple times:


         envVariable || configValue || defaultConstValue // select the first "truthy" of these


        Short-circuiting to call an optional function

        The && operator can be used to evaluate a callback, only if it is passed:


         function myMethod(cb) {
             // This can be simplified
             if (cb) {
                cb();
             }

             // To this
             cb && cb();
         }


        Of course, the test above does not validate that cb is in fact a function and not just an Object/Array/
        String/Number.


        Abstract equality / inequality and type conversion



        The Problem


        The abstract equality and inequality operators (== and !=) convert their operands if the operand
        types do not match. This type coercion is a common source of confusion about the results of these
        operators, in particular, these operators aren't always transitive as one would expect.


         "" ==  0;     // true A
          0 == "0";    // true A
         "" == "0";    // false B
         false == 0;   // true
         false == "0"; // true

         "" !=  0;     // false A
          0 != "0";    // false A
         "" != "0";    // true B




        https://riptutorial.com/                                                                             154
   192   193   194   195   196   197   198   199   200