Not always global?

Before I say what im confused about i want to say i understand already about how var uses hoisting.
Link: global-scope-and-functions

What im confused about here is when we add oopsGlobal = 5 to fun1 the code works.

However if you instead add var oopsGlobal = 5 to fun1 it doesnt work.
Why is it?
Are the var keywords not removed at the start of the script for doping with how javascript adds the declarations to all var variables at the top?
What happens with adding var oopsGlobal = 5 not make fun2 see it?

It appears by adding it, it makes oopsGlobal null

When you use a variable without declaring it with var, let, or const then it becomes a true global variable. So assigning 5 to oopsGlobal without using var, let, or const makes it a global, even when you do this inside a function. That’s why the name of the variable is oopsGlobal, because you accidentally made it a global variable by not using var, let, or const to declare it.

If you use var, let, or const to declare a variable inside a function then the variable has function scope, which means it is only valid inside of the function. That’s why var oopsGlobal = 5 causes the challenge to fail, since you used var then it can only be used inside the fun1 function and so it is not defined in fun2.

In the real world, you would never declare a variable without using either let or const (no one uses var any more). And you would almost always use strict mode, which will throw an error if you try to use a variable that hasn’t been declared with let or const (or var). Basically, strict mode makes it impossible to accidentally declare a global variable.

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.