DEV Community

Oleg Yuzvik
Oleg Yuzvik

Posted on

Check and assign value or just assign value?

Sometimes there is a need to set some flag if one of the items in the collection satisfies a condition. It is usually done in the loop of some kind, like this:

let hasEdibleBananas = false;

bananas.forEach(banana => {

  // ... do some banana related stuff here

  if (banana.isYellow) {
      hasEdibleBananas = true;
  } 
})


This code works, but we reassign value to hasEdibleBananas multiple times in case there is more than 1 yellow banana.
We could add another condition that checks if hasEdibleBananas is already set before assigning a value to it:

let hasEdibleBananas = false;

bananas.forEach(banana => {

  // ... do some banana related stuff here

  if (banana.isYellow && !hasEdibleBananas) {
      hasEdibleBananas = true;
  } 
})


My question is, whether there is really a need for checking if the hasEdibleBananas flag is set before setting it.
As far as I know, there should not be any perceivable performance benefit in the second case - when we perform additional check, neither do I think that the code is more or less readable in either of the cases. In fact, some could say that adding another condition that doesn't make any difference from the functionality point of view adds unnecessary noise to the code and thus makes it less readable.

What do you think?

Top comments (0)