1

I'm reading a chapter of a book dealing with closures and scoping.

Let's start from two examples (I copy them from the book). Consider the following code:

var scope = "global space";
function checkscope(){
  var scope ="local scope";
  function f() { return scope; }
  return f();
}
checkscope();

here the value that we obtain calling checkscope() function is "local scope".

Now, consider this function:

var scope = "global space";
function checkscope(){
  var scope ="local scope";
  function f() { return scope; }
  return f;
}
checkscope()();

It seems similar but it isn't, we have return f rather than return f() inside checkscope function and checkscope itself is called at the end with two pairs of parentheses rather than one couple.

Could you help me to understand these two variations? I don't understand why f function is called without parentheses: it's a function, if you want to call it you need to use the parentheses, I guess. Then, about checkscope function, why all those parentheses?

3 Answers 3

2

I don't understand why f function is called without parentheses: it's a function, if you want to call it you need to use the parentheses, I guess. Then, about checkscope function, why all those parentheses?

It is not called without parenthesis. In JavaScript, functions are first-class values, and you can just refer to them and return them as objects, without calling them. This is what happens here. Calling checkscope does return a function which you then have to call for accessing scope:

var ref_to_f = checkscope(); // the function f() { return scope; }
ref_to_f(); // "local scope"

This is what actually makes closures interesting - you can call a function that has access to a different scope than you (the caller) have.

Sign up to request clarification or add additional context in comments.

Comments

0

Inside the variation of checkscope, you see this:

return f;

It is returning the actual function object; it is not calling the function. In JavaScript, functions are objects just like any other object, like a string.

If you paste this code into the console, and type checkscope(), you will see the return value of function f() { return scope; }. See, it's returning the actual function object, because it's not being called (with ()).

So then, when you do checkscope()(), you are calling checkscope() (which returns a function) and then calling that function that it returns with another ().

Comments

0

In the first example checkscope returns the result of function f, while in the second it returns a reference to function f which is then called in the global scope: checkscope()(); (note the second pare of parentheses).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.