JavaScript scope

A scope can be defined as the region of the execution, a region where the expressions and values can be referenced.

There are two scopes in JavaScript that are global and local:

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

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

In the function’s body, the precedence of the local variable is more than the global variable with the same name. If the name of the function’s local variable is same as the name of the global variable, then the local variable hides the global variable.

Example1

In this example, we are declaring two variables one variable has a global scope, and the second variable has local scope. Both of the variables are declared with the same name.

In the output, we can see that the variable with locally scoped overrides the value of the global variable.

<!DOCTYPE html>   

<html>  

<head>   

</head>  

<body>  

<script>  

var $var12 = 200;     

    

function example() {      

    var $var12 = 300;     

    document.write("Inside example() function = " + $var12);     

}     

document.write("Outside example() function = "  + $var12);    

document.write("<br>");  

example();   

</script>  

  

</body>  

</html>

Output

JavaScript scope

When we declare a variable inside a function without using the var keyword, it acts as a global variable. Let’s see an illustration of the same.

Example2

In this example, we are declaring a variable inside the function without using any variable declaration keyword. Then we are accessing the corresponding variable outside the function.

In the output, we can see that there is no error is generating related to the undefined variable. The code is successfully executed without generating any error.

<!DOCTYPE html>   

<html>  

<head>   

</head>  

<body>  

<script>  

function example() {      

    $var12 = 300;     

    document.write("Inside example() function = " + $var12);     

}     

example();   

document.write("<br>");  

document.write("Outside example() function = "  + $var12);    

</script>  

  

</body>  

</html>

Output

JavaScript scope

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.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *