forEach / break / continue
Conan
Posted on September 4, 2021
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 })
So, the question is:
"At the end of each run, what will the value of
index
andcount
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)
}
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)
}
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)
}
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?
💖 💪 🙅 🚩
Conan
Posted on September 4, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript Demystifying JavaScript Arrays: A Comprehensive Guide for Beginners and Intermediates
August 21, 2023