0

I'm working through examples in the ebook "eloquent javascript." On page 51, in the Functions chapter, in the Closure section, there's the following example:

function wrapValue2(n) {

  var localVariable = n; 
    return function() {
       return localVariable; 
  };
}

 var wrap2 = wrapValue2(3);
   console.log(wrap2());

As you can see in the last line of the code above, "console.log(wrap2());," the variable is being called inside of console.log. I was having some trouble re-writing this code until I realized there are parenthesis after the variable! Why would I put parenthesis after a variable?

Don't I only do that after a function?

Is this command using the variable as a function? If so, why?

Is it because the object contained within the variable is a function? That doesn't seem very likely.

Thanks in advance!

Andrew
  • 737
  • 2
  • 8
  • 24

3 Answers3

2

Exactly: those parentheses are used to call wrap2, because it's a function.

You use

var wrap2 = wrapValue2(3);

And the function wrapValue2 returns another function.

So wrap2 is a function.

Oriol
  • 274,082
  • 63
  • 437
  • 513
  • so when I want to call a variable containing a function I must terminate it with "()" this means that javascript treats variables containing functions as though they are functions themselves, correct? Thanks for confirming that for me. – Andrew Feb 19 '15 at 19:44
  • 1
    @AndÚ If you meant if a function declaration and a function expression are same: yes, the behave almost identically (the only difference is that function expressions are hoisted to the top of the scope). See [var functionName = function() {} vs function functionName() {}](http://stackoverflow.com/q/336859/1529630). – Oriol Feb 19 '15 at 19:49
  • I started looking through the many tutorials offered on the thread you linked to in the comment above, useful! Though while reading through the [4th of example of the "Function As Object" section of permandi tutorial](http://www.permadi.com/tutorial/jsFunc/index.htm) I noticed yet another nuance that requires clarification. var ptr=myFunction"A function is referenced inside of a variable without its parenthesis! So, is the rule, then, I use parenthesis when I call a function-containing variable inside of a command, but no parenthesis are needed when defining a function-containing variable? – Andrew Feb 20 '15 at 02:54
0

The function ...

function wrapValue2(n) {
  var localVariable = n; 
    return function() {
       return localVariable; 
  };
}

returns a function (see return function()) ... that will need executed to get the answer.

rfornal
  • 5,072
  • 5
  • 30
  • 42
0

Because wrap2 will be function as at the end wrapValue2 returns a function not a value.

void
  • 36,090
  • 8
  • 62
  • 107