Please Explain - Did not understand anything

Can any explain what is given here. I have seen various explanations on this but did not understand.

  **Your code so far**

// Declare the myGlobal variable below this line


function fun1() {
// Assign 5 to oopsGlobal Here

}

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

Challenge: Global Scope and Functions

Link to the challenge:

Hi @javedk !
At the top , you have to declare a var which is not declared inside a function. Then inside the first function you have to declare another oopsGlobal without using var.

Thank you for the answer. May I know what is the purpose of var and without var and outside the function and inside the function.

You will learn in next challenges.

If it’s still not clear, variable inside a function is called local scope and it works only in that function, and it’s value is preferred by the function instead of the global scope which is declared outside the function .Sorry I am bad at explaining.

Thank you very much. Your response is appreciated.

Declaring a variable outside the function makes it a global variable, meaning you have access to it everywhere in the programme including inside the function. Declaring the variable inside the function means you only have access to it inside the function and nowhere else.

var myGlobal = 5
function check (){
console.log(myGlobal)}
console.log(myGlobal) // prints out 5 since it is also accessible (globally), inside and outside the funciton.

Running this function will print out //5 since the function has access to myGlobal.

However declaring something inside the function like so:

function myPrivate(){
var myPrivateVariable = 10}
console.log(myPrivateVariable)

Will not work since you do not have access to myPrivateVariable. It can only be accessible and used inside the function. This will give an error, as myPrivateVariable is a private variable only accessible to the function myPrivate.

Thank you very much for the answer. I have some understanding now.

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