Variable Scope
Scope in JavaScript refers to the set of functions and variables that are available for use. Learn where variables and functions are available and how the JavaScript engine gives us the values we need.
Overview
The concept of scope refers to the availability of variables in our code. Can we use a variable in a function if it was created in another function? If a function contains another function, can they access each other’s variables? These questions are simple, but also a source of great confusion to those without an understanding of what’s going on. Let’s jump right in.
There are two types of scope in JavaScript: global scope and function scope.
Global Scope
When we start writing code in a file, we are automatically placed in the global scope of that file. When we declare variables in the file, we place them in the global scope.
var x = 5;var y = 'abc';function fn() {};
At this point, x
, y
, and fn
are all available in the global scope. This is the highest scope available to us. Anything in the global scope can be accessed anywhere in the file.
Local Scope
Functions have their own local scope available to them. This local scope can be thought of as being nested inside the global scope.
var x = 5;var y = 'abc';function fn() {var insideFnScope = true;};
Inner scopes have access to their outer scopes. This means that while inside the function fn
, we can access the variables x
and y
...