Home > Software engineering >  Can `Array.find` use a default value if the callback function doesn't return anything truthy?
Can `Array.find` use a default value if the callback function doesn't return anything truthy?

Time:06-21

I'm using Array.find in one of my JavaScript handlers, and discovered that sometimes there is no truthy test, and so the property gets set to undefined. I worked around it like this:

const previous = this.value;
this.value = this.values.find((value) => value.Id === event.detail.valueId);
if (!this.value) {
    this.value = previous;
}

Is there any way to give a default value to the find method so that if nothing is found it uses that as a fallback?

CodePudding user response:

Yes, you can use the ?? syntax to return a result if your left hand statement is null or undefined

this.value = this.values.find((value) => value.Id === event.detail.valueId) ?? true;

This is called the nullish coalescing operator , and it's a more specific case of the previously common || because that one returns the right hand side value whenever something is "false", not only null or undefined (e.g. also when the LHS is 0 or false)

CodePudding user response:

You can try to use a ternary operator.

const find_value = this.values.find((value) => value.Id === event.detail.valueId)
this.value = find_value ? find_value : previous
  • Related