Explain what is Global Scope

Can anyone explain what is Global Scope and what it does? (@discobot )

Challenge: Global Scope and Functions
Link to the challenge:

I don’t know too I am confused too if you come to know pls answer mei just know how to do it but I didn’t understand

Scope is the visibility a variable has. There is global scope and local scope.

// first line of a script
var one = 1; // This is global scope

function test(){
	var two = 2; // Local scope,  can only be used within this function
	one = one + two; // One is now 3
}

function anotherTest(){
	var three = 3; // Local scope, can only be used within this function
	three = one + three;  // Three is now 4
    three = two + three;  // Error, two is not defined	
}

one = one + two; // error, two is not defined

In the example above the variable one is global scope and can be used and modified everywhere in your code in the current document.
The variable two and three are local scope and can only be used and modified inside the function in which they are declared.


Do note that top-level and global can be seen as two different things.

I guess there is nothing wrong with referring to a top-level variable as global, but when I hear global I tend to think of an identifier on some global object.

In the browser console:

var global = "on window"
window.global
// "on window"

let notGlobal = "not on window"
window.notGlobal
// undefined

MDN: let

Just like const the let does not create properties of the window object when declared globally (in the top-most scope).

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