Skip to main content
Lennu.net

Javascript Reduce with String Concatenation Example

For many reduce function is unknown because you rarely need something like it. Reduce is actually a great function which helps your coding a lot if you learn how to use and when to use it.

Reduce takes an array and applies something to each value and returns only one value. In our example we will apply an array of strings to be concatenated together.

The basic syntax of Reduce is:

var x = ['b','c','d'].reduce(function(previous, current, index, array) {
  return previous + current
}, 'a')

If you specify array in the function parameters, you don’t have to include start (‘a’) value. Start value is to be used if you include it.

So this will happen:

  1. a + b
  2. ab + c
  3. abc + d

And after all the rounds our reduce function will return abcd to our x variable.

It might sometimes be hard to find a problem where to use reduce. When you start to use it, you also start to find problems where you can have great benefits by using it. It has great performance and it is supported by major browsers including IE9. You can also find the same function from certain utility libraries such as lodash or underscore.