Holden Caulfield
Holden Caulfield

Reputation: 55

Using a global variable in a function in javascript

I want to define a variable (Boolean), and then use it in a function two times. I started with defining a global variable, and then use this variable locally in my function as follows:

var  inpLock = false;
…
function doSomething(inpLock) {
    inpLock = true;
    switch …
        case
        case
    inpLock = false;
}

What happens by running this is: it sets the variable to true but not back to false. If I declare the variable inside the function like: var inpLock it also won’t work. Any help will be appreciated.

Upvotes: 0

Views: 176

Answers (1)

Quentin
Quentin

Reputation: 943211

Giving a name to a function argument (doSomething(inpLock)) declares a local variable of that name.

This masks any global variable with the same name.

Changes you make to the variable inside the function only touch the local variable and ignore the global.

Avoid reusing variable names in nested scopes. It causes confusion.

Upvotes: 1

Related Questions