Within a found example code, what is the surprising syntax in an arrow function callback of Array.prototype.find for?

Viewed 79

I found the following example code, and I want to figure out what it does.

projects.find( p => p.value === 'jquery-ui' && ( p.desc = 'your value', true ) );

What is the last true from ( p.desc = 'your value', true ) for? I know that find should return just the first matching array item but I see, with the use of the provided example code, it did not only find the object but it did also change it.

2 Answers

This is actually quite terrible code. ಠ_ಠ

First, the comma operator evaluates all its operands and returns the last one. I.e., p.desc = 'your value', true assigns 'your value' to p.desc and returns true. This is chained to the p.value === 'jquery-ui' check, so only executes when that expression is true. The entire thing is in a find, which iterates over all items until it finds an item where the callback function returns true.

In other words, it's using Array.prototype.find to iterate over all the array entries, and when it finds an entry whose .value is 'jquery-ui', it updates that entry by setting .desc, then ends the find iteration by returning true.

Which is actually quite clever, but:

  1. Introduces a side effect into what should be a pure test callback function and
  2. leads to questions like this because it's unnecessarily clever and hard to comprehend at first sight.

This is a way to find the first object with p.value === 'jquery-ui' and update its desc property to 'your value'.

It's equivalent to:

const found = projects.find(p => p.value === 'jquery-ui');

if (found)
  found.desc = 'your value'
  • First, it checks the p.value === 'jquery-ui' condition. If it returns false, && will short-circuit and will not check the second block. It goes over to the next object in the array.

  • If p.value === 'jquery-ui' is true for some object in the array, && will execute the second expression ( p.desc = 'your value', true ). This uses the comma operator. It evaluates each expression within () and returns the final value. It assigns a new value to the found object and returns true. This is done to short-circuit the find call so that it stops running this callback on any more objects in the array.

  • The comma operator is ONLY required if 'your value' is falsy. In your case, it's a non-empty string. It is redundant and no different to using

     p.value === 'jquery-ui' && p.desc = 'your value'
    
Related