Search code examples
javascriptarraysoptional-chaining

Optional chaining on Array.find in JS


In JavaScript, is it possible to do something akin to an optional chain on Array.find? I.e., like in the (incorrect) example below?

let myArray = [{name: "foo", value: 30}, {name: "abc", value: 40}];
myArray.find(entry => entry.name === 'foo')?.value = 50;

I tried the above syntax, but it throws an error, and I was wondering if there is some neat one-line way to achieve this without having to declare another variable to store the Array.find result and check if it is truthy before you can set value = 50.


Solution

  • When you do:

    ({a:1})?.a = 10
    

    What you are really doing is:

    1 = 10
    

    Which causes the same error as you have observed. So you cannot use optional chaining to set values.

    Assuming you want to mutate the element of an array what you could do is use ?? to default to empty object in case Array#find returns null. If an element is found you can modify it, if not you're just assigning 50 to an object that is immediately discarded:

    let myArray = [{name: "foo", value: 30}, {name: "abc", value: 40}];
    (myArray.find(entry => entry.name === 'foo') ?? {}).value = 50;