7

I found some code about authentication with angular and i can't understand this trick :

authService.isAuthenticated = function () {
    return !!Session.userId;
};

What does !! mean 'different of userId' ?

whenever true = !!true = !!!!true =>etc, it don't understand this.

Somebody can help me?

(https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec for the source , part 'The AuthService')

Rahul Tripathi
  • 152,732
  • 28
  • 233
  • 299
ssbb
  • 1,809
  • 1
  • 18
  • 37

4 Answers4

11

!! Converts any value to a boolean value

 > !!null
 false

 > !!true
 true

 > !!{}
 true

 > !!false
 false

If a value is falsey then the result will be false. If it is truthy the result will be true.

Even more, the third ! inverts the converted value so the above examples become:

    > !!!null
    true

    > !!!true
    false

    > !!!{}
    false

    > !!!false
    true
Georgi-it
  • 3,458
  • 1
  • 17
  • 23
2

It forces what is returned to be a boolean and not an integer or empty value. For example, 0 evaluates to false with == but will not with ===. So to be sure that any integer 0 returned will be converted into an boolean, we use !!. This also works if null or undefined is returned.

So whats happening is actually:

var test = null;
var result = !test; // returns true
    result = !return; // returns false
somethinghere
  • 14,155
  • 2
  • 23
  • 39
1

!! is used to convert the value to the right of it to its equivalent boolean value.

!!false === false
!!true === true
Rahul Tripathi
  • 152,732
  • 28
  • 233
  • 299
0

Coerces oObject to boolean. If it was falsey (e.g. 0, null, undefined, etc.), it will be false, otherwise, true.

!oObject  //Inverted boolean
!!oObject //Non inverted boolean so true boolean representation

So !! is not an operator, it's just the ! operator twice.

Referred from : https://stackoverflow.com/a/784946/2218635

Community
  • 1
  • 1
Ramesh Rajendran
  • 32,579
  • 35
  • 130
  • 205