0
0
Javascriptprogramming~20 mins

Iterating over arrays in Javascript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
πŸŽ–οΈ
Array Iteration Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of forEach with asynchronous callback
What is the output of this code snippet?
Javascript
const arr = [1, 2, 3];
arr.forEach(async (num) => {
  await new Promise(resolve => setTimeout(resolve, 10));
  console.log(num * 2);
});
console.log('Done');
A
2
4
6
B
2
4
6
Done
CDone
D
Done
2
4
6
Attempts:
2 left
πŸ’‘ Hint
Remember that forEach does not wait for async callbacks to finish.
❓ Predict Output
intermediate
2:00remaining
Output of map with side effects
What is the output of this code?
Javascript
const numbers = [1, 2, 3];
const result = numbers.map((num, index) => {
  console.log(index);
  return num * 2;
});
console.log(result);
A
0
1
2
[2, 4, 6]
B[2, 4, 6]
C0 1 2 [2, 4, 6]
Dundefined
Attempts:
2 left
πŸ’‘ Hint
map calls the callback for each element and returns a new array.
πŸ”§ Debug
advanced
2:00remaining
Why does this for...of loop skip the last element?
Consider this code. Why does it skip printing the last element? const arr = [10, 20, 30]; for (let i of arr) { if (i === 20) break; console.log(i); }
Javascript
const arr = [10, 20, 30];
for (let i of arr) {
  if (i === 20) break;
  console.log(i);
}
ABecause the console.log is inside the if statement and skips 30.
BBecause the loop only iterates twice by default.
CBecause the break stops the loop when i equals 20, so 30 is never reached.
DBecause the array length is incorrectly set to 2.
Attempts:
2 left
πŸ’‘ Hint
What does the break statement do inside a loop?
πŸ“ Syntax
advanced
2:00remaining
Identify the syntax error in this array iteration
Which option contains the syntax error?
Afor (let i = 0; i < arr.length; i++) { console.log(arr[i]); }
Bfor arr in i { console.log(i); }
Cfor (let i of arr) console.log(i);
Dfor (let i in arr) { console.log(arr[i]); }
Attempts:
2 left
πŸ’‘ Hint
Check the order of keywords in the for loop syntax.
πŸš€ Application
expert
3:00remaining
Find the sum of squares of even numbers using array iteration
Which code snippet correctly calculates the sum of squares of even numbers in the array [1,2,3,4,5,6]?
A
const arr = [1,2,3,4,5,6];
const sum = arr.filter(n =&gt; n % 2 === 0).map(n =&gt; n ** 2).reduce((a,b) =&gt; a + b, 0);
console.log(sum);
B
const arr = [1,2,3,4,5,6];
const sum = arr.map(n =&gt; n ** 2).filter(n =&gt; n % 2 === 0).reduce((a,b) =&gt; a + b, 0);
console.log(sum);
C
const arr = [1,2,3,4,5,6];
const sum = arr.reduce((a,b) =&gt; a + b ** 2, 0);
console.log(sum);
D
const arr = [1,2,3,4,5,6];
const sum = arr.reduce((a,b) =&gt; a + (b % 2 === 0 ? b ** 2 : 0), 0);
console.log(sum);
Attempts:
2 left
πŸ’‘ Hint
Filter first to keep even numbers, then square, then sum.