Get Free Audit

The Scope of Variables in JavaScript

May 16, 2017

497 Yan Strunevskiy

The Scope of Variables in JavaScript

Use strict mode
The “use strict” directive changes code into the mode that adheres to the up-to-date standard. It looks like the line “use strict” or ‘use strict’ and is placed at the beginning of the script:

Besides, the directive is used in functions. In such cases, a strict mode can be executed in function scope. The action “use strict” can’t be possibly canceled. It’s not supported by versions IE9 and older.

Variable visibility
Declaration of variables is processed before script running. Whenever declaration is, it implies that a variable was declared at the beginning of the code, so a variable gets accessible before being declared. So it is called “variable visibility”.

For example:

– global
Magento 1.9

Magento 2.1.5

– local
Magento 1.9

Vlad Yunusov
Partner With Us Let's discuss how to grow your business. Get a Free Quote.
Talk to Vlad

Magento 2.1.5

  • If a variable is declared outside a function, it has a global scope and is accessible for any function.
  • If a variable is assigned a value, but not declared, it has a global scope.
  • If a variable is declared in a function body, it has a local scope and is accessible only inside a function body.

Memory Leaks
A memory leak is a memory that is no longer required by an application, but due to some reasons, it is not returned. JavaScript has its own built-in “garbage collector”.

There are 3 common memory leaks:

  • Accidental global variables

For example,

In this case, the line is the reason for the leak. It is possible to avoid such mistakes by applying the ”use strict” directive at the beginning of JS files. The directive prevents from accidental global variables appearance, as this enables a strict mode of parsing JavaScript.

The example of increased memory consumption relating to global variables is cache. Cache stores data that is repeatedly used. It is necessary to limit them in size. If you do not do this, it can lead to increased memory consumption.

  • Forgotten timers and callbacks

Let’s consider why dangling timers are harmful. While setInterval is enabled, a handler is active as well, so it can’t be cleaned by “garbage collector”, because it is necessary to stop interval and, as a result, dependencies can’t be collected.

  • Out of DOM references

In this case, we make reference to #button in global objects of elements. The button is still in memory and can’t be collected by “garbage collector”.

Vlad Yunusov
Partner With Us Looking for a partner that will help you to grow your business? We are the right company to develop your webstore. Feel free to get in touch with us. We will be happy to discuss your business opportunities and provide you with a Free Quote. Talk to Vlad

Post a new comment

BelVG Newsletter
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
Email *