3.8 Iterations Homework in JavaScript

Complete the 4 tasks below as homework:

  1. Uncomment the base code so you can work on adding what you need to produce the correct outputs
  2. Use console.log() to display outputs
  3. Some blanks (_) need to be replaced with numbers or code
  4. Important!!! Under each JavaScript hack, be sure to add an image or screenshot of your outputs in console
  5. Have fun!

🧩 Task #1

Write a for loop that prints the numbers 1 through 10.

%%js
// for (let i = _; i <= _; i++) {
//     console.log(_);
// }
for (let i = 1; i <= 10; i++) {
    console.log(i);
}

<IPython.core.display.Javascript object>

🧩 Task #2

Write a while loop that prints the even numbers between 2 and 20.

%%js
// let num = _;
// while (num <= _) {
//     console.log(_);
//     num += _;
// }
let num = 1;
while (num <= 10) {
    console.log(num);
    num += 1;
}

<IPython.core.display.Javascript object>

🧩 Task #3

Make the following shape using iteration loops with the symbol *:

*
**
***
****
*****
%%js
// let stars = "";
// for (let i = _; i <= _; i++) {
//     stars += "*";
//     console.log(_);
// }
let stars = "";
for (let i = 1; i <= 5; i++) {
    stars += "*";
    console.log(stars);
}

<IPython.core.display.Javascript object>

🧩 Task #4

Use a loop to calculate the sum of all numbers from 1 to 100, and print the result.

%%js
// let sum = _;
// for (let i = _; i <= _; i++) {
//     sum += _;
// }
// console.log("The sum is:", _);
let sum = 0;
for (let i = 1; i <= 5; i++) {
    sum += i;
}
console.log("The sum is:", sum);

<IPython.core.display.Javascript object>
%%javascript

// example of for...of loop, similar to Python's for...in loop
let fruits = ["apple", "banana", "cherry", "strawberry", "orange"];
for (let fruit of fruits) {
    console.log(fruit);
}
<IPython.core.display.Javascript object>