Lets Talk “Scope” In Javascript
So I kept coming across the word “scope” each time I read most tech blogs but never really knew what it meant or bothered to research it, life of a lazy developer, expecting to learn everything on twitter lol. Not until last night when I decided to do some research on what global and local scope in javascript meant.
As simple as it may seem to most developers, there are little things we understand in Javascript but not so deeply. This concept is what drives the use of modules in our JS files when building applications like being able to require, export modules etc. So, a global scope in JS is a variable declared outside of a function, this means it is accessible from anywhere and its state can be changed. A local scope is dependent to the function it is declared, I will explain that:
var func = “Trying to explain scope”;The about declaration with the ‘func’ variable in particular is said to exist in the global scope of things, its state can be accessed and updated from anywhere since it exists globally. I can therefore do this:
function alter() {
var func = "On our way to understanding scope";
console.log(func);};
By the above, we have updated the state of the func variable inside our function because it exists globally when we first declared it. Now moving to local scope, this is what you really cant do:
function alter() {
var sauce = "local champion";
console.log(sauce);};
//And then try to change it below:var sauce = "Please change me";
At this point, the sauce variable exists only within the scope of the function “alter”, trying to change its state will print out an error. The sauce variable that exists locally is inaccessible, access not granted, disengaged(pun intended) from everything outside the “alter” function.
There you have it, sounds simple but a fundamental principle on which Javascript is built. Please like, share, comment if you enjoyed the article.