Sobes.tech
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:

  1. Loops

    • for — classic loop with index
    • for...of — iterate over array elements
    • while and do...while — conditional loops
  2. Array methods

    • forEach(callback) — calls a function for each element, does not return a new array
    • map(callback) — creates a new array by applying a function to each element
    • filter(callback) — creates a new array with elements for which the function returned true
    • reduce(callback, initialValue) — reduces the array to a single value
  3. List comprehension (analog) JavaScript does not have a direct syntax for list comprehension like Python, but map and filter can 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.