Before I say what im confused about i want to say i understand already about how var uses hoisting.
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?
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
When you use a variable without declaring it with
const then it becomes a true global variable. So assigning
oopsGlobal without using
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
const to declare it.
If you use
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
In the real world, you would never declare a variable without using either
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
var). Basically, strict mode makes it impossible to accidentally declare a global variable.
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.