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?
In JavaScript, the unary negation operator (
!) will convert its operand into a boolean based on the (somewhat confusing) rules of the language (e.g., ECMA-262 5th Edition). This article on JavaScript syntax shows some examples of how the type conversion happens.Basically, it’s an easy way to test for non-“truthiness”; seemingly false values (e.g.
false,null,0,NaN, the empty string, etc.) will be converted tofalsebefore being logically negated, and vice versa. You can test for “truthiness” explicitly by using the Boolean constructor: