Home > Software engineering >  var variable reassignment within function
var variable reassignment within function

Time:06-27

I don't understand why a var variable can be reassigned within a function, but the change also applies outside of the function. Why/How?

var c = 1;

function Fn() {
c = 2;
}
Fn();
c; // 2

Why isn't the value 2 limited to the scope of the function? When I write c = 2 within a function, does the javascript engine automatically hoist a new var c outside of the function and assigns it the value undefined, which is then changed to 2 once Fn() is called?

CodePudding user response:

It applies outside the function because, inside the function, you are changing the variable.

You are not creating a new variable that exists only inside the function.


Why isn't the value 2 limited to the scope of the function?

You didn't use var, let, const or any other method to create a variable in the scope of the function.

You are accessing the variable you already created in the wider scope.


When I write c = 2 within a function, does the javascript engine automatically hoist a new var c outside of the function and assigns it the value undefined, which is then changed to 2 once Fn() is called?

No. There isn't a new variable. There is only the c you already created outside the function.

CodePudding user response:

This is a common complaint about javascript. Since you used "Var" it has a global scope, so even though you're within a new function when you use c=2 since it's already defined globally it's changed globally. Using "Let" helps define things local to the function and "const" defines globals as constants so they cannot be changed. This issue is particularly fun when you have two global variables with the same name in different JavaScript files and then reference both files to be used on a page. Globals should be used with caution.

  • Related