Javascript Scope

The region of the execution, a region where the expressions and values can be referenced, is known as scope.

There are two scopes available in javascript:-


Global scope

In the global scope, the variable can be accessed from any part of the JavaScript code.

Input:-
 <script>  
	   var message = 'Hi there'; 
     document.write(message);
</script>

Output:-

The variable message is global scoped. It can be accessible everywhere in the script.


Local scope

In the local scope, the variable can be accessed within a function where it is declared.

Input:-
 <script>  
	    function say() {
    	var message = 'Hi there';
    	document.write(message);
	    }
     say();
</script>

Output:-

When the JavaScript engine executes the say() function, it creates a function execution context. The variable message that declares inside the say() function is bound to the function execution context of say() function, not the global execution context.

So this variable will have access within the function only, not outside of it.

Input:-
 <script>  
	    function example() {      
         $var12 = 200;     
         document.write("Inside example() function = " + $var12);     
     }     
     example();   
     document.write("<br>");  
     document.write("Outside example() function = "  + $var12);
</script>

Output:-

In the above code, if we use the variable without calling the function, then the variable is undefined, and there is no output will be generated. In this case, the error will generate related to the undefined variable.