Pass Arguments to Avoid External Dependence in a Function explain

i don’t understand this challenge ):


// the global variable
var fixedValue = 4;

// Add your code below this line
function incrementer (fixedValue) {
  
  return fixedValue = fixedValue + 1;
  
  // Add your code above this line
}

var newValue = incrementer(fixedValue); // Should equal 5
console.log(fixedValue); // Should print 4

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/pass-arguments-to-avoid-external-dependence-in-a-function

ok. First you will need to know what is the significance of this line:

var fixedValue = 4;

It defines a global variable. And assigns 4 to it. Global variables can be seen by any code in the current file.

The function ‘incrementer’ can see and access and change fixedValue. But is that a good idea?
Nope. Functions should not change global variables. And they should declare what they need to work clearly preferably through their parameter requirements. If ‘incrementer’ needs the global fixedValue then it should just say so by requiring someone to pass the value to it as a parameter.

So your incrementer says it needs one param “fixedValue” and therefore anyone calling it is going to give it that.

Edit: deleting most of my first response.

1 Like

ah, but probably it doesn’t work because it modifies the global var anyway?

it worked with me …

1 Like

// the global variable
var fixedValue = 4;

// Add your code below this line
function incrementer (val) {
return (fixedValue , 5);

// Add your code above this line
}

var newValue = incrementer(fixedValue); // Should equal 5
console.log(fixedValue); // Should print 4