Next page | Contents page |

Global and local variables - scope

If variables (or constants) are declared within a compound statement at the top level of a script (ie, not within a function) they are global. That means they can be used from anywhere else in the script. Unlike C/Java, they do not cease to exist ("go out of scope") when execution leaves that compound statement. Eg,

    var i, j;
    i = ... ;
    x = ... + i ... ;

However, variables declared inside the curly braces forming the body of a function (see later) do only exist within the function. They are said to be local variables and they do go out of scope when the function returns. The system clears them away automatically.

There is a page later (here) about how the rules are different for let and const, compared to var.

Next page | Contents page |