Basic JavaScript - Global Scope and Functions

Tell us what’s happening:
Describe your issue in detail here.

Hello, my concerns are about the oopsGlobal variable. We in the instructions are explicitly pointing to assign a value to this variable without any of the keywords to initialize the variable, but nor in the code or in the lesson’s description is not specified that the variable is initialized. I have opened a code sandbox and the following code

function func() {
    variable = 5;
}

console.log(func());

Results in an error: ReferenceError - variable is not defined

  **Your code so far**
// Declare the myGlobal variable below this line
const 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);
}
  **Your browser information:**

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36

Challenge: Basic JavaScript - Global Scope and Functions

Link to the challenge:

Good catch.

If you open the browser console and type:

function func() {
    variable = 5;
}

func()
console.log(variable)

It will run. In node JS as well.

But if the code, at least in node js (edit: also in the browser, exactly as you are seeing there. Test by using the code below in the console as well), is written this way:

"use strict"

function func() {
    variable = 5;
}
func()
console.log(variable)

Then it won’t run.

So I suspect it is because of “use strict”

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