Junior
What array traversal methods are you familiar with?
sobes.tech AI
Answer from AI
To iterate over arrays in JavaScript (Frontend), the following methods are known:
-
Loops
for— classic loop with indexfor...of— iterate over array elementswhileanddo...while— conditional loops
-
Array methods
forEach(callback)— calls a function for each element, does not return a new arraymap(callback)— creates a new array by applying a function to each elementfilter(callback)— creates a new array with elements for which the function returnedtruereduce(callback, initialValue)— reduces the array to a single value
-
List comprehension (analog) JavaScript does not have a direct syntax for list comprehension like Python, but
mapandfiltercan be used for similar purposes.
Example of iterating over an array using forEach and map:
const numbers = [1, 2, 3, 4];
// forEach
numbers.forEach(num => {
console.log(num);
});
// map
const squares = numbers.map(num => num * num);
console.log(squares); // [1, 4, 9, 16]
Thus, for iterating over arrays, you can use both classic loops and functional array methods, which make the code more expressive and concise.