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?
cin the outer scope, hence its value is read from the outer scope. If you'd declared it in the function (var c = 2;), that variable would be local to the function, independent of the outer scope variable with the same name.var con the same line with the definition= 1. There are two definitionsc = 1andc = 2. c is declared only once In this script. To make the inner c only be 2 in the inner scope, you need to changec = 2;tovar c = 2;Toshadowthe outer c.