steveosoule
4/4/2016 - 8:27 PM

pure-impure-1.js

// Examples of pure functions. No side effects. No mutations. 
function square(x) {
  return x * x;
}

function squareAll(items) {
  return items.map(square);
}

// Examples of impure functions.
function square(x) {
  updateXInDatabase(x); // A side effect. A database is called.
  return x * x;
}

function squareAll(items) {
  // Values passed in are being overwritten.
  for (let i = 0; i < items.length; i++) {
    items[i] = square(items[i]);
  }
}