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

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

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

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy