Basic JavaScript - Global Scope and Functions

/Tell us what’s happening:
Describe your issue in detail here.
It is given that if variables are declared without let or const , it is automatically created in global scope, my doubt here is that , inside function fun2() when console.log(typeof(oopsGlobal)) is called we get value as number, but when the same is called outside of a function it returns the type of the same variable as “undefined”, why is it happening? Ideally it has to be a global variable right? so typeof(oopsGlobal) has to be number right? why is it returning type as “undefined” when called outside a function?

  **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() {
var output = "";
if (typeof myGlobal != "undefined") {
  output += "myGlobal: " + myGlobal;
}
if (typeof oopsGlobal != "undefined") {
  output += " oopsGlobal: " + oopsGlobal;
}
console.log(typeof(oopsGlobal)); //returns type as number
}
console.log(typeof(oopsGlobal)); //returns type as undefined
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) 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:

In this case, when you declare the variable inside the function, it has a local scope only.
(Whether you use let or var, it will be locally defined only)

Hi, Thanks for your reply, but if it has local scope, then why am I getting the typeof oopsGlobal variable inside of function fun2() returned as number, it should return “undefined” here as well right? as oopsGlobal is only visible inside function fun1() right ?

Because without a keyword the variable is globally defined, hence the name.

EDIT

Also adding on previous comments, well defined variables (with a keyword) can be scoped to a function, but let and const are also block scoped, this means that any variable bw { } is only accessible inside the braces.

Check out any website to learn more about it.

Example:

if("@"){ let universe=true }

universe isn’t accessible from the outside. If you use var instead, it will be.

1 Like

Thanks for your reply! That was informative!

1 Like

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