Recall & Review
beginner
What is the simplest way to loop through all elements in an array in JavaScript?
Using a
for loop with an index to access each element one by one.Click to reveal answer
beginner
How does the
forEach method work on arrays?It runs a function once for each element in the array, giving you access to the element and its index.
Click to reveal answer
intermediate
What is the difference between
for...of and for...in when iterating arrays?for...of loops over the values (elements) of the array, while for...in loops over the keys (indexes). For arrays, for...of is usually preferred.Click to reveal answer
intermediate
Can you modify the original array elements inside a
forEach loop?Yes, if you access the array by index inside the
forEach callback, you can change elements. But changing the parameter directly won't affect the array.Click to reveal answer
intermediate
What happens if you use
break inside a forEach loop?break does not work inside forEach. To stop early, use a regular for loop or for...of loop.Click to reveal answer
Which loop is best to use if you want to stop iterating an array early?
✗ Incorrect
Only a regular for loop allows using break to stop early.
What does the
for...of loop iterate over in an array?✗ Incorrect
for...of loops over the values (elements) of the array.Which method runs a function on each array element but does NOT return a new array?
✗ Incorrect
forEach runs a function on each element but returns undefined.What will this code output? <br>
const arr = [1,2,3]; arr.forEach((x, i) => arr[i] = x * 2); console.log(arr);✗ Incorrect
The array elements are doubled by modifying them inside forEach.
Which loop is NOT recommended for arrays because it iterates over all enumerable properties?
✗ Incorrect
for...in loops over all enumerable properties, which can include inherited ones, so it's not ideal for arrays.Explain three different ways to iterate over an array in JavaScript and when you might use each.
Think about control flow and readability.
You got /4 concepts.
Describe why you cannot use break inside a forEach loop and what you can do instead to stop iteration early.
Consider how forEach is a function call.
You got /3 concepts.