Local JavaScript Scope

In JavaScript, SCOPE is the set of variables, objects, and functions you have access to. "Scope" is just a technical term for the parts of your code that have access to a variable.

In JavaScript, objects and functions are also variables. JavaScript has function scope: the scope changes inside functions. Variables declared within a JavaScript function, become LOCAL to the function. Local variables have local scope: they can only be accessed within the function.

Back

Just as variables defined within a function are local variables, the variables defined outside a function are called global variables.

In the picture on the left, the scope of the local variable is highlighted blue – it's the function where that var was defined. Any code inside that function can access (read and change) this variable. Any code outside it cannot. It's local, so it's invisible from outside.

Variables defined in the white area are global. Their scope is the entire script. Which means that you can read and change them anywhere in your code.

HTML file: Displayed by browser:
<body>
<p id="demo">First Display Here</p>
<p id="demo1">Second Display Here</p>
<script>
  myFunction();
   document.getElementById("demo").innerHTML =
   "I can display " + typeof carName + " (1st Highlight)";

   function myFunction() {
     var carName = "Volvo"
     document.getElementById("demo1").innerHTML =
     "I can display " + typeof carName + " (2nd Highlight)";

  }
</script>
</body>

First Display Here

Second Display Here

Since local variables are only recognized inside their functions, variables with the same name can be used in different functions. Local variables are created when a function starts, and deleted when the function is completed.

BackTable of ContentsNext