Arrays – reduce(), online
Six activities your students do on their own devices. See who's finished, and their scores.
Arrays – reduce() in one minute
What students need to know
This is exactly what the reduce() method does. The second argument to reduce() is the starting accumulator value.
reduce() returns a single value, not an array. Without return, the accumulator wouldn't carry forward correctly.
Mistakes students make
- 'reduce' must start lowercase - a capital R causes an error.
- Missing the 'return' keyword - without it, nothing is carried forward.
- map() doesn't combine values into one - use reduce() instead.
- This line is missing a semicolon, but that's not required in JS.
What students will learn in this module
Every question in Module 28
Quick questions
- Does reduce() combine all elements into a single value?AYesBNo
- Does reduce() return a new array like map() does?ANoBYes
- Is a return statement needed inside reduce()'s function?ANoBYes
- Can reduce() take a starting value as a second argument?ANoBYes
- Is 'Reduce' with a capital R valid JavaScript syntax?ANoBYes
Key terms
Students type the meaning of:
reduce()
Match the pairs
nums.reduce(function(total, n) { return total + n; }, 0)Match it to what it doesnums.reduce(function(total, n) { return total * n; }, 1)Match it to what it doesCombines every element into a single result valueMatch it to what it doesSets the accumulator's value before the loop beginsMatch it to what it doesnums.Reduce(function(t, n) { return t+n; }, 0)Match it to what it doesnums.reduce(function(t, n) { t + n; }, 0)Match it to what it doesFill in the blanks
let sum = nums.______(function(total, n) {Hint: Type the array method that combines all elements into one value.
let sum = nums.reduce(________(total, n) {Hint: Type the keyword used to define the function passed to reduce.
______ total + n;
Hint: Type the keyword that sends the running total back.
let product = nums.______ (function(total, n) {Hint: Type the array method that combines all elements into one value.
let product = nums.reduce(function(total, n) { ______ total * n; }, 1);Hint: Type the keyword that sends the running total back.
Spot the error
Question 1
Alet a = [1, 2, 3];Blet b = a.Reduce(function(t, n) {Creturn t + n;
Question 2
Alet c = [1, 2, 3];Blet d = c.reduce(function(t, n) {Ct + n;
Question 3
Alet e = [1, 2, 3];Blet f = e.map(function(t, n) {Creturn t + n;
Question 4
Alet g = [1, 2, 3];Blet h = g.reduce(function(t, n) {Creturn t + nD}, 0);
Question 5
Alet i = [1, 2, 3];Blet j = i.reduce(function(t, n) {Creturn t + n;D], 0);
