DEV Community

Cover image for Understanding Javascript Scope
EmmahNcodes
EmmahNcodes

Posted on

Understanding Javascript Scope

scope overview

What is scope

Scope in javascript refers to rules that guide where variables are stored and how variable look ups(reading variables) happen. We can take scope as a container where whatever details we put in cannot be accessed outside of the container, scope helps us hide details(values) that we don't want to be globally accessible in a file.

Before ES6 the smallest unit of scope was the function scope, we could group javascript scope into global and function scope. The introduction of let and const in ES6 helped introduce a new unit of scope Block scope. Whatever variables we define in the global scope are readily available anywhere in a file, this can easily lead to mistakenly overwriting variable values and sometimes hard to debug errors.

Function scope helped introduced the concept of local scope and hiding implementation details. Variables defined in a local scope are only available within that local scope and when we try to access those variables outside of their scope container, we get a reference error if that variable does not exist in the global scope.
scope presentation

Scopes can be nested, local scopes nested in other local scopes and finally enclosed by the global scope. When reading or assignng values to a variable in a function, the function scope would be checked first to see if that variable exists. In the case of reading a variable value, if it exists in the scope we use that value else the JS engine checks the enclosing scope(i.e goes up by a level), we get a reference error if that variable does not exist in any of the enclosing scopes. If we are not in strict mode and we try assigning a value to a variable that does not exist in the function scope, we go up by a level until we find the variable and if we evntually get to the global scope and still can't find the variable we automatically get one created for us in the global scope, else we get reference error in strict mode.

nested scopes

Conclusion

I'll be writing a continuation of this article to explain block scope with more examples, this was meant to be a very short article that just helped break down javascript scope😅. please let me know if there is anything that confuses you as you read.

Things to note:
var when not used in a function automatically creates a global scope variable.
let and const hijacks scopes and forcefully creates a block scope when used in forloops or other non function blocks.

Top comments (2)

Collapse
 
naucode profile image
Al - Naucode

Hey, that was a nice read, you got my follow, keep writing 😉

Collapse
 
emmahchinonso profile image
EmmahNcodes

Thank you @naubit