Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

! operator in JavaScript

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? ​

like image 544
hrishikeshp19 Avatar asked May 22 '12 21:05

hrishikeshp19


People also ask

What is '$' in JavaScript?

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.

Why operators are used in JavaScript?

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.


1 Answers

! 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.

like image 149
djechlin Avatar answered Sep 28 '22 05:09

djechlin