Closures in JavaScript

In JavaScript we can pack a function inside another function. When one function A is inside another function B then function A is called outer function while function A is called inner function and this phenomenon is called a closure.
In closure the in…


This content originally appeared on DEV Community and was authored by Bishnu Prasad Chowdhury

In JavaScript we can pack a function inside another function. When one function A is inside another function B then function A is called outer function while function A is called inner function and this phenomenon is called a closure.
In closure the inner function can have access to the outer function scope.

function B() {
  let x = 7;
  function A() {
     console.log(x);
  }
  return A;
}

var c = B();
c();

>7
Enter fullscreen mode Exit fullscreen mode

Closures are used to make private function or variables that has limited access. The outer function of a closure cannot access the inner function scope so it can be used to hide data.

Apart from this use closure do have drawbacks where as long as closure is running memory cannot be garbage collected resulting to memory leaks. This can be avoided by making them null force fully after the use.


This content originally appeared on DEV Community and was authored by Bishnu Prasad Chowdhury


Print Share Comment Cite Upload Translate Updates
APA

Bishnu Prasad Chowdhury | Sciencx (2021-03-03T16:28:43+00:00) Closures in JavaScript. Retrieved from https://www.scien.cx/2021/03/03/closures-in-javascript/

MLA
" » Closures in JavaScript." Bishnu Prasad Chowdhury | Sciencx - Wednesday March 3, 2021, https://www.scien.cx/2021/03/03/closures-in-javascript/
HARVARD
Bishnu Prasad Chowdhury | Sciencx Wednesday March 3, 2021 » Closures in JavaScript., viewed ,<https://www.scien.cx/2021/03/03/closures-in-javascript/>
VANCOUVER
Bishnu Prasad Chowdhury | Sciencx - » Closures in JavaScript. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/03/03/closures-in-javascript/
CHICAGO
" » Closures in JavaScript." Bishnu Prasad Chowdhury | Sciencx - Accessed . https://www.scien.cx/2021/03/03/closures-in-javascript/
IEEE
" » Closures in JavaScript." Bishnu Prasad Chowdhury | Sciencx [Online]. Available: https://www.scien.cx/2021/03/03/closures-in-javascript/. [Accessed: ]
rf:citation
» Closures in JavaScript | Bishnu Prasad Chowdhury | Sciencx | https://www.scien.cx/2021/03/03/closures-in-javascript/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.