JavaScript Loops #
for #
iterator variable is initialized, changed with each loop. Loop ends when some condition met.
Minimal form includes (separated by ;):
- initialization
- stopping condition - as long as the condition is true, loops will keep running
- interation statement / action / thing that happens on each loop
A simple example:
for (let iterVar = 0; iterVar < 10; iterVar++){
console.log(iterVar)
}
// this was loop and print out a value until 10 is reached
Arrays #
.length is handy for looping through arrays.
const someArr = ['first', 'second', 'third']
for (let i = 0; i < someArr.length; i++) {
console.log(`look! ${someArr[i]})
}
// one by one, prints out elements of the array
Don’t forget the let
while #
While a condition is true, loop continues.
This:
for (let iterVar = 0; iterVar < 10; iterVar++){
console.log(iterVar)
}
// this was loop and print out a value until 10 is reached
becomes this while loop:
let iterVar = 0;
while (iterVar < 10>) {
console.log(iterVar);
iterVar++;
}
do-while #
Run the block at least once and then go into a while loop.
If the while condition is true, then the block gets looped.
In its bare form:
do {
...;
} while (some condition);
break #
exit a loop when some condition is met.
for (let i = 0; some condition; i++) {
if (some other condition) {
break;
}
}
nesting #
I generally don’t like this, but sometimes it’s necessary :/
Often used for array comparisons.
const arrFirst = ['A', 'B', 'C'];
const arrSecond = ['B', 'C', 'D'];
for (let i = 0; i < arrFirst.length; i++) {
for (let j = 0; j < arrSecond.length; j++) {
if (arrFirst[i] === arrSecond[j]) {
console.log('This letter is in both arrays: ' + arrSecond[j]);
}
}
}
for-in #
When it comes down to unordered key-value pairs (unlike arrays), we can use the for...in construct.
This runs a block of code in each key-value pair in an object.
let someObj = {
key1: {
keyA: {
...
},
keyB: {
...
},
...,
}
}
for (let someNewVar in someObj.key1) {
...;
}
Where someNewVar is one of the keys under key1.