A scope can be defined as the region of the execution, a region where the expressions and values can be referenced.
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.
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
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.
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
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.