poor content

not useful

useful

very useful

excellent

Rate

What is a Javascript closure

February 23, 2022

Alireza Ataei

By: Alireza Ataei

What is a Javascript closure

Reading time: min

    Content List

The closure in Javascript can be a bit tricky some times, but in fact it's just a function not unlike normal JS function, but using a global var inside it

They don’t have any difference in appearance, just Javascript functions! the difference between normal Javascript function aka non-closure and a closure, is that the closure uses global variables in the code, while normal/pure function doesn’t.

Which from the memory view point, means that in case of a normal function execution, the arguments of the function are stored in Stack Memory(short lived) and deleted once the function is has fulfilled the job!

But in closure, The use of global var, leads the app to use the Heap Memory(long lived), beside the Stack Memory for arguments, so the closure uses more memory!

But there is a reason that such a thing exists and is popular, right?

The Closure, also causes Data Encapsulation, prevent leaking or exposing data where it’s nor needed. In order to use this feature of closure, you can create an outer function, with a variable inside it, and then create another function inside the primary function and return the function for example.

So what happens here, is that the inner function can access the variables out side of itself, which is inside the outer function, but the outer function, can not use the data inside the inner function, so the data in memory is created, and vanished already

You can also watch this video to have a better understanding

Was this page helpful?

What was the most helpful point of this page for you?

Thanks for your cooperation!

poor content

not useful

useful

very useful

excellent

Comments1

One response to “What is a Javascript closure”

Leave a Reply

Your email address will not be published.