Play with the controls to see how the code works. All code is present in the page, but some scrollback may be necessary to grok everything.
# forEach / break / continue / @@iterator
3 min read
Loops of the standard and functional variety, breaking out of them, and skipping iterations.
# for / forEach()
function forLoop() {
let index = 0
let count = 0
for (; index < 1000; index += 1) {
count = count + 1
}
log('done, count === ', count)
}
function usingForEach() {
let count = 0
oneThousandItems().forEach(
(_, index) => {
count = count + 1
}
)
log('done, count === ', count)
}
const { log } = console
const oneThousandItems = () =>
Array.from({ length: 1000 })
# break / some() / every()
function breakLoop() {
let index = 0
let count = 0
for (; index < 1000; index += 1) {
if (index > 499) {
break
}
count = count + 1
}
log('done, count === ', count)
}
function usingSome() {
let count = 0
oneThousandItems().some((_, index) => {
if (index > 499) {
return true
}
count = count + 1
})
log('done, count === ', count)
}
function usingEvery() {
let count = 0
oneThousandItems().every((_, index) => {
count = count + 1
if (index < 499) {
return true
}
})
log('done, count === ', count)
}
# continue / forEach()
function continuedLoop() {
let index = 0
let count = 0
for (; index < 1000; index += 1) {
if (index > 249) continue
count = count + 1
}
log('done, count === ', count)
}
function usingForEach() {
let count = 0
oneThousandItems().forEach(
(_, index) => {
if (index > 249) return
count = count + 1
}
)
log('done, count === ', count)
}
# Object.keys() / values() / entries()
const stars = {
['ð Sirius A']: {
['ð']: 'Alpha Canis Majoris'
},
['âïļ Canopus']: {
['ð']: 'Alpha Carinae'
},
['ð Rigil Kentaurus']: {
['ð']: 'Alpha Centauri'
}
}
const keys = () =>
Object.keys(stars)
const values = () =>
Object.values(stars)
const entries = () =>
Object.entries(stars)
# Symbol.iterator / @@iterator
stars[Symbol.iterator] = function () {
const latinNames = Object
.values(this)
.map(x => x['ð'])
let index = 0
return {
next: () => ({
value: latinNames?.[index],
done: ++index > latinNames.length
})
}
}
function forOfLoop() {
const output = []
for (let star of stars) {
output.push(star)
}
return output
}
function arraySpread() {
return [...stars]
}
# Symbol.iterator / Generator
stars[Symbol.iterator] = function * () {
const latinNames = Object
.values(this)
.map(x => x['ð'])
let index = 0
while (index < latinNames.length) {
yield latinNames[index++]
}
}
function forOfLoop() {
const output = []
for (let star of stars) {
output.push(star)
}
return output
}
function arraySpread() {
return [...stars]
}