
JavaScript in Charts (Part 1)
One of the secrets of an effective JavaScript developer is a deep understanding of the semantics of the language. In this article I will explain the basic elementary parts of the language using the most simple and understandable diagrams.
A variable in JavaScript is simply a name that points to a value stored somewhere in memory. These values can be either primitives (strings, integers, Booleans), or objects or functions.
In the following example, we will create four local variables in the scope of the highest level and point them to some primitive values:
Output
=> true

Note that two variables point to the same value in memory. This is because the primitives are immutable and the virtual machine can use one instance of the object for all variable references that point to this value.
In the example above, we checked whether two links point to the same value using the === operator and received a confirmation of true .
The rectangle on the left in the diagram is the top-level external closed scope ( closure scope ). The variables in it - local variables of a higher level, it is important not to confuse them with the properties ( properties ) of the object global / window .
Objects are simply collections of links to other objects and prototypes. The only difference is that you add a prototype chain to access properties that are not in the local object, but in the parent.
Output
=> true

Here we have one object with four properties that the tim variable refers to . We also created a new object that inherits the first and refers to it with the jack variable . After that, we rewrite the two properties in the local object.
Now, if we start looking for the jack.likesJavaScript property , we first find the object that jack points to . Next, we look for the likesJavaScript property . Since it is not there, we look at the parent object and find it there and get the true value to which this property refers.
If you ever wondered why tools like jslint always advise you not to forget to put a var statement before a variable declaration, then this is what happens otherwise:

Note that likesJavaScript is now a property of the global object, instead of being a free variable in an external closed scope. This only matters when you mix multiple scripts. But in real programs, this is exactly what you are going to do, right?
Remember: always put var expressions to keep the variable in the current and child closed scope.
If you need to put something in a global object, do it on purpose using window.woo in the browser or global.woo in node.js
JavaScript is not just a collection of related data structures. It contains executable, called code, known as functions. Functions create related areas of visibility and closure.
A function can be represented as a special object that contains not only properties, but also executable code. Each function has a special property [scope] , which represents the environment in which the function was located at the time of declaration. If the function is returned from another function, then this very link to the environment from where it was returned is “closed” by the new function to “closure”.
In this example, we will create a simple factory method that generates a closure and returns a function.
Output
Cloe the Closure Albert the Awesome

When we call description1 (), the virtual machine looks for the function from this link and executes it. This function searches for a local variable called name and finds it in a closed scope. This factory method is good in that each generated function has its own scope for local variables.
If you want to know more about closures, see in my article why use closure (approx. If you are interested, I will translate this article as well).
Sometimes for reasons of productivity or preferences in the programming style, shared functions are used that allow you to use the same function in different scopes using the this keyword .
Create a couple of objects that share a common function. This function will use pointers to this to show the difference.
Output
Lane the Lambda Fred the Functor undefined Zed the Zetabyte

In this diagram, we see that although Fred.description was assigned to Lane.description , this is just a function reference. Thus, all three links point to one common anonymous function. That’s why I try not to name functions in prototype constructors “methods”, this can lead to confusion about some binding of functions to the constructor and its “class”.
If you want to know more about this , see in my article what is this (approx. If you are interested, I will translate this article as well).
Hope this helps JavaScript learners better understand the semantics of the language. In the past I was both a client developer / designer and a server architect, so I chose a special visual way of explanation.
Original article from Tim Caswell: howtonode.org/object-graphs
From the translator: this is my first article and translation on Habré, the whole cycle of articles seemed very useful to myself. The author has two more parts and many other materials on howtonode.org . If there are inaccuracies or corrections, I will correct it. Not quite sure if the translation closure (closure) and scope (space) are correct, maybe someone has better versions? If it is interesting, I will translate the remaining two parts.
UPD:I corrected the typos, tidied up the code examples and, on the advice of ilya42, replaced the “spaces” with the more correct “scope”.
Links everywhere
A variable in JavaScript is simply a name that points to a value stored somewhere in memory. These values can be either primitives (strings, integers, Booleans), or objects or functions.
Local variables
In the following example, we will create four local variables in the scope of the highest level and point them to some primitive values:
// создадим несколько локальных переменных в области видимости верхнего уровня
var name = "Tim Caswell";
var age = 28;
var isProgrammer = true;
var likesJavaScript = true;
// Проверим, указывают ли две последние переменные на одно и то же примитивное значение
isProgrammer === likesJavaScript;
Output
=> true

Note that two variables point to the same value in memory. This is because the primitives are immutable and the virtual machine can use one instance of the object for all variable references that point to this value.
In the example above, we checked whether two links point to the same value using the === operator and received a confirmation of true .
The rectangle on the left in the diagram is the top-level external closed scope ( closure scope ). The variables in it - local variables of a higher level, it is important not to confuse them with the properties ( properties ) of the object global / window .
Objects and Prototype Chains
Objects are simply collections of links to other objects and prototypes. The only difference is that you add a prototype chain to access properties that are not in the local object, but in the parent.
// Создадим родительский объект
var tim = {
name: "Tim Caswell",
age: 28,
isProgrammer: true,
likesJavaScript: true
}
// Создадим дочерний объект
var jack = Object.create(tim);
// Локально переназначим некоторые свойства
jack.name = "Jack Caswell";
jack.age = 4;
// Теперь поищем какое-нибудь свойство в цепочке прототипов
jack.likesJavaScript;
Output
=> true

Here we have one object with four properties that the tim variable refers to . We also created a new object that inherits the first and refers to it with the jack variable . After that, we rewrite the two properties in the local object.
Now, if we start looking for the jack.likesJavaScript property , we first find the object that jack points to . Next, we look for the likesJavaScript property . Since it is not there, we look at the parent object and find it there and get the true value to which this property refers.
Global object
If you ever wondered why tools like jslint always advise you not to forget to put a var statement before a variable declaration, then this is what happens otherwise:
var name = "Tim Caswell";
var age = 28;
var isProgrammer = true;
// Забываем поставить var
likesJavaScript = true;

Note that likesJavaScript is now a property of the global object, instead of being a free variable in an external closed scope. This only matters when you mix multiple scripts. But in real programs, this is exactly what you are going to do, right?
Remember: always put var expressions to keep the variable in the current and child closed scope.
If you need to put something in a global object, do it on purpose using window.woo in the browser or global.woo in node.js
Functions and Scopes
JavaScript is not just a collection of related data structures. It contains executable, called code, known as functions. Functions create related areas of visibility and closure.
Fault visualization
A function can be represented as a special object that contains not only properties, but also executable code. Each function has a special property [scope] , which represents the environment in which the function was located at the time of declaration. If the function is returned from another function, then this very link to the environment from where it was returned is “closed” by the new function to “closure”.
In this example, we will create a simple factory method that generates a closure and returns a function.
function makeClosure(name) {
return function () {
return name;
};
}
var description1 = makeClosure("Cloe the Closure");
var description2 = makeClosure("Albert the Awesome");
console.log(description1());
console.log(description2());
Output
Cloe the Closure Albert the Awesome

When we call description1 (), the virtual machine looks for the function from this link and executes it. This function searches for a local variable called name and finds it in a closed scope. This factory method is good in that each generated function has its own scope for local variables.
If you want to know more about closures, see in my article why use closure (approx. If you are interested, I will translate this article as well).
Common Functions and this
Sometimes for reasons of productivity or preferences in the programming style, shared functions are used that allow you to use the same function in different scopes using the this keyword .
Create a couple of objects that share a common function. This function will use pointers to this to show the difference.
var Lane = {
name: "Lane the Lambda",
description: function () {
return this.name;
}
};
var description = Lane.description;
var Fred = {
description: Lane.description,
name: "Fred the Functor"
};
// Вызваем функцию из разных областей видимости
console.log(Lane.description());
console.log(Fred.description());
console.log(description());
console.log(description.call({
name: "Zed the Zetabyte"
}));
Output
Lane the Lambda Fred the Functor undefined Zed the Zetabyte

In this diagram, we see that although Fred.description was assigned to Lane.description , this is just a function reference. Thus, all three links point to one common anonymous function. That’s why I try not to name functions in prototype constructors “methods”, this can lead to confusion about some binding of functions to the constructor and its “class”.
If you want to know more about this , see in my article what is this (approx. If you are interested, I will translate this article as well).
Conclusion
Hope this helps JavaScript learners better understand the semantics of the language. In the past I was both a client developer / designer and a server architect, so I chose a special visual way of explanation.
Original article from Tim Caswell: howtonode.org/object-graphs
From the translator: this is my first article and translation on Habré, the whole cycle of articles seemed very useful to myself. The author has two more parts and many other materials on howtonode.org . If there are inaccuracies or corrections, I will correct it. Not quite sure if the translation closure (closure) and scope (space) are correct, maybe someone has better versions? If it is interesting, I will translate the remaining two parts.
UPD:I corrected the typos, tidied up the code examples and, on the advice of ilya42, replaced the “spaces” with the more correct “scope”.