“Scope” in a nutshell

Andrew Park
3 min readApr 25, 2021

--

Scope can be quite confusing for new developers, and I still make mistakes when referencing variables outside the scope.

In the below code, variable currentYear is declared within Global scope, and it is available for use everywhere:

In the below code, variable currentYear is used within function whatIsCurrentYear even though it was declared outside the function. As I mentioned above, Global variables can be accessed everywhere.

However, in the below code, variable currentMonth was declared within a function scope, and it cannot be accessed outside the function.

Variable declared within a function scope can be only used within the function scope. In the below code, function whatIsCurrentYear has access to both currentYear and currentMonth:

Here, within function whatIsCurrentYear, another variable with same name currentYear was declared. So, the function whatIsCurrentYear has access to both currentYear variables (one in Global scope and another in function scope). In this case function whatIsCurrentYear will use the variable that is in function scope. If the function cannot find the variable within its scope, then it will look for the variable within its parent scope.

In the below code, function whatIsCurrentYear contains a child function week. Invoking whatIsCurrentYear() invokes child function week(). As expected, function week can access all of the variables.

In the below code, another child function day was added within function whatIsCurrentYear. Even though function day() was invoked within function week(), function day() does not have access to variable currentWeek (declared with function week) since currentWeek is defined within sibling, not parent.

If the variable currentWeek was declared within function day, or within parent function whatIsCurrentYear, or within Global scope, function day will have access to all variables:

Just remember that scope will only “look up” to search for variables.

--

--

No responses yet