Don’t alter a variable or object within a function - is that true?

Hi

I was wondering about this lesson: Refactor Global Variables Out of Functions

Once I passed the challenge, I was a bit disappointed. What is the reason you should not alter objects inside functions? It made sense when I read it on the surface, but once I get into coding projects, I would’ve made a function to actually change the object (or array data) and not return a new object instead.

Could anyone elaborate on this, whether it’s really or not considered as bad coding practise to go against this rule:

  1. Don’t alter a variable or object - create new variables and objects and return them if need be from a function.
1 Like

If you do Functional Programming, you’d better follow those recommandations or else when your program grows, it may become uncontrollable and messy.

Here’s an example of a code that changes an array:

var bookList = ["The Hound of the Baskervilles", 
"On The Electrodynamics of Moving Bodies", 
"Philosophiæ Naturalis Principia Mathematica", 
"Disquisitiones Arithmeticae"];

function addBook (book) {
     bookList.push(book)
} 

addBook('Critique of Pure Reason')

console.log(bookList) /* output: The Hound of the Baskervilles,
On The Electrodynamics of Moving Bodies,
Philosophiæ Naturalis Principia Mathematica,
Disquisitiones Arithmeticae,Critique of Pure Reason */

The simplest question would be, what if you want to reuse bookList the way it was before?

In this case, bookList is not reusable anymore.

Also, the good thing in making functions that do not change external data is that it will be easier for you to trace bugs, knowing the fact that your functions will not be responsible for any changes in external data.

And finally, it’s important to note that addBook() function in the previous example, will not be reusable too because it only depends on bookList array. The solution is to allow the function to receive 2 arguments (The array in question and the name of the book) and 2 parameters (2 placeholders / variables representing them) => The challenge for this is here: Pass Arguments to Avoid External Dependence in a Function.

1 Like

It’s much easier to reason about and consequently you’re less likely to make errors.

1 Like