0

I have this global variable in my javascript code:

var currentcount=0;

Later on I try to update currentcount, and it is enclosed in the following manner:

 function next(){
   ...
    if(userAnswer === myQuestions[overallcount].correctAnswer){
      ...
       var tempcount = currentcount;
        for(tempcount in myQuestions.length-1){
          if(currentdiff<myQuestions[tempcount].difficulty)
            currentcount=tempcount;
        }
      ...
  }

When I output currentcount, it is still 0.

I am simply having trouble understanding what the scope of currentcount is, and why it is not updating in the way I want it to. tempcount does update to whatever currentcount is, but currentcount never updates.

If I do something like:

 function next(){
   ...
    if(userAnswer === myQuestions[overallcount].correctAnswer){
      ...
       var tempcount = currentcount;
       currentcount++;
      ...
    }
  }

currentcount does update, but again, it's not the way I want it to.

Please provide an explanation as to why it is so and if there is a solution to update currentcount in the manner I want it to.

Thank you in advance.

andresc23
  • 25
  • 3
  • 1
    Does this answer your question? [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Jared Smith May 16 '20 at 03:13
  • You should try printing global variable in console within each block of your code and check where it gets loose, afaik it should work with no problem – HYAR7E May 16 '20 at 03:28

1 Answers1

0

Ah, I realized that I was not updating tempcount within the for-loop, Instead, it should've been written at as:

 for(tempcount ; myQuestions.length-1;tempcount++){

Before, it was not updating tempcount, which in turn was not updating currentcount.

Thank you to everyone else who answered though, it was helpful too!

andresc23
  • 25
  • 3