What is '!!user' used for? Whats the result of this line?

Viewed 71

I want to craete angular route guard in my app. I found this code but don't understand why we map user to !!user. What's the purpose of map(user => !!user) line?

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> {

      return this.auth.user.pipe()
           take(1),
           map(user => !!user),
           tap(loggedIn => {
             if (!loggedIn) {
               console.log('access denied')
               this.router.navigate(['/login']);
             }
         })
    )
1 Answers

!! is a common way to cast something to a boolean.

By applying the NOT operator (!) twice in the map() function, it maps the user to a boolean which is then used as loggedIn which is used in the tap() function.

Likely the user is supposed to be an object with userdata (which has a truthy value).

I also assume that if you are not logged in, the user will be null or undefined (which has a falsy value).

Related