Coder Social home page Coder Social logo

javascript's Introduction

JavaScript

Closures

Closure is another important concept in JavaScript and understanding this can be really helpful while building JavaScript applictions. A closure is a combination of a function bundled together with references to its surrounding state (lexical environment). That is, a closure gives you access to an outer function’s scope from an inner function. All this might sound a bit confusing but it is better understood as you read further.

Now we'll look at an example where we will actually see how these closures may be helpful. Take a simple example of implementing a counter function. It can be implemented easily by running the following code.

var count = 0;//Global Variable
function counter(){
  count = count + 1;
  return count;
}
console.log(counter()) //outputs 1
console.log(counter()) //outputs 2

It seems to work perfectly and is pretty straight forward. Well, although this might work for this small program but if you wish to write a large piece of code with many people contributing and using the same variable counter, you will surely run into a problem.

The other possibility is using a local variable.

function counter(){
  var count = 0;//local variable
  count = count + 1;
  return count;
}

In this case if you run console.log(counter()) you will see that it always outputs 1. This is because our variable is always reassigned to 0 whenever we call the function.

Thats where closures come in.

We define the function in the following manner

function makeCounter() {
  var count = 0;
  function counter() {
  count = count + 1;
  return count;
}
  return counter;
}

Then we run the following commands

var doCount = makeCounter();
console.log(doCount());//outputs 1
console.log(doCount());//outputs 2

At first glance, it may not seem obvious that this code still works. In some programming languages, the local variables within a function exist only for the duration of that function's execution. So after makeCounter() is called the variable named count can get destroyed and may no longer be accessible. But in Javascript that's not the case.

This is beacause functions in JavaScript form closures (functions along with the lexical environment). This environment consists of any local variables that were in-scope at the time that the closure was created.

In this case when we call makeCounter, it creates a counter function and returns it along with an environment containing the free variable 'count' (actual reference to the count variable, not a copy). In other words, it creates a closure. The function returned from makeCounter is stored in doCount. So whenever we call doCount it looks for a variable named count in the lexical environment and retrieves its value.

So this is what basically a closure is. However there are many applications of closures and if you are interested you can read further in the documentation

javascript's People

Contributors

paramansh avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.