Click here to Skip to main content
15,896,269 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
function wrapValue(n){
var localVariable = n;

return function () { return localVariable}
}

var wrap1 = wrapValue(5);
var wrap2 = wrapValue(10);

console.log (wrap1());

console.log(wrap2());

What I have tried:

my guess is that wrap1 is a variable.

In the console.log, why do you call it as a function: wrap1()?

why no just wrap1?
Posted
Updated 11-May-16 14:09pm
Comments
Mohibur Rashid 11-May-16 18:37pm    
If you read the function carefully, you will see that wrapValue is returning a function. So wtap1 is a variable which refer to a function.
anaQata 11-May-16 18:48pm    
so a variable which refers to a function is referenced as a function? is it same for other OOP languages (C#, java etc)?
Sergey Alexandrovich Kryukov 11-May-16 19:53pm    
There is no such concept as "call a variable". It's not clear "a variable that references to a function".
—SA
anaQata 11-May-16 22:25pm    
What should be the right term?

1 solution

Please see my comment to the question.

Of course, wrap1 is a variable, but it means nothing. A variable can be a function or non-function. Function is also on object. Let's see.
JavaScript
var wrap1 = wrapValue(5);
means that wrap1 is assigned to some object returned by function wrapValue. So, let's see what this function returns. As you can see, it returns another function. In other words, returned object is a function function object. Unlike other objects, this kind of object supports the operation "call". And the syntax wrap1() is just the syntax call.

The question "why no just wrap1?" simply makes no sense. Both wrap1 and wrap1() are two different expressions; both are correct and return totally different objects: first return the result of the function call, the type if this result is defined by n passed during the call to wrapValue; second returns a parameterless function function object which, in turn, can return the object of the same type. Compare
JavaScript
var myObject = wrap1; // some parameterless function
var myOtherObject = wrap1(); // some object, same as n
// you can call
var someObject = myObject(); // because this is a function object
//someObject will be the same as myOtherObject

Are you getting the idea?

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900