Member-only story

Types of `For`

Jack
1 min readSep 21, 2020

--

There are several methods in JS that use for .

for is typically used as a counter.

for ([initialization]; [condition]; [final-expression])
statement

An example being

for (let i = 0; i < 9; i++) {
console.log(i);
// more statements
}

for…of is primarily used for arrays.

for (variable of iterable) {
statement
}

An example being

const iterable = [10, 20, 30];

for (const value of iterable) {
console.log(value);
}
// 10
// 20
// 30

for…in is primarily used for hashes

for (variable in object)
statement

An example being

var obj = {a: 1, b: 2, c: 3};

for (const prop in obj) {
console.log(`obj.${prop} = ${obj[prop]}`);
}

// Output:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"

--

--

Jack
Jack

Written by Jack

Magician, Mathematician, and Software Engineer

No responses yet