DEV Community

Cover image for forEach / break / continue
Conan
Conan

Posted on • Updated on

forEach / break / continue

Photo by Dan Meyers on Unsplash

A short Q&A on loops of the standard and functional variety, breaking out of them, and skipping iterations.

All code below assumes the following header:

const { log } = console

const oneThousandItems = () =>
  Array.from({ length: 1000 })
Enter fullscreen mode Exit fullscreen mode

So, the question is:

"At the end of each run, what will the value of index and count be?" 🤔

1. for vs. forEach, full-loops

// 1a)
function forLoop() {
  let index = 0
  let count = 0
  for (; index < 1000; index += 1) {
    count = count + 1
  }
  log('index === ', index)
  log('count === ', count)
}

// 1b)
function usingForEach() {
  let index
  let count = 0
  oneThousandItems().forEach(
    (_, _index) => {
      index = _index
      count = count + 1
    }
  )
  log('index === ', index)
  log('count === ', count) 
}
Enter fullscreen mode Exit fullscreen mode

Next up, breaking-out of loops:

2. for vs. some vs. every, broken loops

// 2a)
function breakLoop() {
  let index = 0
  let count = 0
  for (; index < 1000; index += 1) {
    if (index > 499) { 
      break
    }
    count = count + 1
  }
  log('index === ', index)
  log('count === ', count)
}

// 2b)
function usingSome() {
  let index
  let count = 0
  oneThousandItems().some((_, _index) => {
    index = _index
    if (index > 499) { 
      return true
    }
    count = count + 1
  })
  log('index === ', index)
  log('count === ', count)
}

// 2c)
function usingEvery() {
  let index
  let count = 0
  oneThousandItems().every((_, _index) => {
    index = _index
    count = count + 1
    if (index < 499) { 
      return true
    }
  })
  log('index === ', index)
  log('count === ', count)
}
Enter fullscreen mode Exit fullscreen mode

Finally, skipping to the next iteration:

3. for vs. forEach, skipped loops

// 3a)
function continuedLoop() {
  let index = 0
  let count = 0
  for (; index < 1000; index += 1) {
    if (index > 249) continue 
    count = count + 1
  }
  log('index === ', index)
  log('count === ', count)
}

// 3b)
function usingForEach() {
  let index
  let count = 0
  oneThousandItems().forEach(
    (_, _index) => {
      index = _index
      if (index > 249) return 
      count = count + 1
    }
  )
  log('index === ', index)
  log('count === ', count)
}
Enter fullscreen mode Exit fullscreen mode

If you need a little help, I made a corresponding interactive version of the article that offers some very basic visuals.

I'm not sure if they help intuit what's going on, but they give the answers at least! Did they meet your expectations?

Discussion (0)