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.

Test it Now

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.

Test it Now

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.


Next TopicJavaScript scroll




Contact US

Email:[email protected]

JavaScript scope
10/30