JavaScript: Variables & Scope. A Visual Guide.

JavaScript: Variables & Scope. A Visual Guide.
by Janeth Kent Date: 13-05-2019 javascript variables visual guide guide


We often speak of discrepancies between

var, let and const

But more often than not, we still see developers struggling to fully grasp the idea of how everything works.

That's because concepts are rarely visualized.

Let's catch a glimpse.

Not all scopes are identical. Do not memorize scope rules for each type of scope. Try to figure out why this actually works. (e.g. variable privacy.)

Let's begin with the block scope - the most basic of all. Actually only { } brackets form a block scope. They can be placed anywhere in your program. This does not often happen, because usually { } is used for - loops, functions, classes, etc. However, a simple vanilla scope can be:

// Define variable in global scopevar variable = 1;
// Check value of hoisted variable that was created in block scope
console.log(hoisted); // undefined
// Create a block scope
{    var hoisted = 2;    console.log(variable); // 1}

Block Scope

Simple block scope accessibility rules:

 

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:

Global variables will spread into the function scope, but variables defined within a function will not hoist, even if they are defined with var.

Hints Of The Closure Pattern

Functions allow closure patterns because their variables are hidden from the global scope, but can still be accessed from other function scopes within them:

The idea is to protect variables from the global scope, but still, be ready to call the function. In just a moment, we will take a closer look at this. Protecting variables from outside the scope helps to reduce bugs in the long run. You may not see it immediately.

But if you stick to this idea, you will avoid causing bugs in the future that don't really have to happen.

Global Scope

There are no differences in global scope. With too many differences between "var, let and const" tutorial headlines, it is easy to believe that the three are totally different. But that's not always true.

When variables are defined in global scope… there is no difference between var, let and const in terms of scope visibility:

Keywords let and const limit variable to the scope in which they were defined:

 

Variables defined using let and const are not hoisted. 

In Function Scope

Though, all variable types, including var, remain limited to their scope when it comes to functions:

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.

So, what's the trick? The counter variable is hidden from the global scope. But we can still call add() from global scope. In other words, the counter variable remains private. But we can still access it from global scope as closure’s return value.

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:

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 the counter 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, in which the internal functions of a class member method are hidden from the environment from which they were called.

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:

class Cat {
let property = 1; // Unexpected token error
let property = 2; // Unexpected token error
}

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:

The this Keyword In Class constructor Function

The keyword is used to define object properties. Once defined in constructor they become available for access in all class methods via 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:

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:

conts speed_of_light: 186000; //Melis per second
speed_of_light= 1; //Typeerror Assignment to constand variable

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:

conts A = [];
A [0]= "a"; //ok
A = []; //Typeerror Assignment to constand variable

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:

Enjoy reading :-)

 

 

Here's the Original article

Background vector created by blossomstar - www.freepik.com

 
by Janeth Kent Date: 13-05-2019 javascript variables visual guide guide hits : 8180  
 
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN END DEVELOPMENT.

 
 
 

Related Posts

Strings in JavaScript: What they are and how to use them

In this tutorial we are going to explain what strings are and how they are used in JavaScript. The tutorial is intended for people who are learning to program in…

Dates in local format with Javascript

In the articles we have about dates in JavaScript we were missing one about how to create dates in local format with JavaScript. That is to say, being able to…

Formatting hours in Javascript

Continuing with the set of articles that talk about internationalisation elements, like the previous one where we talked about relative dates in JavaScript, we will see in this one how…

Request data with prompt in JavaScript

After having published several articles about how to manipulate arrays and dates, today I will publish a post that some of you will find too basic and others will find…

Relative dates in JavaScript

One of the interesting things about the internationalisation library represented in the Int object is the handling of relative dates in Javascript. This handling allows us to represent a date…

How to access webcam and grab an image using HTML5 and Javascript

We often use webcams to broadcast video in real time via our computer. This broadcast can be viewed, saved and even shared via the Internet. As a rule, we need…

The JavaScript forEach loop

We have already talked about how to handle some of loops  types in Javascript including for, for-in and for-off loops. In the case of today we are going to see how…

What are React Hooks and what problems they solve

Working with React, - and before the release of Hooks in version 16.8 -  there was always the possibility to create components in three different ways based on a number of…

Flattening arrays in JavaScript

When we are handling arrays that are arrays or have multiple dimensions it can be very useful to know how to flatten arrays in JavaScript. That is to say, to…

How to populate an array with random numbers in JavaScript

Some of you might think that what we explained in the article on how to populate an array with numbers, apart from the didactic part, would not have much applicability…

How to populate an array with numbers in JavaScript

Populate an array with numbers in JavaScript The first step is to initialise the array. So today we are going to see a simple way to do it and see how…

Top Javascript Libraries and Frameworks Part 2

What are JavaScript frameworks?   JavaScript frameworks are application frameworks that allow developers to manipulate code to meet their particular needs. Web application development is like building a house. You have the option…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration