Challenge - 5 Problems
Reduce Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediateWhat is the output of this reduce example?
Consider the following JavaScript code using the reduce method. What will be printed to the console?
Javascript
const numbers = [1, 2, 3, 4]; const sum = numbers.reduce((acc, val) => acc + val, 0); console.log(sum);
Attempts:
2 left
π‘ Hint
Think about how reduce adds each number starting from 0.
β Incorrect
The reduce method adds all numbers starting from 0, so 1+2+3+4 equals 10.
β Predict Output
intermediateWhat does this reduce code output?
Look at this code that uses reduce to find the longest word in an array. What will it print?
Javascript
const words = ['cat', 'elephant', 'dog', 'hippopotamus']; const longest = words.reduce((a, b) => a.length > b.length ? a : b); console.log(longest);
Attempts:
2 left
π‘ Hint
Reduce compares lengths and keeps the longer word.
β Incorrect
The reduce compares each word and keeps the longest. 'hippopotamus' is longest.
β Predict Output
advancedWhat is the output of this reduce with objects?
This code uses reduce to count how many times each color appears. What is the output?
Javascript
const colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']; const count = colors.reduce((acc, color) => { acc[color] = (acc[color] || 0) + 1; return acc; }, {}); console.log(count);
Attempts:
2 left
π‘ Hint
Each color is counted by adding 1 to its current count.
β Incorrect
The reduce counts each color's occurrences correctly: red 2, blue 3, green 1.
β Predict Output
advancedWhat error does this reduce code cause?
What error will this code produce when run?
Javascript
const arr = []; const result = arr.reduce((a, b) => a + b); console.log(result);
Attempts:
2 left
π‘ Hint
Think about what happens when reduce has no initial value and the array is empty.
β Incorrect
Reduce throws a TypeError if the array is empty and no initial value is given.
π§ Conceptual
expertWhich option produces the product of all numbers using reduce?
You want to multiply all numbers in an array using reduce. Which option correctly does this?
Attempts:
2 left
π‘ Hint
Start with 1 and multiply each value to the accumulator.
β Incorrect
Option A multiplies all numbers starting from 1. Option A fails on empty arrays. B adds instead of multiplies. D multiplies val by itself, ignoring acc.
