0

I'm just beginning with JavaScript, but I've searched and read about the js variable scope, and can't figure this out.

I want to be able to set a variable value declared outside any function, within the functions which also contains if-statements. But yet it does not change the global variable. Example:

var counter = 0;
goNext();    

function goNext()
{   
    if(counter = 0)
    {
        counter = 3;
    }
}

alert('I now want counter to be 3! How?');
Jason Aller
  • 3,541
  • 28
  • 38
  • 38

1 Answers1

6

Inside the if you are assigning 0 to counter

if(counter = 0)

The code needs to be

if(counter == 0)

or

if(counter === 0)

Using a tool like JSHint will hlp you find these errors. By pasting your code into the interface, it will show you warnings. When I paste your code into the page it produced:

One warning
6   Expected a conditional expression and instead saw an assignment.
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • 1
    I would recommend `===` as it's generally considered better practice. See here: http://stackoverflow.com/questions/523643/difference-between-and-in-javascript – mayabelle Dec 09 '13 at 16:49