0

After looking around, I'm still not too clear on this.

function() {
    var a = 'foo';
    a = 'bar';
}

I'm attempting to update the value of a variable here. Since the variable is already declared with "var", does my second line only update the variable, or does it also make it global?

1
  • No, it will just update the variable value. Commented Feb 13, 2014 at 7:39

4 Answers 4

3

It only updates the variable.

One use of var, anywhere in the function, will declare it to be a local variable.

Sign up to request clarification or add additional context in comments.

Comments

2

When you assing a value to a variable javascript will check if that variable is defined within the current block/scope.

If yes then it will update that variable. If no then it will check its parent block. and this goes on until it finds a variable declared in the global space.

In your case it will update the var a inside your function.

If no variable is found in the global space it will create a new one and thus pollutes the global namespace.

1 Comment

Thank you - this gave me the answer but also gave me an idea on why it works this way :)
1

It will update the variable value, not make it global. To make it global, declare it outside the function:

var a = 'foo';
function() {   
    a = 'bar';
}

Comments

0

Your second variable which is the 'bar' must be the new value now of a. Then, the scope for this is just for this function only and cannot work with other function or an outside call.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.