Search code examples
javascriptincrement

Increment a variable in Javascript


I am trying to increment a variable using Javascript, but I am not quite understanding what I am doing wrong. What do I need to change?

function init(){
    var a = 0;
}

function repeat(){
    a = a+1;
}

Solution

  • Do you want this ?

    var a;
    function init(){
        a = 0;
    }
    function repeat(){
        a = a+1;
    }
    

    If a is declared in a function, it's not available outside this function.

    See the MDN on var :

    The scope of a variable declared with var is the enclosing function or, for variables declared outside a function, the global scope (which is bound to the global object).