Why is my js function returning itself rather than the returned value? [Angular]

I’ve gotta be missing something obvious, but I can’t figure it out and it’s driving me crazy. I’m using angular and I have a factory ‘Auth’ which has this function in the return { } of ‘Auth’ (forced to return false for emphasis):

isAuthenticated: function() {
            var storedJwt = $window.sessionStorage.authToken;
            console.log('stored JWT: '+storedJwt);
            if(storedJwt){
                var storedPayload = jwtHelper.decodeToken(storedJwt);
                console.log('payload: '+JSON.stringify(storedPayload));
                if(jwtHelper.isTokenExpired(storedJwt)){
                    console.log('is expired expired: '+jwtHelper.getTokenExpirationDate(storedJwt));

                    delete $window.sessionStorage.authToken;
                } else {
                    console.log('is not expired expires: '+jwtHelper.getTokenExpirationDate(storedJwt));    
                }
            }

            return false;
            //LocalService.get('authToken');
        },

Then in a controller I’m doing this:

$scope.isLoggedIn = function(){
    console.log('chk:'+Auth.isAuthenticated);
    return Auth.isAuthenticated;
};

the console.log though is showing: http://grab.by/GZSw

And so always returns true. Why can’t I get it to be false? I think this is probably very basic js issue, but I don’t get it.

Answer

Auth.isAuthenticated is a reference to the function. It is not calling the function.

Therefore, it will always be truthy and never calls the function either. It is simply an object now.

If you want the return a value from inside the function you need to call it:

return Auth.isAuthenticated();

That being said, there are conditions in the function that don’t return anything and the function itself never returns true inside.

Leave a Reply

Your email address will not be published. Required fields are marked *