Iteration Popcorn Hacks
Iterations Popcorn Hacks
Popcorn Hacks on Iterations in JavaScript
Instructions:
Complete the exercises below in JavaScript.
You can run and test your code in a JavaScript environment.
Exercise 1: Counting with a For Loop
Write a JavaScript for loop that prints all numbers from 1 to 10.
Example:
Output:
1
2
3
…
9
10
%%js
for (let count = 1; count <= 10; count++) {
console.log(count);
}
<IPython.core.display.Javascript object>
Exercise 2: Sum of Numbers
Write a for loop in JavaScript to calculate the sum of all numbers from 1 to n using a loop.
Example:
Input: 5
Output: 15 (because 1 + 2 + 3 + 4 + 5 = 15)
%%js
let total = 0;
for (let count = 1; count <= 10; count++) {
total += count;
}
console.log(total);
<IPython.core.display.Javascript object>
Exercise 3: Looping through Arrays
Write a JavaScript program to iterate through an array of names and print each name.
%%js
const names = ['John','Tanisha','Rachit','Jeff'];
for (let i = 0; i < names.length; i++){
console.log(names[i]);
}
<IPython.core.display.Javascript object>