JavaScript Scope Examples

The following code shows an example of a global variable:

var x = 10;

function myFunction() {
  // x can be used here because it has global scope
  console.log(x);
}

myFunction();

The following code shows an example of a local variable:

function myFunction() {
  var y = 10;

  // y can only be used here because it has local scope
  console.log(y);
}

myFunction();

		

Task

Run the above code and experiment with the code to get used to it.

JavaScript Scope Summary

Here is a summary of the JavaScript scope that was covered in this chapter:

  • Scope is the region of a JavaScript program where a variable can be referenced.
  • There are two types of scope in JavaScript: global scope and local scope.
  • Variables declared in the global scope are available to all functions and blocks of code in the program.
  • Variables declared in a function are only available to that function.
  • Variables declared in a block of code are only available to that block of code.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT