I cannot increment a global variable in function parameter

Asked

Viewed 511 times

1

What was asked of me:

  • Declare a global variable called counter and assign it 0.
  • Declare a Function called incrementCounterBy, which receives a Parameter called amount. It should increment counter by the amount.
  • Declare a Function called resetCounter that should set the counter value back to 0.
  • Test your counter and have some fun.

And my code is like this:

var counter = 0;

var incrementCounterBy = function (amount) {    
counter++;
};


var resetCounter = function () {
    setCounter= 0;
};

When I try to run the code I get the error:

Code is incorrect Make sure you are incrementing the counter by amount

  • What is asked is not: counter++; BUT YES counter += amount;.

  • Ahh as n saw it earlier? how frustrating n know to interpret well what is asked! Anyway, thank you very much!

1 answer

0


In fact it’s wrong, because counter++ increases the value of counter in 1. But you should not increase by 1, but use the amount that was reported in the function.

And in function resetCounter you are assigning the value in the variable setCounter, and not in the counter:

var counter = 0;

function incrementCounterBy(amount) {
    counter += amount;
}

function resetCounter() {
    counter = 0;
}

incrementCounterBy(2);
console.log(counter); // 2
incrementCounterBy(5);
console.log(counter); // 7

resetCounter();
console.log(counter); // 0
incrementCounterBy(3);
console.log(counter); // 3

Notice also that I have declared the functions as function nome() {...} instead of var nome = function() {...} (to learn more about the difference, see here).

  • 1

    THANK YOU FOR THE CLARIFICATION and thank you for sharing the link too!!! for some reason the functions only accept if you take the name var = Function() {...} I changed this and gave it right,

Browser other questions tagged

You are not signed in. Login or sign up in order to post.