JavaScript – Meaning of ‘!’ Operator with Non-Boolean Variables

javascriptoperators

While reading through javascript codes I've been seeing the ! operator used for non boolean variables. Here is an example of code not used in.

/**
 * loads a resource from a url
 * @param {string} url the url of the resource to load
 * @param {string} relativeTo the url to load relative to
 * @param {function} callback thefunction to call once the file is loaded
 * @private
 */
 GLGE.Wavefront.prototype.loadFile=function(url,relativeTo,callback){
    if(this.relativeTo && !relativeTo) relativeTo=this.relativeTo; //<-- used on a string?
    else this.relativeTo=url;
    if(!callback) callback=this.loaded;    //<-- used on a function?
    var req = new XMLHttpRequest();
    if(req) {
               // request handling code                
            }
        };
        req.open("GET", url, true);
        req.send("");
    }   
}

In this library I've seen many uses of this operator in this manner.

Can someone explain how/if the 'not' function of a string, object or function can be determined when it isn't one half of a Boolean set like the set; true and false?

Best Answer

Any falsy value will satisfy the if(!insert_variable_here) condition, including:

  • false
  • null
  • undefined
  • The empty string ''
  • The number 0
  • NaN

If callback return evaluates any of those values, the condition will be satisfied.

Even though null != false, the following will give you an alert:

x = null;
if(!x) {
    alert('"!null" does evaluate to true');
}

Regardless of whether or not null != false makes sense to you or anyone else, the point is that in JavaScript null is a falsy value, and thus a value that would satisfy the condition in my first bit of code listed above. This, it seems, is the question you have asked--not, rather, if null should or should not == false.

Related Question