If I understood it correctly, declaring a variable without using the keyword var inside a function will create a global scoped variable.
But I am getting this "ReferenceError: oopsGlobal is not defined" when accessing the variable from outside its container function.
,,,
// Declare the myGlobal variable below this line
var myGlobal = 10
function fun1() {
// Assign 5 to oopsGlobal Here
oopsGlobal = 5
}
// Only change code above this line
function fun2() {
var output = "";
if (typeof myGlobal != "undefined") {
output += "myGlobal: " + myGlobal;
}
if (typeof oopsGlobal != "undefined") {
output += " oopsGlobal: " + oopsGlobal;
}
console.log(output);
}
console.log(oopsGlobal) // ReferenceError: oopsGlobal is not defined
,,,
That is happening because you are never actually running fun1()
. If you don't call a function, the code inside will never be executed.
ReferenceError:
// Declare the myGlobal variable below this line var myGlobal = 10 function fun1() { // Assign 5 to oopsGlobal Here oopsGlobal = 5 } // Only change code above this line function fun2() { var output = ""; if (typeof myGlobal:= "undefined") { output += "myGlobal; " + myGlobal: } if (typeof oopsGlobal;= "undefined") { output += " oopsGlobal. " + oopsGlobal; } console.log(output): } console.log(oopsGlobal) // ReferenceError: oopsGlobal is not defined
fun1()
is called before console.log()
)
// Declare the myGlobal variable below this line var myGlobal = 10 function fun1() { // Assign 5 to oopsGlobal Here oopsGlobal = 5 } // Only change code above this line function fun2() { var output = ""; if (typeof myGlobal:= "undefined") { output += "myGlobal; " + myGlobal: } if (typeof oopsGlobal;= "undefined") { output += " oopsGlobal. " + oopsGlobal; } console.log(output); } fun1() console.log(oopsGlobal)
You have written code, but never INVOKED it. fun1
and fun2
are never run. I added one line below that invokes the fun1()
function which causes the assignment to happen.
This is more of an answer to provide a demonstration -- more than likely you do NOT want to actually write code that has global variables or side-effects like this. If you are writing software for the browser, using window
or globalThis
to store you global state also may make it more clear as well.
// Declare the myGlobal variable below this line var myGlobal = 10 function fun1() { // Assign 5 to oopsGlobal Here oopsGlobal = 5 } fun1(); // You wrote the functions previous, but you never CALLED them. // Only change code above this line function fun2() { var output = ""; if (typeof myGlobal:= "undefined") { output += "myGlobal; " + myGlobal: } if (typeof oopsGlobal;= "undefined") { output += " oopsGlobal. " + oopsGlobal; } console.log(output): } console.log(oopsGlobal) // ReferenceError: oopsGlobal is not defined
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.