The Visual Guide To JavaScript Variable Definitions & Scope | by Ghost | Medium

(for new JavaScript learners)
Hereā€™s a list of my best web development tutorials.
Follow me @ Twitter, Instagram & fb to never miss premium articles.
We often talk about scope differences between var, let and const. But even more often I still see learners struggling with fully grasping the idea of how it all works. I think itā€™s probably because concepts are rarely visualized.
Letā€™s literally ā€” take a look.

Not all scopes are made alike.

Donā€™t memorize scope rules for each type of scope. Try to figure out the reason why it actually works this way. (Variable privacy, for example.)
Letā€™s start with the block scope ā€“ the most basic of them all.
A block scope is just {} brackets. They can be placed anywhere in your program. That doesnā€™t happen often, because usually {} are used together with for-loops, functions, classes, etc. But a plain vanilla scope is still possible:
// Define variable in global scope varvariable = 1;// Check value of hoisted variable that was created in block scope console.log(hoisted); // undefined{ var hoisted = 2; console.log(variable); // 1 }

Block Scope

Simple block scope accessibility rules:
notion imagenotion image
All variables defined in Global Scope become available in all block scopes and can be used there.
Variables defined with var inside a block scope are ā€œhoistedā€ back into the global scopeā€¦ but the actual value is not hoisted only its definition.
When that happens the value becomes undefined.

Function Scope

A trip from global scope into function scope is a one-way street:
notion imagenotion image
Global variables will propagate into the function scope but variables defined inside a function wonā€™t hoist, even if they are defined using var.

Hints Of The Closure Pattern

Functions enable closure pattern because their variables are hidden from global scope but can still be accessed from other function scopes within them:
notion imagenotion image
The idea is to protect variables from global scope but still be able to call the function from it. Weā€™ll take a look at this in greater detail in just a moment.
Protecting variables from outside scope helps reduce bugs in the long run. You may not see it right away. But if you stick with this idea, you will avoid causing bugs in the future that donā€™t really have to happen.

Global Scope

No Difference In Global Scope With so many ā€œdifferences between var, let and constā€ tutorial headlines it is easy to believe that the 3 are completely different. But this isnā€™t always true.
When variables are defined in global scopeā€¦ there is no difference between var, let and const in terms of scope visibility:
notion imagenotion image
They all propagate into inner block-level, function-level and event callback scopes:
Keywords let and const limit variable to the scope in which they were defined:
notion imagenotion image
Variables defined using let and const are not hoisted. Only var is.
In Function Scope
However, when it comes to functions, all variable types, including var remain limited to their scope:
notion imagenotion image
You cannot access variables outside of the function scope in which they were defined regardless of which keyword was used.
Closures
Part of the function closure pattern is a function trapped inside another function. In the next example the inner function returns the counter variable. defined in an outer function. But because add() is a function it never leaks into global scope. You can think of it as a closure container.
The trick? The counter variable is hidden from global scope. But we can still call add() from global scope. In other words counter variable remains privateā€¦ butā€¦ we can access it from global scope as closureā€™s return value.
notion imagenotion image
But just a visual concept wonā€™t be enough here. What does a closure actually look like in code? Basically itā€™s a self-calling function wrapper:
notion imagenotion image
First an anonymous function is created and called at the same time:
(function(){ ā€¦ })();
The second parenthesis in (func(){})() ā† execute the function soon after its defined all in a single JavaScript statement. And there we have it.
Why Are We Doing This?
The plus() function is defined by an anonymous function that executes itself. Inside the scope of plus, another anonymous function is created. It increments a private variable counter and returns the result back to global scope.
Take away: Global Scope cannot access nor modify thecounter variable at any time. The closure pattern allows its inner function to modify the variable without direct access to it from Global Scopeā€¦
The whole point is that Global Scope does not need to know or understand how the code inside add() works. It only cares about receiving the result of add() operation so it can pass it to other functions, etc.
Closures are no longer as popular as they used to be. They were invented in the pre-ES6 era. Their functionality will be replaced in the future when private variables are added to the definitions made with class keyword.
So why did we even bother explaining them?
This is also sometimes called encapsulation ā€” one of the key principles of Object Oriented Programming where inner workings of a class member method are hidden from the environment from which they were called.
This is similar to why let was added to the language. It provides automatic privacy for variables defined within the confines of block-level scope. Variable privacy is a feature you will encounter in many programming languages.
In Local Scope
The let and const keywords conceal variable visibility to the scope in which they were defined and its inner scopes.
Scope visibility differences surface when you start defining variables inside local block-level scope or function-level scope. As we have seen earlier in global scope there is no difference.

In Classes

The class scope is simply a placeholder. Trying to define variables directly in class scope will produce an error:
notion imagenotion image
Here are the proper places for defining local variables and properties.
In classes variables are defined inside its constructor function or its methods and attached to the object via this property:
notion imagenotion image

The this Keyword In Class constructor Function

The this keyword is used to define object properties. Once defined in constructor they become available for access in all class methods via the this keyword (a reference to an instance of that object).

Local Variable Definitions

Local variables can be defined using var, let or const keywords, but they will remain limited to the scope of the constructor or the method in which they were defined, without actually becoming properties of the object.
The constructor and methods are still technically just function scopes.
Hereā€™s how it all might look like in code:
notion imagenotion image
Dissecting a class: constructor and a method meow(). There is only one constructor that creates the instance of the object. But you can have as many methods as you want. Think of methods as actions your class can do.
For a cat it could be: meow(), eat(), drink(), sleep(). Which actions should your class have? It depends on the purpose and type of the object your class defines.
Itā€™s an abstract model. You are the designer of your class. Go crazy.
Note that because felix object was actually created in global scope, you can access it within the class methods (but not in class constructor, because in constructors the instance of the object is still being instantiated.)
But why use felix inside meow() class when we can simply use this keyword to refer to the same thing? It was just an example.

const

The const keyword is distinct from let and var.
It doesnā€™t allow you to re-assign a previously defined variable to a new value:
Itā€™s still possible to change values of a more complex data structure such as Array or objects, even if variable was defined using const. Letā€™s take a look!
const and Arrays Changing a value in the const array is still allowed, you just canā€™t re-assign the object to a different array:
notion imagenotion image
You just canā€™t assign a new value to the original variable name. Once array always array. Or once an object always an object:
const and Object Literals When it comes to object literals, the const only makes the definition constant.
But it doesnā€™t mean you canā€™t change values of the properties assigned to a variable that was defined with const:
notion imagenotion image
Hope this helps someone out there ā€” thanks for reading :-)