Intro to iterations
The Break Statement
- We use it to terminate a loop/switch
%%js
for (let i = 0; i < 10; i++) {
if (i == 6) {
break;
}
console.log(i);
}
<IPython.core.display.Javascript object>
Output
0
1
2
3
4
5
- When i = 6, the break statement is run, and it ends the loop early
Continue Statement
- used to restart a while or for loop
- when used, ends the current iteration, and continues the next iteration
%%js
for (let i = 0; i < 10; i++) {
if (i == 6) {
continue;
}
console.log(i);
}
<IPython.core.display.Javascript object>
Output
0
1
2
3
4
5
7
8
9
- Notice how it skips 6 and continues the loop
For each loops
- We did this in the previous lesson to loop through an array
%%js
const colors = ['red','blue','yellow','green','black'];
for (let i = 0; i < colors.length; i++){
console.log(colors[i]);
}
<IPython.core.display.Javascript object>
There is a different way to do this
%%js
const colors = ['red','blue','yellow','green','black'];
//color = i
for (let color of colors) { //checks each element in the list
console.log(color); //prints each color
}
<IPython.core.display.Javascript object>
- These blocks of code both have the same output
Output
red
blue
yellow
green
black
Edit Popcorn hack 3 to work with for each loops
Nested For Loops
- You can put for loops inside for loops
- these are called nested for loops
- pretty simple
Example
%%js
for (let i = 0; i < 3; i++){
for (let j = 0; j < 3; j++){
console.log(j);
}
console.log('\n');
}
<IPython.core.display.Javascript object>