Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Can anyone please explain this Closure concept?

I really ain't able to understand this closure concept. Considering the example below:

function makeAdder(x){

  function add(y){
    return y + x;
  };

  return add;
}
var plusFour = makeAdder(4);
console.log(plusFour(10));  // results 14
console.log(plusFour(40)); // results 44

Questions:

1 - Why the plusFour argument stores its value to the add(y) argument? 2 - Why does ADD can be returned as a value to the makeAdder function?

Thanks in advance!!

3 Answers

In JavaScript functions are object; that means that you can pass them as arguments to another function, assign them to variables, return them from functions, etc. In this case we are returning a function that has access to its parents arguments ("x") and assigning it to our variable plusFour.

var plusFour = makeAdder(4);

it's basically

var plusFour = function add(y) {
   return y + x;
}

And since it remembers the parent arguments, then it will know that x = 4;

Closures are kinda hard to explain so I can't make myself clear but it's basically a function that has access to its parents variables.

Watch this video, I bet Andrew explains it better than I do https://teamtreehouse.com/library/understanding-closures-in-javascript

Jesus, thanks for your help. I understand when you say that the inner function can see its parent argument (x). But i don't understand the (y) argument....

I will also watch your video recommendation. Thanks a lot

There are two common ways to create functions in JavaScript

Function Declarations

function makeAdder(x) {
   function add(y) {
      return x + y;
   }

   return add;
}

and Function Expressions

var makeAdder = function(x) {
   var add = function(y) {
      return x + y;
   }

   return add;
}

Now that we know about function expression, declarations and we know that functions can be returned from other functions

var plusFour = makeAdder(4);

is basically a function expression which value is the function returned from the makeAdder(4) function

var plusFour = function add (y) {
   return 4 + y;
}

it will be something like this. Why? Because makeAdder returns add. To execute a function expression we use the name of the variable that we assigned the function; in this case plusFour(y)

Note: this might not be how Closures work internally but its how I like to picture it myself to understand it.

From Eloquent Javascript...

"A good mental model is to think of the function keyword as “freezing” the code in its body and wrapping it into a package (the function value). So when you read return function(...) {...}, think of it as returning a handle to a piece of computation, frozen for later use."

With this concept of a frozen piece of code in mind, it is important to realize that a closure is a function that "closes over" a local variable. It basically freezes that variable so that it can be used however you need to later on.

With your example...

function makeAdder(x){

  function add(y){
    return y + x;
  };

  return add;
}
var plusFour = makeAdder(4);
console.log(plusFour(10));  // results 14
console.log(plusFour(40)); // results 44

We have a function that is adding two numbers. Lets say that adding four is very important so we have a variable called plusFour that stores a function that that will add four to whatever other number we feed it. plusFour is actually storing this...

var plusFour = function add(y){
    return y + 4;
}

If we also needed to add seven alot, we could do the same thing

var plusSeven = function add(y) {
    return y+7;
}

So closure is a way of storing a local variable that can be used again and again however you need to. Rather than write the same bits of code over and over, a function can be written that does this for us.

function add(x) {
   function add(y) {
        return x+y;
  }
}

In this way, it is somewhat similar to a constructor function however, the reason this is called a closure is because it specifically deals with local variables that will be stored for later change.

Let say you always order the same drink, a cup of coffee with whatever you order at lunch.

function myOrder (drink) {
    function restOfOrder(food) {
        return ("<p>Order my usual " + drink + " and I would like " + food + " to eat. Thanks </p>");
    }
}

Here is the same function as above where math was involved but now, every time you order food your drink is always there...

var herLunchOrder = myOrder(coffee);

so we are really just storing

getSomethingToEat =  function restOfOrder(food) {
        return ("<p>Order my usual " + drink + " and I would like " + food + " to eat. Thanks </p>");
    }

and if someone else comes along and always has a soda you can do the same thing for them.

var hisLunchOrder = myOrder(soda);

Just less coding involved but, can be a useful way to deal with writing the same code over and over.