How to avoid undefined variable errors in inline statement

Hi, I’d like to display age in contacts for contacts whose birthdate I know, and it works quite well:

- born:: 2000-01-01
- `= "age " + (date(today) - this.born).years + "y"`

However, when I don’t know the date and leave the born variable empty/undefined, I get an error. I tried the following and I thought it would simply display “age unknown” when born is empty:

`= choice(this.born, "age " + (date(today) - this.born).years + "y", "age unknown")`

However, this still ends up with the same error. I spent most of the day looking for a way to do this, but couldn’t find it. Is there a way?

Thanks in advance.

(I’m a newbie, so take my answer with a grain of salt)

Might require dataviewjs?

if (dv.current().born) 
// date math here using moment.js, luxon, etc?
} else 
dv.paragraph("birthdate missing")

I don’t know why - because in choice(bool, left, right) the main logic should be “if this.born null, choice right” - but in some way it seems to check the “left” expression too.

In that case it fails because it can’t accept “date - null”. It seems a kind of bug.

To bypass this behavior, it’s necessary, in the expression (date(today) - this.born).years, find a away to avoid “this.born” as null if no born value.

Try this:

= choice(this.born, "age " + ((date(today) - default(this.born, date(today))).years) + "y", "age unknown")

With the function default(field, value)default(this.born, date(today)) - we said: "if this.born null use “date(today)” as value (or date(yesterday) or other valid date… Just to avoid the null. (in this case date value isn’t important, it’s just a away to avoid a false step.)

1 Like

Thanks a lot, this works perfectly.

= choice(this.born, "age " + (date(today) - default(this.born,date(today))).years + "y", "age unknown")

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.