Basic JavaScript - Global Scope and Functions - limitation of Automatically Global

Tell us what’s happening:
I tried to add another Automatically Global in this task.
Let say I’ll have carName = "Volvo"; under fun1() or fun2() it won’t work.
I got “ReferenceError: carName is not defined” in the console.

But if I have new Automatically Global in the new function:

function fun3() {
  carName = "Volvo"
}

it works. Is it limitation from JavaScript or limitation from this tool?

Your code so far

const myGlobal = 10;

function fun3() {
// carName = "Volvo" // it works here
}

function fun1() {
  oopsGlobal = 5;
// carName = "Volvo" // it won't work here
}

function fun2() {
// carName = "Volvo" // it won't work here
  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 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36

Challenge: Basic JavaScript - Global Scope and Functions

Link to the challenge:

The tests run in strict mode which doesn’t allow for accidental globals. The identifier oopsGlobal is actually declared behind the scene by the test (in the --before-user-code-- section).

https://github.com/freeCodeCamp/freeCodeCamp/blob/main/curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/global-scope-and-functions.md

1 Like
let carName = "Volvo" // it works here
let carName = "Volvo" // it won't work here
let carName = "Volvo" // it won't work here

if i declare those carName by adding let in front of your lines. it works.
I guess you cannot declare it to be global.

so it is the limitation of this tool, right?
Bcs I don’t have other environment to try.

I wouldn’t call it a limitation, as much as rule enforcement.

The challenge is teaching you about why accidental global variables are bad and the environment in which the code runs is forced to “strict mode” for that very reason (and other rule enforcements).

1 Like

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