DEV Community

Randy Rivera
Randy Rivera

Posted on • Edited on

Avoiding Mutations and Side Effects Using Functional Programming

  • The issue in the previous posts was with the splice call in the tabClose() function. Unfortunately, splice changes the original array it is called on, so the second call to it used a modified array, and gave unexpected results.
    This is a small example of a much larger pattern - you call a function on a variable, array, or an object, and the function changes the variable or something in the object.

  • One of the core principles of functional programming is to not change things. Changes lead to bugs. It's easier to prevent bugs knowing that your functions don't change anything, including the function arguments or any global variable.

  • Let's try to master this discipline and not alter any variable or object in our code.

  • Let's fill in the code for the function incrementer so it returns the value of the global variable fixedValue increased by one.

var fixedValue = 4;

function incrementer () {

}
Enter fullscreen mode Exit fullscreen mode
  • Answer:
var fixedValue = 4;

function incrementer () {
  return fixedValue + 1;
}

console.log(fixedValue); will display 4
console.log(incrementer()); will display 5;
Enter fullscreen mode Exit fullscreen mode
  • The function incrementer did not change the value of fixedValue(which is 4). and incrementer function should returned a value that is one larger than the fixedValue value.

Top comments (1)

Collapse
 
sharmi2020 profile image
Sharmila kannan

Thank you!!!