What is the purpose of the array forEach method?

Instruction: Explain how the forEach method works and provide an example of when it would be used.

Context: This question evaluates the candidate's familiarity with array iteration methods, an essential skill for manipulating collections of data in JavaScript.

Updated

Official answer available

Read the opening below, then unlock the full answer and practical guidance.

forEach calls a callback for each present array index in ascending order. The callback receives the value, index and array. It is useful for side effects such as logging; forEach itself returns undefined rather than a transformed array.

const values = [2, 4, 6]; const messages = []; const result = values.forEach((value, index) => { messages.push(`${index}: ${value}`); }); console.log(messages); // ['0: 2',...

Related Questions