How to free up the memory in JavaScript?

Regardless of the programming language, memory life cycle is pretty much always the same −

  • Allocate the memory you need
  • Use the allocated memory (read, write)
  • Release the allocated memory when it is not needed anymore

The second part is explicit in all languages. Use of allocated memory needs to be done by the developer.

The first and last parts are explicit in low-level languages like C but are mostly implicit in high-level languages like JavaScript.

Hence there is no explicit way to allocate or free up memory in JavaScript. Just initializing objects allocates memory for them. When the variable goes out of scope, it is automatically garbage collected(frees up memory taken by that object.)


function test() {
   // Allocate and use the memory
   let x = {
      name: "John",
      age: 24
   return null;
   // As soon as the method goes out of scope, it is garbage collected
   // and it's memory freed.

The cycle mentioned in the comments is carried out every time the method is called.

Updated on: 19-Sep-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started