0
0
Javascriptprogramming~5 mins

Iterating over arrays in Javascript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Afor loop
BforEach method
Cmap method
Dfilter method
What does the for...of loop iterate over in an array?
AProperties
BIndexes
CKeys and values
DValues
Which method runs a function on each array element but does NOT return a new array?
AforEach
Bfilter
Cmap
Dreduce
What will this code output? <br> const arr = [1,2,3]; arr.forEach((x, i) => arr[i] = x * 2); console.log(arr);
A[1, 2, 3]
B[2, 4, 6]
C[undefined, undefined, undefined]
DError
Which loop is NOT recommended for arrays because it iterates over all enumerable properties?
Afor loop
Bfor...of
Cfor...in
DforEach
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.