Search code examples
javascriptbreakfor-of-loop

Using Break Statement vs Early Return in Exiting for-of Loop Block in JavaScript


I have a for of loop where I need to exit if there are no resulting values. It occurs to me that I could use an early return statement to handle this, or use a break statement. To be clear, in this case, there is no additional code to execute WITHIN this block of code after the part I'm skipping, so I'm assuming either one would work here (break or return). Any functional or performance reason to use one over the other in this particular case?

OPTION 1: (break)

  for (let diff of differences) {
    if (!diff.path) break;

    if (diff.path[0] !== "updatedAt") {
      const docChange = new ChangedProp(doc, diff, lastEditedBy, "customer");
      docChange.log();
    }
  }

OPTION 2: (return)

  for (let diff of differences) {
    if (!diff.path) return;

    if (diff.path[0] !== "updatedAt") {
      const docChange = new ChangedProp(doc, diff, lastEditedBy, "customer");
      docChange.log();
    }
  }

Solution

  • Any functional or performance reason to use one over the other in this particular case?

    No, if we assume that the for-of loop is the last thing in the function containing it. There may be style arguments one way or the other, but no functional or performance reason.

    Obviously, if there's code after the for-of loop, using break will result in that code getting run, and using return will result in that code being skipped. That's a significant functional difference:

    function a(array) {
      for (const value of array) {
        if (value % 2 == 0) {
          break;
        }
      }
      console.log("This line gets reached");
    }
    function b(array) {
      for (const value of array) {
        if (value % 2 == 0) {
          return;
        }
      }
      console.log("This line does NOT get reached");
    }
    
    const arr = [1, 2, 3];
    a(arr);
    b(arr);

    In that example, the code in a and b are the same other than that a uses break and b uses return (and the text logged at the end is slightly different).

    Without that console.log after the loop, though, no functional difference.