Thumb

JavaScript Scope

1/21/2020 2:32:52 AM

In the JavaScript have scope concept, basically JavaScript have two scope concept one is Global scope and another is local scope. Generally global scope access from anywhere and this global scope attach the window property. Global variable accesses the outside of the function as well as inside the function or scope. Local variable only access into the won scope. Scope are defined by the “{}” this symbol. First “{” this symbol is representing the scope start and “}” this symbol is representing the end the scope. It can be function scope, class scope etc. Now given bellow the scope example code and explain the code:

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
<script type="text/javascript">
// Global scope
var globalScope=5;
function myFun(){
  // Local scope
  var localScope=10;
console.log("Access the global scope inside the function: "+globalScope)
console.log("Access the local scope inside the function: "+localScope)
}
//access out side of the sope
console.log("Access the global scope out side the function: "+globalScope)
//can't access out side of the sope
console.log("Access the local scope inside the function: "+localScope)
myFun();
</script>
</body>
</html>     

In this code we show the global variable also local variable. Global variable access from the inside of function scope as well as out of the scope. We know global variable attach the window property so we can access the console window from our web browser. On the other hand, local variables can’t access from outside of the function also this variable can’t attach the window property.