Pass Arguments to Avoid External Dependence in a Function explain

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:


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.


Actually, the line above will return the number 5. The right side of the = operator is evaluated first, so fixedValue + 1 becomes 5 and then is assigned to fixedValue and then returned.

However, it much simpler to write it as return fixedValue + 1 as you pointed out in your post.


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


it worked with me …


It does not modify the global var. If it did, the console.log(fixedValue) would display 5 instead of the original global value of 4.

Now if you wrote the code as:

function incrementer () {
  return fixedValue = fixedValue + 1;

and did not pass in fixedValue to the function, then you would be modifying the global variable fixedValue.

Note: In JavaScript, primitives like numbers and strings are passed by value and not by reference like arrays and object.