Search code examples
javascriptangularjsjasminechutzpah

Angular: module behavior, I don't understant javascript code if ("")


I am using angularjs 1.4.3. And I have a curiosity because I don't understand a piece of code of the code generated by Jasmine Spec Runner.

When we generate it, Jasmine (via ChutzPath) create this code:

    (function () {
        var amdTestPaths = [];
        if (window.require && typeof window.require === "function" && amdTestPaths.length > 0) {
            if (window.chutzpah) {
                window.chutzpah.usingModuleLoader = true;
            }

            if("") {
                require.config({
                    baseUrl: ""
                });
            }

            require.config({
                map: {'*': { } }
            });

            window.require(amdTestPaths, function () {    
                console.log("!!_!! Stating Jasmine from AMD callback...");            
                window.initializeJasmine();
            });
        } else {
           var currentWindowOnload = window.onload;

           window.onload = function() {
           if (currentWindowOnload) {
               currentWindowOnload();
           }

           window.initializeJasmine();
       };
   }
})();

what is it if("")? I know that's stupid question but I don't ubderstand

maybe is like if (true) or if (1)?


Solution

  • As you know, the code within the if statement executes if its condition evaulates to the boolean true. If the condition does not return a boolean, javascript uses Type Coercion to interpret the condition as a boolean. You may read more about Type Coercion here:

    What exactly is Type Coercion in Javascript?

    An article giving the true/false values that different kinds of data takes when type coerced is available here:

    https://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/

    Quoting the relevant section in your case:

    Conditionals

    In JavaScript, all conditional statements and operators follow the same coercion paradigm. We’ll use the if statement by way of example.

    The construct if ( Expression ) Statement will coerce the result of evaluating the Expression to a boolean using the abstract method ToBoolean for which the ES5 spec defines the following algorithm:

    Argument Type   Result
    Undefined       false
    Null            false
    Boolean         The result equals the input argument (no conversion).
    Number          The result is false if the argument is +0, −0, or NaN;
                    otherwise the result is true.
    String          The result is false if the argument is the empty String 
                    (its length is zero); otherwise the result is true.
    Object          true.