JavaScript Closures Function

You are Here:

JavaScript Closures Function

In JavaScript, nested functions have access to the outer functions variables.

Closures refer to the existence of variables outside a functions normal execution context.

Disadvantage

Though closures are one of the more powerful (and advanced) areas of JavaScript. It is frequently created by accident and can cause memory leak problems.

More Examples

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p id="point"></p> <script> var x = document.getElementById("point"); function myFunction(){ var txt = "Hello"; function displayText(){ x.innerHTML = txt; } displayText(); } myFunction(); </script> </body> </html>

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p id="point"></p> <script> var x = document.getElementById("point"); function myFunction(){ var txt = "Hello"; function displayText(){ x.innerHTML = txt; } displayText(); } var greet = myFunction(); greet(); </script> </body> </html>

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p id="point"></p> <p id="point1"></p> <script> var x = document.getElementById("point"); var y = document.getElementById("point1"); function myAdder(x){ return function(y){ return x + y; } } var add50 = myAdder(50); var add100 = myAdder(100); x.innerHTML = add50(25); y.innerHTML = add100(25); </script> </body> </html>

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <h2>Change my Styling</h2> <a href="#" onclick="red()">Red</a> <a href="#" onclick="green()">Green</a> <a href="#" onclick="blue()">Blue</a> <script> function myChange(clr, size) { return function() { document.body.style.color = clr; document.body.style.fontSize = size+"px"; }; } var red = myChange("red", 12); var green = myChange("green", 14); var blue = myChange("blue", 16); </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author