Intro to iterations
- The basic gist of iterations are to repeat multiple actions for a desirable result
- Used to repeat code more efficiently compared to just writing out all the functions line by line
The syntax of a for loop consists of three main parts:
for (initialization; condition; increment) {
// Code to execute
}
Initialization: This sets up a counter variable and runs once at the beginning of the loop.
Condition: Before each iteration, the loop checks this condition. If it’s true, the loop continues; if false, the loop ends.
Increment: This updates the counter variable after each iteration.
For Loop with Syntax Error
Code Runner Challenge #1
Run loop, the fix the Syntax Error
View IPYNB Source
%%js
// CODE_RUNNER: Run loop, the fix the Syntax Error
for (let i = 1, i <= 5; i++) {
console.log(i);
}
Lines: 1
Characters: 0
Output
Click "Run" in code control panel to see output ...
Usage: Looping Through Arrays
You can use a for loop to iterate over elements in an array.
Code Runner Challenge #2
Run loop, then add another fruit to the array and print all fruits
View IPYNB Source
%%js
// CODE_RUNNER: Run loop, then add another fruit to the array and print all fruits
let fruits = ["Heart Shaped Herb", "Yami Yami no Mi", "Gomu Gomu no Mi"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Lines: 1
Characters: 0
Output
Click "Run" in code control panel to see output ...
Add two of your own fruits and try it out!
Objects
for loops can also be used to iterate objects over each key and its value
Code Runner Challenge #3
Run loop, then change to your Personal Info
View IPYNB Source
%%js
// CODE_RUNNER: Run loop, then change to your Personal Info
const personInfo = { // Define an object
name: "Rishab",
age: 15,
city: "San Diego",
occupation: "High School Student"
};
for (let key in personInfo) { // Notice we are using for... in... instead of for... of...
console.log(key + ": " + personInfo[key]);
}
Lines: 1
Characters: 0
Output
Click "Run" in code control panel to see output ...
Challenge Iteration
Write an iteration to calculate the sum of all numbers from 1 to n
Test it with an input of 5
Hint: use ‘n’ to define your condition, and replace ‘n’ with the number that you want to be the upper limit you are adding to your sum.
Code Runner Challenge #4
Complete function to Sum Numbers from 1 to n, and call the function with a parameter of your choice
View IPYNB Source
%%js
// CODE_RUNNER: Complete function to Sum Numbers from 1 to n, and call the function with a parameter of your choice
function sumNumbers(n) {
let sum = 0;
Lines: 1
Characters: 0
Output
Click "Run" in code control panel to see output ...