Search code examples
javascriptangularjsrootscope

Undefined is not an object - Angular $rootScope.user.userMessage


I keep getting an error of

Error: undefined is not an object (evaluating '$rootScope.user.userMessage')

with this code:

if (typeof($rootScope.user.userMessage) === null) {

but if I do have something in $rootScope.user.userMessage it doesn't crash. How can I perform a check to see if this is undefined or null so that the thing doesn't break?

other things i've tried include:

if (typeof($rootScope.user.userMessage) === undefined) {
if ($rootScope.user.userMessage === undefined) {

Solution

  • if($rootScope.user && $rootScope.user.userMessage){
        ...
    }