Continuing from the last post. We didn't alter the global variable value, but the function
incrementer
would not work without the global variablefixedValue
being there.Another principle of functional programming is to always declare your dependencies explicitly. This means if a function depends on a variable or object being present, then pass that variable or object directly into the function as an argument.
There are several good consequences from this principle. The function is easier to test, you know exactly what input it takes, and it won't depend on anything else in your program. This can give you more confidence when you alter, remove, or add new code. You would know what you can or cannot change and you can see where the potential traps are.
Finally, the function would always produce the same output for the same set of inputs, no matter what part of the code executes it.
Let's update the
incrementer
function to clearly declare its dependencies. Let's write theincrementer
function so it takes an argument, and then returns a result after increasing the value by one.
var fixedValue = 4;
function incrementer () {
};
- Answer:
var fixedValue = 4;
function incrementer (num) {
return num + 1;
};
console.log(incrementer(5));
- The function
incrementer
did not change the value of fixedValue and the function also took an argmentnum
.
Top comments (0)