Pure

Functions

Objectives

  • Define a pure function

Pure Function

A function with no side effects

 

It does not modify its inputs

 

It's repeatable

(same inputs, same outputs)

Not A Pure Function

function doubleVals(arr) {
  for (var i = 0; i < arr.length; i++) {
    arr[i] = arr[i] * 2;
  }
  return arr;
}

Pure Function

function doubleVals(arr) {
  return arr.map(v => v * 2);
}

Not A Pure Function

var person = {id: 53, name: "Tim"};
function addJob(job){
  person.job = job;
}
addJob("Instructor");

Pure Function

var person = {id: 53, name: "Tim"};
function addJob(personObj, job){
  return Object.assign({},
                       perosnObj,
                       {job});
}
addJob(person, "Instructor");

Object Spread

var person = {id: 53, name: "Tim"};
function addJob(personObj, job){
  return {...personObj, job}; 
}
addJob(person, "Instructor");

What does this have to do with React?

All changes to this.state

should be pure