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?
Updated on July 03, 2019. The dollar sign ($) and the underscore (_) characters are JavaScript identifiers, which just means that they identify an object in the same way a name would. The objects they identify include things such as variables, functions, properties, events, and objects.
Operators are used to perform specific mathematical and logical computations on operands. In other words, we can say that an operator operates the operands. In JavaScript operators are used for compare values, perform arithmetic operations etc.
!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With