info@enlightsolution.com           01710-318199           9:00AM - 6:00PM

  • Home
  • Services
    • Custom Software Development
    • Web Application
    • Mobile Application
  • Products
    • Enlight Business Solutions
    • Enlight Accounting
    • Enlight HR & Payroll
    • Enlight POS
    • Asset Management System
  • Portfolio
  • Insights
  • About Us
  • Career
  • Contact US

Closure in JavaScript

Closure in JavaScript

by Admin / Monday, 20 May 2019 / Published in Uncategorized

Closure:

A closure is a feature in JavaScript where an inner function has access to the outer (enclosing) function’s variables. Whenever a function is called, a new scope is created for that call. The local variable declared inside the function belongs to that scope; they can only be accessed from that function.

Example:

function add(n) {

var b = n;

function result(m) {

var a = m;

return a+b;

}

return result;

}

var x=add(2);

console.log(x(3));

Output: 5

 

Here we have two functions.

  1. add() creates a local variable called b and returns the result() function.
  2. The result() function is an inner function that is defined inside add() and is only available within the body of the add() function. Note that the result() function has local variable a.

However, since inner functions have access to the variables of outer functions, result() can access the variable b declared in the parent function, add(). If result() were to have its own b local variable, it would use this instead. The result() function return sum of the a and b value.

In our example, the result() function had preserved the value of b when the add() function was executed, and continued to preserve (closure) it.

About Admin

What you can read next

Prototypes in JavaScript
Higher Order Function in JavaScript

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

ENLIGHT SOLUTIONS

Enlight Solutions is working with Leading software development system. We provide out clients nice and fluent software solutions in minimum amount of time.

Quick Links

  • About Us
  • Products
  • Services
  • Portfolio
  • Blog
  • Career

All right reserved.
ENLIGHT SOLUTIONS @ 2019

  • Home
  • contact us
TOP