Prepare for the Salesforce JavaScript Developer Exam. Utilize comprehensive quizzes, flashcards, and multiple choice questions with hints and explanations. Boost your exam readiness!

Practice this question and more.


What will be logged when the following code is executed? [1, 2, 3, 4].reduce((x, y) => console.log(x, y));

  1. 1 2 and 3 3 and 6 4

  2. 1 2 and 2 3 and 3 4

  3. 1 undefined and 2 undefined and 3 undefined and 4 undefined

  4. 1 2 and undefined 3 and undefined 4

The correct answer is: 1 2 and undefined 3 and undefined 4

In the provided code snippet, the `reduce` method is called on the array `[1, 2, 3, 4]`. The `reduce` function takes a callback function which logs the current accumulator (`x`) and the current value (`y`) as it processes each element of the array. Initially, when `reduce` is invoked, it starts with the first two elements in the array. The first invocation of the callback has `x` set to the first element (1) and `y` set to the second element (2), resulting in the log of `1 2`. After the first invocation, the result of the callback is not used for the accumulator (which would typically be carried over to the next iteration), because no value is returned from the callback function. Thus, `x` takes its default value of `undefined` for the subsequent iterations. The next invocation occurs with `x` as `undefined` and `y` as the third element of the array (3), leading to the log of `undefined 3`. The same pattern continues for the last element, where `x` remains `undefined` and `y` becomes 4, which results in the log of `undefined 4