When using named functions in the global scope as callbacks, the area in which the function is named can lead to the function being stored in memory and preventing its garbage collection. This is one of many ways to cause a memory leak in your application. Anonymous functions, on the other hand, are flagged for the GC immediately after they are completed, and anything that has not been returned (there may also be a closure) will be automatically flagged for garbage collection.
Consider a rather complicated jQuery plugin. Before generating and returning the actual object that is the subject of the plugin, you may need to create dozens of variables that contain temporary state data. If this was not done in IIFE (immediately called a functional expression: an anonymous function that immediately executes), this variable "seeps" into the global scope. JavaScript data remains in memory if there is any one variable or closure that still references it. Since these variables βleakedβ to the global scope, they will remain in memory until this tab / window is closed. When defined inside IIFE, certain variables get stuck in the area of ββa local anonymous function. Thus, when the function completed execution, the variables are "gone" and their data no longer has references. The JS Engine garbage collector notices that this specific data in memory is no longer mentioned, and marks it for deletion, freeing up occupied memory for other data.
So, if you named your functions and you call them only once, perhaps they uselessly take up memory. If they are anonymous, they will return the memory after execution, reducing the application overhead.
This is essentially a description of how most dynamic languages ββwork, and why they are more popular than static languages ββsuch as C, where you need to track every memory allocation you select and delete them when you no longer need them (exercise itself by itself, deciding how long you need data is not always trivial).
abject_error
source share