Get Free Audit

How Do JavaScript Closures Work in Magento 2? (Magento Developer Certification)

Jun 7, 2017

597 Yan Strunevskiy

How Do JavaScript Closures Work in Magento 2? (Magento Developer Certification)

The closure is considered to be the inner function that has access to the variables of the outer function. Every time when executing the outer function, the instance of the inner function containing new references to variables of the outer function is created. Thanks to closure, the inner function remembers all the variables passed to the inner function.

Let’s consider the example of Magento:

Magento 2.1.5 (pub/static/frontend/Magento/luma/en_US/Magento_Catalog/js/compare.js)

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


Another significant point that should be kept in mind is a leak when dealing with closures. Closure saves a marker on contents enclosed. As a result, closure fixing to DOM element can cause circular dependency and, therefore, memory leak. For example:


The closure contains a marker on the element, a and b, even though closure never uses element. Since element contains marker on closure, it creates a cycle that is never removed by the garbage collector.

magento custom development

Magento Custom Development

Take your online store to the next level with BelVG Magento Custom Development

Visit the page
Igor Dragun
Partner With Us Looking for a partner to grow your business? We are the right company to bring your webstore to success. Talk to Igor

2 Comments

Post a new comment

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