1

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
0

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, is there a more elegant way than this at all: <%= (user && user.pages && user.pages.pageVisits && user.pages.pageVisits.accountPage) ? user.pages.pageVisits.accountPage : '0' %>
0

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")
}

7 Comments

Thanks, this works, but I guess I have to nest a lot to get this to work and the code ends up very messy. Do you know if there is a more elegant solution?
Using a try-catch could clean it up. I edited my post
"Using a try-catch could clean it up" -- you're kidding, aren't you.
What's wrong with a try-catch? It might not be the #1 cleanest way to go about it, but it's better than convoluted boolean logic in certain cases
Well, leaving aside performance penalties and the fact that there is nothing exceptional here (why try and throw?), how would you recover if all you wanted to do is to simply set a variable <%= (user && user.pages && user.pages.pageVisits && user.pages.pageVisits.accountPage) ? user.pages.pageVisits.accountPage : '0' %>. OP doesn't want to log anything, he wants the value to be 0 if there is no such prop.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.