Javascript Reduce and Rest

JavaScript's Reduce Method / Rest Operator

A quick explanation and demo of an algorithm that loops over a list and adds the values using the reduce() method and the rest operator.

USAGE: Copy and paste the code in the code window below into your Javascipt file directly, or, for demo purposes, simply paste into the Javascript console and hit return.


// REST Operator ... takes all arguments as an array.
// REDUCE method loops over a list (currentValue) and combines elements (accumulator).
// This reduce algorithm replaces the need to loop over a list and increment (accumulator += currentValue).
// Instead of all of that, just do the following:
function sum(...args) { return args.reduce((accumulator,currentValue) => accumulator+currentValue); } console.log(sum(1,2,3,4,5));

Link your website to this page! Copy and paste the URL below:
Copyright 2019. All Rights Reserved.