Code Anatomy - For loops, array reduce and method chaining

JavaScript, Array, Iterator · Jun 12, 2021

For loops

const files = [ 'foo.txt ', '.bar', '   ', 'baz.foo' ];
let filePaths = [];

for (let file of files) {
  const fileName = file.trim();
  if(fileName) {
    const filePath = `~/cool_app/${fileName}`;
    filePaths.push(filePath);
  }
}

// filePaths = [ '~/cool_app/foo.txt', '~/cool_app/.bar', '~/cool_app/baz.foo']
  • Any for loop can be used - read more about the different JavaScript loops.
  • Less common nowadays, due to functional programming being more popular.
  • Control over the iteration, such as skipping over elements or early returns.
  • Resulting array needs to be declared beforehand, outside the loop.
  • Uses Array.prototype.push() or the spread (...) operator to add elements.
  • O(N) complexity, each element will be iterated over only once.

Array reduce

const files = [ 'foo.txt ', '.bar', '   ', 'baz.foo' ];
const filePaths = files.reduce((acc, file) => {
  const fileName = file.trim();
  if(fileName) {
    const filePath = `~/cool_app/${fileName}`;
    acc.push(filePath);
  }
  return acc;
}, []);

// filePaths = [ '~/cool_app/foo.txt', '~/cool_app/.bar', '~/cool_app/baz.foo']
  • Uses Array.prototype.reduce() with an empty array as the initial value.
  • More common nowadays, due to functional programming being more popular.
  • Less control over the iteration, cannot skip elements or return early.
  • Can be chained with other methods, if necessary.
  • Uses Array.prototype.push() or the spread (...) operator to add elements.
  • O(N) complexity, each element will be iterated over only once.

Method chaining

const files = [ 'foo.txt ', '.bar', '   ', 'baz.foo' ];
const filePaths = files
  .map(file => file.trim())
  .filter(Boolean)
  .map(fileName => `~/cool_app/${fileName}`);

// filePaths = [ '~/cool_app/foo.txt', '~/cool_app/.bar', '~/cool_app/baz.foo']
  • Uses Array.prototype.map() and Array.prototype.filter().
  • More common nowadays, due to functional programming being more popular.
  • Less control over the iteration, cannot skip elements or return early.
  • Declarative, easier to read and refactor, chain can grow as necessary.
  • Does not use Array.prototype.push() or the spread (...) operator.
  • O(cN) complexity, c iterations per element, (c: length of the chain).

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • JavaScript Array Methods

    Get acquainted with some common JavaScript array methods, as well as some more advanced array tricks.

    Collection · 7 snippets

  • Tip: Use JavaScript for loops if you need to break out early

    JavaScript provides a handful of ways to iterate over data. While array methods are usually preferred, there are cases where a for loop is actually the best option.

    JavaScript, Array · Jun 12, 2021

  • Filter matching and unspecified values

    Filters an array of objects based on a condition while also filtering out unspecified keys.

    JavaScript, Array · Oct 22, 2020

  • Array of successive values

    Applies a function against an accumulator and each element in the array (from left to right), returning an array of successively reduced values.

    JavaScript, Array · Oct 22, 2020