0

I am currently trying to perform some simple actions on a variable that I've given the value of zero. First of all, I am declaring a variable and giving it a value (0). Secondly, I am creating a function which is supposed to increment the value of my variable when the function is invoked. This is my code:

var orderCount = 0;

function takeOrder(orderCount) {
return orderCount++;
}

takeOrder(orderCount);
takeOrder(orderCount);

alert(orderCount);

The exptected result of the code snippet above would be "2", since the function is invoked twice and the number 0 therefore should be incremented twice.

I have also tried incrementing the variable "orderCount" with the following code instead of the one posted above:

function takeOrder(orderCount) {
return orderCount + 1;
}

Neither works. What am I doing wrong?

  • Related: [What is the scope of variables in JavaScript?](/q/500431/4642212), [Is JavaScript a pass-by-reference or pass-by-value language?](/q/518000/4642212). – Sebastian Simon Dec 06 '21 at 06:29

3 Answers3

3

Remove orderCount from your parameter list, and don't include it as an argument when calling the function. By specifying it as a parameter, you're shadowing (hiding) the global variable that takeOrder closes over.

var orderCount = 0;

function takeOrder() {
//                 ^----- don't include `orderCount` as a parameter
    return orderCount++;
}

takeOrder(); // <== don't specify it when calling the
takeOrder(); // <== function (though it would just be ignored)

alert(orderCount);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

Couple of facts:

  1. Parameter of the function acts like a function-scoped variable. You can re-assign it, increment it etc. All these changes are gone once function finishes its execution.

  2. Local variables named the same as "global" ones hide the latter inside function body and therefore make all in-function changes isolated from the outside world.

Changing the parameter name will not help either, because the value of the global variable will be placed on the function call stack. In fact, passing any variable is not helpful at all.

Typical solution is to not use parameters at all and make your function change variable in the outside scope directly.

It is, however, possible to emulate passing a "reference" to a variable. If you really want your function to not know the global variable name:

var order = { count: 0 };
var anotherOrder = { count: 0 };
    
function takeOrder(order) {
    order.count++;
}

takeOrder(order); 
takeOrder(order); 
takeOrder(anotherOrder);

console.log("Order:"+order.count);
console.log("Another order:"+anotherOrder.count);
Alex Pakka
  • 9,466
  • 3
  • 45
  • 69
0

Simply call the function without passing the parameter

var orderCount = 0;

function takeOrder() {
  return orderCount++;
}

takeOrder();
takeOrder();

alert(orderCount);
brk
  • 48,835
  • 10
  • 56
  • 78