Basic JavaScript - Global Scope and Functions

Tell us what’s happening:
Describe your issue in detail here.
Why you don’t have to put let,var or const before oopsGlobal? it is not declared anywhere.
Your code so far

// Declare the myGlobal variable below this line
let myGlobal=10;

function fun1() {
  // Assign 5 to oopsGlobal here
   oopsGlobal=5;
}

// Only change code above this line

function fun2() {
  let 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 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36

Challenge: Basic JavaScript - Global Scope and Functions

Link to the challenge:

Hi, so in this scenario, the oopsGlobal becomes a new variable that you are declaring within the block. As it is a block scope variable, it is new and would not be found elsewhere in the code - specific to this function only. I hope this helps :slight_smile:

so if i declare it in the function,i dont have to put let or const?i dont understand your explanation.

You should use let or const. This challenge is showing why it’s bad to not declare your variables.

When you do not declare a variable JS tries to be “helpful” by placing it on the global object. Which is just a huge foot gun and not actually helpful.

Open a new browser tab, open the console Shift + Ctrl + J paste the code below.

function createGlobalVariable() {
  oopsGlobal = 5;
}

createGlobalVariable();
console.log(globalThis.oopsGlobal); // 5

Do the same again in strict mode and it will fail (remember to open a new tab).

'use strict'
function createGlobalVariable() {
  oopsGlobal = 5;
}

createGlobalVariable();
console.log(globalThis.oopsGlobal); // Uncaught ReferenceError: oopsGlobal is not defined

Links:

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