My Web Development Blog Posts

JavaScript Scope

Posted: 26/07/18

What is "scope" and how does it work in JavaScript?

When discussing scope in JavaScript what you are talking about is the visibility of the variables throughout your code. This is an important concept as it affects which variables are able to be used in what part of your code. An analogy which may help explain the operation of scope in JavaScript would be to imagine a series of one-way mirrors lined up in a row. The global scope is the outermost layer of these mirrors and faces the reflective side so it can only see itself, as you step down into the local scopes contained within it, it is like you are stepping in between mirrors further down this chain. Looking back towards the global scope you are peering through the clear side of the mirror and can see any local scopes between yourself and the global however if you were to look further down the chain those scopes would not be visible to you. The term for this type of scope is "lexical scoping".

An advantage of scope working in this way is that it provides some isolation between your functions, variables that are declared within a function are local to that function and additionally each time that function is called a new instance of those variables is created. This is a useful property as when you are building functions to be reusable throughout your code you don't have to be concerned of conflicts between your variable values. If a local scope does reuse the same variable name as one declared in the global scope it is the local scope variable which trumps the global scope variable.