0

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?

2
  • 1
    Just the same as anything else that can use a fallback arr.find() || fallbackValue or with newer syntax arr.find() ?? fallbackValue. Commented Jun 20, 2022 at 14:54
  • 1
    Depends on the contents of this.value. Are they all guaranteed to be objects? Then .find(...) || previous is fine. If they might have falsey values, then use multiple lines as you have but be specific about testing against undefined. ?? is specific for null and undefined only, but there's still a little room for a false positive if null is a legal value. Commented Jun 20, 2022 at 14:54

2 Answers 2

3

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)

Sign up to request clarification or add additional context in comments.

4 Comments

Om my, I was today years old wen I learned that ?? is more useful than || in most cases.
@somethinghere it’s much safer too
@DanielA.White Haven't really ran into issues using || but it's rather interesting and will definitely use it now.
@somethinghere You might if you try it with numbers. I've had problems when I had something like minValue = config.min || 10 - consider the case for config.min = 0, then minValue would be erroneously set to 10 instead of only using the default if there is no config for that. Similar thing if you try to default a string, e.g., description = config.description || "ADD TEXT" or defaulting a boolean to true, e.g., you have required = config.mandatory || true
1

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

Comments

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.