All sample questions / JavaScript
What does console.log(['a', 'b', 'c'].reduceRight((acc, x) => acc + x)) print? JavaScript Arrays and Iteration
Block 4, Arrays and Iteration, question 2 of the JavaScript sample
console.log(['a', 'b', 'c'].reduceRight((acc, x) => acc + x));
What does this print?
Show the answer and why each option is right or wrong
Answer, C. cba
- A. abc
- Assumes reduceRight processes the array in the same left to right order as reduce. reduceRight always folds the array starting from the last element and moving toward the first.
- B. cab
- Assumes the last element ends up somewhere in the middle of the result rather than at the very front. reduceRight starts its very first step with the last two elements, so the last element always leads the accumulation.
- C. cba
- Correct. reduceRight folds the array from right to left, so starting from "c" and appending "b" then "a" produces the string "cba".
- D. undefined
- Assumes reduceRight without an explicit initial value fails the same way reduce does on an empty array. The array here is not empty, so the last element simply becomes the seed and the reduction proceeds normally.
reduceRight behaves exactly like reduce except that it processes the array from the last element toward the first. Without an initial value it seeds the accumulator with the last element rather than the first, then works backward through the rest of the array.
The answer above is what the Node interpreter printed when the snippet was run, not what someone expected it to do.
This question comes from a bank of 600 JavaScript interview questions, all built the same way, sold as one PDF with the full answer key.
Get the 600 JavaScript questions, 9 euros
Or play the free JavaScript sample, twenty questions in the browser, also as a free PDF.
Previous question Next question
Did this save you a lookup? Buy me a coffee on Ko-fi.