2 min read

JavaScript Closures

A closure is a function having access to the parent scope, even after the parent function has closed.Closure makes it possible for a function to have "private" variables.
JavaScript Closures

JavaScript variables can belong to the local or global scope.Global variables can be made local (private) with closures.

Global Variables

A function can access all variables defined inside the function but a function can also access variables defined outside the function, like this:

var a = 4;
function myFunction() {
return a * a;
}

Global variables can be used (and changed) by all scripts in the page (and in the window).

A local variable can only be used inside the function where it is defined. It is hidden from other functions and other scripting code.

Global and local variables with the same name are different variables. Modifying one, does not modify the other.

Variables created without a declaration keyword (var, let, or const) are always global, even if they are created inside a function.

JavaScript Closures

Remember self-invoking functions? What does this function do?

Example

var add = (function () {
var counter = 0;
returnfunction () {counter += 1; return counter}
})();

add();
add();
add();

Explained above example

add return self invoking function.The self-invoking function only runs once. It sets the counter to zero (0), and returns a function expression.This way add becomes a function. The "wonderful" part is that it can access the counter in the parent scope.This is called a JavaScript closure. It makes it possible for a function to have "private" variables.The counter is protected by the scope of the anonymous function, and can only be changed using the add function.

https://dmitripavlutin.com/static/955adfa7435c76ac16bfaf9d7d992ac1/da8b6/javascript-closure-2.png
JavaScript Function Closures
https://www.w3schools.com/js/js_function_closures.asp

#JavaScript #Closure #Global #Local #Probyto #Probyto AI

Subscribe and follow us for latest news in Data Science and Machine learning and stay updated!

Facebook: https://facebook.com/probyto
Twitter: https://twitter.com/probyto
LinkedIn: https://linkedin.com/company/probyto
Instagram: https://instagram.com/probyto