Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the double exclamation (!!) work in javascript? [duplicate]

Tags:

javascript

I'm going through the Discover Meteor demo, and am struggling to figure out how exactly 'return !! userId;' works in this section:

Posts.allow({   insert: function(userId, doc) {   // only allow posting if you are logged in     return !! userId;   } }); 
like image 891
wordsforthewise Avatar asked Mar 28 '15 00:03

wordsforthewise


People also ask

What does 2 exclamation marks mean in JavaScript?

September 02, 2014. If you have ever noticed a double exclamation mark (!!) in someone's JavaScript code you may be curious what it's for and what it does. It's really simple: it's short way to cast a variable to be a boolean (true or false) value.

What does 2 exclamation marks mean in a text?

This punctation emoji of a double exclamation mark features two big red exclamation points that can be used to express surprise, shock, or to really emphasize or drive home a point.

Should you use double exclamation?

Use the number of exclamation points that's in your heart. Language is supposed to help you communicate what you mean, so if you need two exclamation points for an extra-emphatic opinion and 27 for an announcement to your brother about your promotion, go for it.

What does 3 exclamation marks mean in JavaScript?

So the third use (!! x) turns the "falsey" value into a true boolean. ... with that in mind, the third exclamation point makes a TRUE negation of the original value (a negation of the "true boolean" value).


1 Answers

! is the logical negation or "not" operator. !! is ! twice. It's a way of casting a "truthy" or "falsy" value to true or false, respectively. Given a boolean, ! will negate the value, i.e. !true yields false and vice versa. Given something other than a boolean, the value will first be converted to a boolean and then negated. For example, !undefined will first convert undefined to false and then negate it, yielding true. Applying a second ! operator (!!undefined) yields false, so in effect !!undefined converts undefined to false.

In JavaScript, the values false, null, undefined, 0, -0, NaN, and '' (empty string) are "falsy" values. All other values are "truthy."(1):7.1.2 Here's a truth table of ! and !! applied to various values:

 value     │  !value  │  !!value ━━━━━━━━━━━┿━━━━━━━━━━┿━━━━━━━━━━━  false     │ ✔ true   │   false  true      │   false  │ ✔ true  null      │ ✔ true   │   false  undefined │ ✔ true   │   false  0         │ ✔ true   │   false  -0        │ ✔ true   │   false  1         │   false  │ ✔ true  -5        │   false  │ ✔ true  NaN       │ ✔ true   │   false  ''        │ ✔ true   │   false  'hello'   │   false  │ ✔ true 
like image 74
Jordan Running Avatar answered Sep 24 '22 15:09

Jordan Running