We can use the forEach method to pass through the elements of an array.
Which of the following code snippets will display all consecutive elements of the animals array in the console?

  • animals.forEach(console.log(animal));
  • forEach(animals, a => {
       console.log(a);
    })
  • animals.forEach(a => a);
  • animals.forEach(a => {
        console.log(a);
    })
Explanation & Hint:

Let’s analyze the code snippets one by one:

animals.forEach(console.log(animal));

This code snippet is incorrect. It directly calls console.log(animal) instead of passing a function reference or an arrow function. It will immediately execute console.log(animal) for each element of the animals array, but it won’t display the consecutive elements correctly.

animals.forEach(a => a);

This code snippet is also incorrect. The arrow function a => a doesn’t perform any action or output anything. It doesn’t contain any code to display the elements of the animals array in the console.

animals.forEach(a => { console.log(a); });

This code snippet is correct. It uses the forEach method on the animals array and provides an arrow function as the callback function. Inside the arrow function, console.log(a) is called to display each element of the animals array in the console. This will correctly display all consecutive elements of the animals array.

forEach(animals, a => { console.log(a); });

This code snippet is incorrect. It calls an undefined function forEach and tries to pass the animals array as the first argument. The correct usage is to call the forEach method directly on the array, like animals.forEach(…), as shown in snippet 3.

For more Questions and Answers:

JavaScript Essentials 1 | JSE1 – Module 5 Test Exam Answers Full Score 100%