Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of !! javascript [duplicate]

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')

like image 500
ssbb Avatar asked Apr 20 '15 09:04

ssbb


People also ask

What is JavaScript clone ()?

Cloning in javascript is nothing but copying an object properties to another object so as to avoid creation of an object that already exists. There are a few ways to clone a javascript object. 1) Iterating through each property and copy them to a new object. 2) Using JSON method.

What is copy by value and copy by reference in JavaScript?

When you copy an object b = a both variables will point to the same address. This behavior is called copy by reference value. Strictly speaking in Ruby and JavaScript everything is copied by value. When it comes to objects though, the values happen to be the memory addresses of those objects.


3 Answers

!! 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
like image 172
Georgi-it Avatar answered Oct 03 '22 15:10

Georgi-it


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
like image 28
somethinghere Avatar answered Oct 03 '22 16:10

somethinghere


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

!!false === false
!!true === true
like image 21
Rahul Tripathi Avatar answered Oct 03 '22 15:10

Rahul Tripathi