user1149620
user1149620

Reputation: 873

Check for undefined property in object in EJS in Node.JS

I have an object, called user, which may or may not have subproperties defined. For example, sometimes there is no "pages" object, sometimes you can go user.pages.someothervariable.

I can see in EJS how to check that user exists, but how can I check that user.pages.someothervariable exists without getting a "cannot access property of undefined" error.

I've tried this and typeof, but cannot get it to work.

<% if(locals.user.pages.pageVisits){ %>foo defined<% }else{ %>foo undefined<% } %>

I get this error:

Cannot read property 'pageVisits' of undefined

Upvotes: 1

Views: 734

Answers (2)

Michael Karpinski
Michael Karpinski

Reputation: 353

You can check if your user has a pages field by running if(local.user.pages). This is because almost any value can be evaluated in if statements in JS. If user.pages is null, then the if statement will return false. If user.pages exists it will return true.

You could do a try-catch to avoid messiness:

var obj = {
  test: "hello"
}

try {
  console.log(obj.fakeKey.otherFakeKey)
}
catch(ex) {
  console.log("Caught")
}

Upvotes: 0

user9539019
user9539019

Reputation:

You can use short-circuiting && --

if(locals.user.pages && locals.user.pages.pageVisits) { /* do sth */ }

If user.pages is falsy, the evaluation won't proceed.

If the chain gets too long, you can try to encapsulate it into a function, like --

function getPage(user) {
    return (user && user.pages && user.pages.accountPage)
        || "0"; // a fallback if the left side is falsy
}

Upvotes: 1

Related Questions