Memory Management in JavaScript


Memory management is an essential task when writing a good and effective program in some programming languages. This article will help you to understand different concepts of memory management in JavaScript. In low-level languages like C and C++, programmers should care about the usage of memory in some manual fashion. On the other hand, Javascript automatically allocates memory when objects are created into the environment and also it cleans the memory when an object is destroyed. JavaScript can manage all of these on its own but this does not imply that the developers do not need to worry about the memory management in JavaScript.

Memory management in any programming language involves three important phases, termed as memory life-cycle −

  • Allocating the memory which is required in our program.

  • Utilize the allocated memory unit.

  • After completion, clear the memory block.

Different Strategies to Allocate Memory in JavaScript

Allocating by value initialization

In JavaScript, we do not need to care about allocating memory for simple variables. We can directly assign values to some variables and it will allocate necessary memory on its own.

Syntax

var variable1 = <value>
var variable2 = <value>

Example

For simple allocation by values, see the following example.

Source Code

<head> <title>HTML Console</title> </head> <body> <h3> Output Console </h3> <p> Output: </p> <div id="output"> </div> <div id="opError" style="color : #ff0000"> </div> <script> var content = '' var error = '' var opDiv = document.querySelector('#output') var opErrDiv = document.querySelector('#opError') // actual javascript code try { var number = 52; var st = 'my_string'; var student = { name: 'Smith', roll: 5, age: 23, }; var arr = [15, null, 'another_string']; content += "Allocated memory for number: " + JSON.stringify(number) + '<br>' content += "Allocated memory for string: " + JSON.stringify(st) + '<br>' content += "Allocated memory for student: " + JSON.stringify(student) + '<br>' content += "Allocated memory for array: " + JSON.stringify(arr) + '<br>' } catch (err) { error += err } finally { // display on output console opDiv.innerHTML = content opErrDiv.innerHTML = error } </script> </body> </html>

From the above example, it is clear that numbers and strings are single values, and allocation is also simple. But for objects and arrays, JavaScript can also easily allocate the memory based on their values.

Allocating by Function Call

Like variable value assignment, we can also create some memory blocks by calling some functions. For example, when a function returns a separate object it will automatically assign a new memory block to the system.

Syntax

Memory_reference = <function call which returns any value>

Examples

The following example uses a function that works on an HTML document. So this program will run on a browser or HTML editor.

Source Code

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <script> var e = document.createElement('div'); e.innerHTML = "<h1> Header from JavaScript </h1>" document.body.appendChild(e); </script> </body> </html>

In this example, the JavaScript code is present inside the <script> tag in HTML. Please notice, in this case, initially, the document does not have any <div> block inside <body>. The JavaScript creates a new component by calling createElement(), and then a new div block is created. This block allocates the memory but only when a function is called. After that, the new component is added as a child of the body tag to use this inside the HTML document.

Using previously Allocated Memory in JavaScript

Using previously allocated memory is just reading or writing values from some variables which are assigned previously. We can update its existing value with some other values. See the following example for a better understanding−

Example

Initially allocating memory for a variable, then reading the value from it. Writing a new value and again reading from it.

Source Code

<!DOCTYPE html> <html> <head> <title>HTML Console</title> </head> <body> <h3> Output Console </h3> <p> Output: </p> <div id="output"> </div> <div id="opError" style="color : #ff0000"> </div> <script> var content = '' var error = '' opDiv = document.querySelector('#output') var opErrDiv = document.querySelector('#opError') // actual javascript code try { var a = 52; // allocate memory content += "Reading value of variable a: " + JSON.stringify(a) + '<br>' a = 100 content += "Reading value of variable a: " + JSON.stringify(a) + '<br>' } catch (err) { error += err } finally { // display on output console opDiv.innerHTML = content opErrDiv.innerHTML = error } </script> </body> </html>

Deallocating memory blocks in JavaScript

When our purpose is served, we can remove the allocated memory block. In some low-level languages, this is a necessary step, otherwise, it may occupy memory spaces over time and the total system may crash. JavaScript also has native support of Garbage Collector, which cleans unnecessary memory blocks and cleans up the memory. But sometimes the compiler cannot understand whether a block will be used in later cases or not. In such cases, the Garbage Collector does not clean up that memory. To manually remove allocated locations, we can use the ‘delete’ keyword before the variable name.

Syntax

delete <variable_name>

The variable must be allocated beforehand, otherwise, it will raise an error while trying to delete that variable. Let us see one example to understand this concept clearly.

Example

Source Code

<!DOCTYPE html> <html> <head> <title>HTML Console</title> </head> <body> <h3> Output Console </h3> <p> Output: </p> <div id="output"> </div> <div id="opError" style="color : #ff0000"> </div> <script> var content = '' var error = '' var opDiv = document.querySelector('#output') var opErrDiv = document.querySelector('#opError') // actual javascript code try { a = "a simple variable"; // allocate memory content += "Reading value of variable a: " + JSON.stringify(a) + '<br>' delete a content += "Reading value of variable a: " + JSON.stringify(a) + '<br>' } catch (err) { error += err } finally { // display on output console opDiv.innerHTML = content opErrDiv.innerHTML = error } </script> </body> </html>

Note − The ‘delete’ keyword will only work when the variable is allocated directly (without using the var or let keyword).

Conclusion

Working with any programming language, the programmer should know the overall concept in depth. Memory management is one of the concerning issues, in which developers should properly manage the memory otherwise it will occupy unnecessary memory blocks and create major problems in the environment. JavaScript provides an additional garbage collector tool that automatically cleans the unused memory blocks. However, we can also deallocate memory by using the ‘delete’ keyword just before the variable name (Assumption: the variables are allocated without using let or var keywords.)

Updated on: 22-Aug-2022

951 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements