JavaScript Operators – Understanding the ! Operator

javascriptoperators

I am now confused about ! operator in JavaScript. My understanding was ! operator operates only on boolean. But a comment to one of my answers says it can operate on anything and returns a boolean, which happened to be true after I did some tests.

alert(!undefined); //true
alert(!function(){}); //false
alert(!{}); //false
alert(!null); //true
alert(!()); //crash
alert(!"false"); //false
alert(!false)​;​​​​​​​​​​​​ //true​​​​​​​​​​​​​​​​​​

Can somebody help me generalize the behavior of ! operator.

EDIT

Even more confusing stuff:

​alert( new String() == ""); //true
alert(!""); //true
alert(! new String()); //false

How?

Best Answer

! does what you think: turns true to false and vice-versa. The weird behavior has to do with how Javascript can convert literally anything to true or false.

http://11heavens.com/falsy-and-truthy-in-javascript

Like in C (only worse) all values can be promoted to true or false. The googlable terms you want are "truthy" and "falsy," or "truthiness" and "falsiness." Truthy means something converts to true, falsy means something converts to false. All values are truthy except null, undefined, 0, "", NaN, and... false

This link has more fun examples:

http://www.sitepoint.com/javascript-truthy-falsy/

And this site really likes doing pathological things with the funny behavior here:

http://wtfjs.com

Also note that == really tries hard to make things comparable whereas === just returns false if the things aren't comparable. Crockford in Javascript: The Good Parts recommends not using == entirely.