Bird
Raised Fist0
Javascriptprogramming~10 mins

Reduce method in Javascript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Reduce method
Start with initial accumulator
↓
Take next array element
↓
Apply reducer function(accumulator, element)
↓
Update accumulator with result
↓
More elements?
Yes→Take next array element
No↓
Return accumulator
The reduce method starts with an initial value and processes each array element to update an accumulator, returning the final accumulated result.
Execution Sample
Javascript
const numbers = [1, 2, 3];
const sum = numbers.reduce((acc, val) => acc + val, 0);
console.log(sum);
This code sums all numbers in the array using reduce, starting from 0.
Execution Table
StepAccumulator (acc)Current Value (val)OperationNew Accumulator
1010 + 11
2121 + 23
3333 + 36
Exit6-No more elementsReturn 6
💡 All elements processed, reduce returns final accumulator 6
Variable Tracker
VariableStartAfter 1After 2After 3Final
accumulator01366
currentValue-123-
Key Moments - 3 Insights
Why does the accumulator start at 0 and not the first array element?
Because we provided 0 as the initial value in reduce (see execution_table step 1), so accumulator starts at 0 before processing elements.
What happens if we omit the initial value in reduce?
If omitted, reduce uses the first array element as the initial accumulator and starts from the second element, changing how steps proceed.
Why does the accumulator update after each operation?
Because reduce applies the reducer function to combine accumulator and current value, then stores the result as the new accumulator for next step (see execution_table).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the accumulator value after step 2?
A1
B6
C3
D0
💡 Hint
Check the 'New Accumulator' column at step 2 in the execution_table.
At which step does the reduce method finish processing all elements?
AStep 2
BExit
CStep 3
DStep 1
💡 Hint
Look for the row labeled 'Exit' in the execution_table.
If the initial accumulator was 10 instead of 0, what would be the final accumulator?
A16
B6
C10
D13
💡 Hint
Add 10 to the final accumulator 6 shown in variable_tracker final value.
Concept Snapshot
Array.reduce(callback, initialValue)
- Processes array elements one by one
- callback(accumulator, currentValue) returns new accumulator
- Starts with initialValue as accumulator
- Returns final accumulator after all elements
- Useful for sums, products, or combining values
Full Transcript
The reduce method in JavaScript takes a function and an initial value. It starts with the initial value as the accumulator. Then for each element in the array, it applies the function to the accumulator and the current element. The function returns a new accumulator value. This repeats until all elements are processed. Finally, reduce returns the accumulated result. For example, summing [1, 2, 3] with initial 0 results in 6. The execution table shows each step's accumulator and current value, how they combine, and the updated accumulator. Beginners often wonder why the initial value matters and how the accumulator updates. The visual quiz tests understanding of accumulator values at different steps and effects of changing the initial value.

Practice

(1/5)
1. What does the reduce method do in JavaScript?
easy
A. It combines all array elements into a single value.
B. It creates a new array with filtered elements.
C. It sorts the elements of an array.
D. It adds a new element to the end of an array.

Solution

  1. Step 1: Understand the purpose of reduce

    The reduce method processes each element of an array to produce one combined result.
  2. Step 2: Compare with other array methods

    Unlike filter or sort, reduce returns a single value, not a new array or sorted array.
  3. Final Answer:

    It combines all array elements into a single value. -> Option A
  4. Quick Check:

    Reduce = combine into one value [OK]
Hint: Reduce combines array items into one value quickly [OK]
Common Mistakes:
  • Confusing reduce with filter or map
  • Thinking reduce returns an array
  • Assuming reduce sorts elements
2. Which of the following is the correct syntax to use reduce on an array arr to sum its elements (safe for empty arrays)?
easy
A. arr.reduce((acc, val) => acc + val, 0);
B. arr.reduce((acc, val) => acc + val);
C. arr.reduce(acc, val => acc + val);
D. arr.reduce((val, acc) => val + acc);

Solution

  1. Step 1: Check the callback function parameters

    The callback must have (accumulator, currentValue) in that order.
  2. Step 2: Verify initial value usage

    Providing 0 as the initial value ensures correct sum starting point.
  3. Final Answer:

    arr.reduce((acc, val) => acc + val, 0); -> Option A
  4. Quick Check:

    Correct syntax with initial value = arr.reduce((acc, val) => acc + val, 0); [OK]
Hint: Use (acc, val) and initial value for sum [OK]
Common Mistakes:
  • Swapping accumulator and current value parameters
  • Omitting initial value causing errors on empty arrays
  • Incorrect arrow function syntax
3. What is the output of the following code?
const numbers = [1, 2, 3, 4];
const result = numbers.reduce((acc, val) => acc * val, 1);
console.log(result);
medium
A. 10
B. 24
C. 1234
D. Error

Solution

  1. Step 1: Understand the reduce operation

    The reduce multiplies all elements starting with initial value 1.
  2. Step 2: Calculate the product step-by-step

    1 * 1 = 1, 1 * 2 = 2, 2 * 3 = 6, 6 * 4 = 24.
  3. Final Answer:

    24 -> Option B
  4. Quick Check:

    Product of array = 24 [OK]
Hint: Multiply stepwise with initial 1 for product [OK]
Common Mistakes:
  • Adding instead of multiplying
  • Forgetting initial value 1
  • Concatenating numbers as strings
4. Find the error in this code snippet:
const arr = [2, 4, 6];
const sum = arr.reduce((acc, val) => acc + val);
console.log(sum);
medium
A. Accumulator and current value are swapped.
B. Arrow function syntax is incorrect.
C. Missing initial value causes error on empty array.
D. Reduce method cannot sum numbers.

Solution

  1. Step 1: Check for initial value in reduce

    The reduce call lacks an initial value, which is risky if array is empty.
  2. Step 2: Understand consequences

    Without initial value, reduce uses first element as accumulator, which works here but fails on empty arrays.
  3. Final Answer:

    Missing initial value causes error on empty array. -> Option C
  4. Quick Check:

    Initial value missing = Missing initial value causes error on empty array. [OK]
Hint: Always provide initial value to avoid errors [OK]
Common Mistakes:
  • Assuming reduce always works without initial value
  • Confusing parameter order
  • Thinking reduce can't sum numbers
5. Given an array of objects representing sales:
const sales = [
  { product: 'A', amount: 10 },
  { product: 'B', amount: 20 },
  { product: 'A', amount: 15 }
];

// Use reduce to find total sales amount for product 'A'

Which code correctly calculates this total?
hard
A. sales.reduce((acc, item) => acc + item.amount);
B. sales.reduce((acc, item) => acc + item.amount, 0);
C. sales.reduce((acc, item) => item.product === 'A' ? acc + item.amount : acc);
D. sales.reduce((acc, item) => acc + (item.product === 'A' ? item.amount : 0), 0);

Solution

  1. Step 1: Filter and sum only product 'A'

    The reduce callback adds item.amount only if item.product is 'A', else adds 0.
  2. Step 2: Provide initial value 0

    Starting from 0 ensures correct total even if no 'A' products exist.
  3. Final Answer:

    sales.reduce((acc, item) => acc + (item.product === 'A' ? item.amount : 0), 0); -> Option D
  4. Quick Check:

    Filter and sum with initial 0 = sales.reduce((acc, item) => acc + (item.product === 'A' ? item.amount : 0), 0); [OK]
Hint: Add amounts conditionally with initial 0 [OK]
Common Mistakes:
  • Summing all amounts without filtering
  • Omitting initial value causing errors
  • Incorrect conditional logic inside reduce
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard