Learn JavaScript Closures in 6 Minutes

Learn JavaScript Closures in 6 Minutes

They're stateful functions.

Closures are notoriously difficult to grasp, yet vital to advancing as a JavaScript developer. Understanding them can lead to more elegant code and better job opportunities.

This is a companion discussion topic for the original entry at https://www.freecodecamp.org/news/learn-javascript-closures-in-n-minutes/

Why are you passing in 500 as an argument to getBalance()? It doesn’t require any parameters.

Great read, it’s always a good thing to get a reminder on closures :slight_smile:
But when you say that all local variables of a function are cleared once its lifecycle is complete " Unless it returns another function.", it can lead to think that closures can be used only if the function returns another function. Even though there are other case where you can leverage closures, for example by declaring an event in the body of a function :slight_smile:

This is the simplest explanation I have read on closures. The concept doesn’t seem so alien anymore. Thanks!

Probably a copy/paste behaviour ¯_(ツ)_/¯

You’re getting Data Privacy wrong. It’s not about security, as much as good API design. A user can still access those “private” variables (nothing client side is really secure) but closures allow you to hide variables that users should not care about. This is paramount in achieving a good API design so your users can use your library easily