Scope in JavaScript

Scope is the visibility of the variable. By visibility means where you can use the variable.
There are two kind of scopes in JavaScript.

  • Global Scope
  • Local Scope

Global Scope

When you can access the variable from anywhere in the file or every js file included in HTML. To make variable visible globally, you have to declare the variable outside of the function. When the variable's scope is global, you can use the variable outside or inside of the function.


var message = "This is global variable";
function foo(){
    console.log(message);
    //output: "This is global variable"
}
console.log(message);
//output: "This is global variable"
                    

Right now, you don't have to worry about the function. Just look at the fundamentals of the global variable.

Local Scope

When you declare a variable inside the function, then that variable can only be accessed inside the function. That variable has the local scope.


function foo(){
    var message = "This is local variable";
    console.log(message);
    //output: "This is local variable"
}
console.log(message);
//output: undefined
                    

Conclusion

In this section, you learned about the scope in JavaScript, what is local scope and what is global scope.
In next section, you will learn about let vs var in JavaScript.