266

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; } }); 
1

1 Answer 1

675

! 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
Sign up to request clarification or add additional context in comments.

7 Comments

Note worthy (as with "hello") !!"false" #=> true
It seems that it works the same as the JavaScript Boolean method
JavaScript Boolean method Example: console.log(Boolean(12)); > true
@SergeyZolotarev I've seen this being used: let array = [1, 2 ,3]; !!array.length && ...do something...
@Stokely What you described are not "edge cases". In JS, an empty string is falsey and non-empty strings are truthy. Doesn't matter what is contained inside the string, a non-empty string is a non-empty string. What you may be confused about is when using the == operator to compare two operands. This will coerce values to some other type for the sake of the comparison and give unexpected results. You're better off using === or !== for comparison in JS as it will take into account the type and not do any conversion. stackoverflow.com/a/359509/2565869
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.