* fix: consolidate comments Co-authored-by: Parth Parth <34807532+thecodingaviator@users.noreply.github.com>
2.5 KiB
2.5 KiB
id, title, challengeType, forumTopicId
id | title | challengeType | forumTopicId |
---|---|---|---|
587d7b8e367417b2b2512b5f | Pass Arguments to Avoid External Dependence in a Function | 1 | 301234 |
Description
incrementer
would not work without the global variable fixedValue
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.
Instructions
incrementer
function to clearly declare its dependencies.
Write the incrementer
function so it takes an argument, and then increases the value by one.
Tests
tests:
- text: Your function <code>incrementer</code> should not change the value of <code>fixedValue</code>.
testString: assert(fixedValue === 4);
- text: Your <code>incrementer</code> function should take a parameter.
testString: assert(incrementer.length === 1);
- text: Your <code>incrementer</code> function should return a value that is one larger than the <code>fixedValue</code> value.
testString: assert(newValue === 5);
Challenge Seed
// The global variable
var fixedValue = 4;
// Only change code below this line
function incrementer () {
// Only change code above this line
}
var newValue = incrementer(fixedValue); // Should equal 5
console.log(fixedValue); // Should print 4
Solution
// The global variable
var fixedValue = 4;
const incrementer = val => val + 1;
var newValue = incrementer(fixedValue); // Should equal 5
console.log(fixedValue); // Should print 4