Câu hỏi phỏng vấn Javascript
Câu hỏi

Can you describe the main difference between a .forEach loop ...

Câu trả lời

In JavaScript, both .forEach() and .map() are methods used to iterate over the elements of an array, but they serve different purposes and have different behaviors which influence when you would choose one over the other.

Main Differences

  1. Return Value:

    • .forEach() executes a provided function on each array element but does not return a value. It always returns undefined[1][2][5].
    • .map(), on the other hand, creates and returns a new array that contains the results of calling a provided function on every element in the array it is called upon[1][2][5][16][17].
  2. Purpose and Usage:

    • Use .forEach() when you need to execute a function on each item in an array and do not need to return a value. It is typically used for operations that involve side effects, such as modifying an external variable or performing I/O operations[1][2][5][15].
    • Use .map() when you need to transform elements in an array and return a new array with the transformed elements. This is useful for cases where you need to apply a function to each element of an array and use the array that results from those operations[1][2][5][16][17].
  3. Immutability:

    • .forEach() does not inherently return a new array and generally does not mutate the original array unless the provided function does so[1][2][5].
    • .map() returns a new array and does not mutate the original array, which aligns with functional programming principles where immutability is a key aspect[1][2][5][16][17].

Choosing Between .forEach() and .map()

  • Choose .forEach() if you are performing operations where you do not need to return data. For example, logging each item of an array to the console or updating the UI for each item in an array.
  • Choose .map() if you need to transform the original array into a new array, while keeping the original array unchanged. This is particularly useful in scenarios where you need to apply a transformation or computation to the data, such as multiplying each element by a factor, or extracting a specific property from each object in an array of objects.

#...

senior

senior

Gợi ý câu hỏi phỏng vấn

middle

What is Currying in javascript?

middle

Suggest one simple way of removing duplicates from an array using ES6

middle

What is generator in JS?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào