ðŸŠī\zansh.in\js

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]
}

Google it:

ðŸŒļ addition assignment 🌚 Array every 🌷 Array fill ðŸŒŧ Array forEach 🌞 Array some ðŸŒđ closures 💐 destructuring assignment ðŸŒļ for-break 🌚 for-continue 🌷 for-loop ðŸŒŧ generators 🌞 iteration protocols ðŸŒđ Object entries 💐 Object keys ðŸŒļ Object values 🌚 spread rest