Skip to content
Advertisement

Shortcut to checking if a value exist in an object

So I’m trying to get a shortcut to return a value in an object. For example,

const days = {
 Monday: 4,
 Thursday: 3,
 Friday: 1
} 

Now, if I want to do days.Thursday, that value will be undefined, so if I do days.Thursday, it will return undefined, but I would like for it to return 0, if it is undefined. My method of doing this would be to do:

days.Thursday?days.Thursday:0

But doing this is very repetitive and I’d have to do it at least 7 times, for each day of the week, considering this object is being set based off of data from firebase.

Advertisement

Answer

You can use ?? (the nullish coalescing operator) to default to a different value if the expression on the left is undefined (or null):

const thursdayVal = days.Thursday ?? 0;

I’d have to do it at least 7 times, for each day of the week

Consider iterating over an array of property names instead, eg

const dayNames = ['Monday', 'Tuesday', 'Wednesday', /* ... */];
for (const dayName of dayNames) {
  // do something with days[dayName] ?? 0
}
Advertisement