Chris Ullyott
Chris Ullyott

Reputation: 423

Redefining a variable in Javascript

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?

Upvotes: 0

Views: 427

Answers (4)

Yoseph
Yoseph

Reputation: 1

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.

Upvotes: 0

Konza
Konza

Reputation: 2163

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.

Upvotes: 2

Janak Prajapati
Janak Prajapati

Reputation: 886

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';
}

Upvotes: 1

Quentin
Quentin

Reputation: 943569

It only updates the variable.

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

Upvotes: 3

Related Questions