Summary of “Events in JavaScript”, part 2
Scope
Each function has a scope, which is defined as all of the values that are available to this function.
The scope is limited by the function, which means that you cannot get local variables and function parameters from outside of this scope.
Local variables are variables in which the scope is limited by the function where they are declared. This scope is called local.
Global variables are variables that are declared at the level of the entire program. They can be seen from any block of code. The scope in which they are declared is called global.
If a non-local variable is called inside the function, JavaScript will look for the variable outside the scope, moving progressively up from one level to the next until it finds the desired variable. If the variable cannot be found either inside the function or outside of it, there will be an error.
Since the function can use variables that are declared outside of its scope, they can be redefined.
var food = 'pasta';
var eatDinner = function () {
console.log('I ate ' + food);
};
eatDinner();
// Outputs: I ate pasta.
// We redefine the variable food.
food = 'celery';
eatDinner();
// Outputs: I ate celery.
Redefining variables that are used by the function outside of its scope is not a best practice. When you do this, it can lead to unexpected consequences and errors in the code. You need to use this technique carefully.
Scopes can only be created by functions. Therefore, if a variable was created in another construct, such as in a loop, for example, it will be available to be read from within the function.
Closures
A closure is a function that remembers its surroundings. This is the function + all of the values outside the local scope that it uses.
Closures allow us to record a certain value in the function as well as to use the function itself later.
var collectContainer = function (food) {
return function () {
console.log('I ate ' + food);
};
};
var schoolkid = collectContainer('pasta');
schoolkid();
// Outputs: I ate pasta.
Closures and Asynchrony
Certain functions are performed asynchronously, so the value of the variable may already change at the time the code is executed. In order to avoid this problem, you need to create a separate scope. That way, all of the variables will be under control and the closures will prevent the desired values from being lost.
var thumbnails = document.querySelectorAll('.gallery__photo-preview');
var fullPhoto = document.querySelector('.full-photo');
var addThumbnailClickHandler = function (thumbnail, photo) {
thumbnail.addEventListener('click', function () {
fullPhoto.src = photo;
});
};
for (var i = 0; i < thumbnails.length; i++) {
addThumbnailClickHandler(thumbnails[i], photos[i]);
}
Continue