I'm confused between these two closure functions.
The doSomeMath returns the function without executing it when I assigned it to a variable, test. It will only run the closure function when I do test();
However this is not the case for showName function. As soon as I pass in the values, it calls the closure function right away instead of returning it.
Can someone kindly explain it to me? Thanks.
function showName (firstName, lastName) {
var nameIntro = "Your name is ";
// this inner function has access to the outer function's variables, including the parameter
function makeFullName () {
var full = nameIntro + firstName + " " + lastName;
return full;
}
return makeFullName ();
}
showName ("Michael", "Jackson"); // Your name is Michael Jackson
function doSomeMath(a, b) {
var a = a;
var b = b;
function multiply() {
var result = a * b;
return result;
}
return multiply;
}
var test = doSomeMath(5,10);
test();
These two functions are two different ways of demonstrating how closures work.
You could as easily have done the opposite to achieve the same effect.
function doSomeMath(a, b) {
var a = a;
var b = b;
function multiply() {
var result = a * b;
return result;
}
return multiply();
}
doSomeMath(5,10) //50
In the above code you return the result of invocation of the inner function instead of the function itself. Here, as you can see, multiply has a closure over 5 and 10 and so you get the outcome as 50.
Similarly, try:
function showName (firstName, lastName) {
var nameIntro = "Your name is ";
// this inner function has access to the outer function's variables, including the parameter
function makeFullName () {
var full = nameIntro + firstName + " " + lastName;
return full;
}
return makeFullName;
}
var show = showName ("Michael", "Jackson");
show() //"Your name is Michael Jackson"
The above code returns the inner function instead of its invocation and in turn demonstrates how the inner function, makeFullName has a closure over the nameIntro variable of the outer function.
The other answer provides a concise understanding on closures. To know more read up on closures to understand the above examples better.
I think you are confusing closures and higher order functions.
There is no such concept as manually calling a function. A function must always be called. This does not change if the function is a closure.
In fact one might say that this is the essential power of closures as an abstraction mechanism.
A closure is a function that references elements in its enclosing scope.
This is often referred to as lexical scoping.
The set of elements of the enclosing scope that are referenced by a closure are known as its environment.
A function that does not refer to elements in its enclosing scope can be thought of as a degenerate closure - a closure with an empty environment.
The value returned by a function may be another function but this is purely orthogonal to the notion of closures.
In JavaScript, as in many languages, functions are first class values. This means that they can be stored in variables, passed as arguments, and returned as results.
Consider
var createIncrement = function (incrementBy) {
return function (value) {
return value + incrementBy;
};
};
The function above is higher order, because it returns a function. Incidentally, it is also a closure because it references incrementBy which is declared in an enclosing scope.
The confusion expressed in the framing of your question likely arises from the fact that, in practice, the two features will be used together in even the simplest of JavaScript programs.
Related
Thanks to this question I understand how a function may take two sets of parentheses and how a function may return another function which fires immediately after being returned.
What I do not understand is why this is good to know? How could this be applied to solve a problem?
The example of:
function add(x){
return function(y){
return x + y;
};
}
add(3)(4) === 7; // true
Works fine - sure. But why not just write it like this instead?
function add(a, b) {
return a + b;
}
add(3, 4) === 7; // true
Lets take the same code which you have mentioned.
function add(x) {
return function(y) {
return x + y;
};
}
var adder3 = add(3); //Forming adder3
var op1 = adder3(4) // 7
var op1 = adder3(5) // 9
// Now adder 10:
var adder10 = add(10); //Forming adder3
var op1 = adder10(4) // 14
var op1 = adder10(5) // 15;
Hope you understand!!
Revert me if you need more info on closure.
Your example called as closures
Closures’ Rules and Side Effects
Closures have access to the outer function’s variable even after the outer function returns:
One of the most important and ticklish features with closures is that the inner function still has access to the outer function’s variables even after the outer function has returned. Yep, you read that correctly. When functions in JavaScript execute, they use the same scope chain that was in effect when they were created. This means that even after the outer function has returned, the inner function still has access to the outer function’s variables. Therefore, you can call the inner function later in your program. This example demonstrates:
function celebrityName(firstName) {
var nameIntro = "This celebrity is ";
// this inner function has access to the outer function's variables, including the parameter
function lastName(theLastName) {
return nameIntro + firstName + " " + theLastName;
}
return lastName;
}
var mjName = celebrityName("Michael"); // At this juncture, the celebrityName outer function has returned.
// The closure (lastName) is called here after the outer function has returned above
// Yet, the closure still has access to the outer function's variables and parameter
mjName("Jackson"); // This celebrity is Michael Jackson
Closures store references to the outer function’s variables; they do not store the actual value.
Closures get more interesting when the value of the outer function’s variable changes before the closure is called. And this powerful feature can be harnessed in creative ways, such as this private variables example first demonstrated by Douglas Crockford:
function celebrityID() {
var celebrityID = 999;
// We are returning an object with some inner functions
// All the inner functions have access to the outer function's variables
return {
getID: function() {
// This inner function will return the UPDATED celebrityID variable
// It will return the current value of celebrityID, even after the changeTheID function changes it
return celebrityID;
},
setID: function(theNewID) {
// This inner function will change the outer function's variable anytime
celebrityID = theNewID;
}
}
}
var mjID = celebrityID(); // At this juncture, the celebrityID outer function has returned.
mjID.getID(); // 999
mjID.setID(567); // Changes the outer function's variable
mjID.getID(); // 567: It returns the updated celebrityId variable
Reference site : http://javascriptissexy.com/understand-javascript-closures-with-ease/
Functions which return functions are useful when you want similar functions which depend on some parameters.
A real life example: [].sort can be called with a custom comparator function, but it can make sense to define a comparator function to allow more customizations:
function comparator(options) { // Function which returns a function
return function(a, b, tmp) {
if(options.reverse) tmp = a, a = b, b = tmp;
if(options.map) a = options.map(a), b = options.map(b);
if(options.func) return options.func(a, b);
return a < b ? -1 : (b < a ? 1 : 0);
}
}
Then you can use
[1,11,10,2].sort(comparator({map: String})); // [1, 10, 11, 2]
[1,11,10,2].sort(comparator({reverse: true})); // [11, 10, 2, 1]
[1,11,10,2].sort(comparator({func: Function.prototype})); // [1, 11, 10, 2]
if we require a function in certain state with certain value then we can use it inside another function and return that, so that the return function with certain state can be directly used in different scenario.
you can check out various example on closure.
http://javascriptissexy.com/understand-javascript-closures-with-ease/
If you know the first param is always going to be the same, then it will convenient to have it closure, instead of passing it again and again. For simple programs, it may not make sense. But, for programs which handles repetitive params more often, this technique definitely comes handy.
Other than closures you can also use it for pre-processing as a one time job, consider if you had to do something intensive, e.g. generate a million things;
function generateSessionSecrets(lock) {
var secrets = [], i = 1000000;
while (i-- > 0) {
secrets[i] = Math.random();
}
return function(key, i) {
if (key === lock) return secrets[i];
}
}
var chest = generateSessionSecrets('fizz');
chest('fizz', 0); // e.g. 0.2096199430525303
chest('fizz', 1); // e.g. 0.30329699837602675
// ...
chest('fizz', 0); // still 0.2096199430525303
(This is an example of concept, not an example of real security)
there isn't a point to using it immediately. you would use it to create a function to attach it to an event or use as a callback for an asynchronous function. an example might be such:
function factory(param){
return function(result) {
if (result==param) dosomething();
}
}
$('#domobject').click({
param = $('#domvalue').value;
asynch_function(factory(param));
});
Here I've attached a click event to presumably a button. When it is clicked it will retrieve the value of an input and create a function based on it and call an asynchronous function with the newly created function as it's callback. The asynchronous function might be an ajax request. When the asynchronous function completes the function that factory created, the callback, will be called. It will check the return value the asynchronous function passed to the callback against the param specified when the event was attached.
If we move the dom lookup to inside the callback function, then we wouldn't need factory or param, but then it would use the value that is in the input at the time when the asynch function has returned, rather than when the button was clicked which is later and the value might have changed.
Sometimes, you won't be able to obtain a value you need in the context of the callback for other reasons. Or it might just be that you want to abstract out a class of functions so you don't have to retype a slightly different version of it in all the places you use it.
Is there any way to share code between two closures?
Example:
// ANTIPATTERN
var cbDoThing = function cbDoThing(arg){
return typeof closed1 +" " + arg;
}
function getClosure1(closed1) {
return cbDoThing;
}
function getClosure2(closed1) {
return function(arg) {
// do other work
return cbDoThing(arg);
}
}
f1 = getClosure1();
f1("ARG1"); // returns "undefined ARG1"
f2 = getClosure2();
f2("ARG2"); // returns "undefined ARG2"
Here getClosure1() and getClosure2() return a closure that does similar tasks. I.e. both of them need to execute the cbDoThing() within a closure environment, but getClosure2() runs some other code in addition.
The above example does not work as wanted. cbDoThing() is defined in the global context, so closed1 variable is undefined. The wanted behavior is a pattern to make the closed1 variable be read from the closure scope chain, but without redefining the cbDoThing()function in each closure.
PS: JsFiddle playground.
EDIT:
Now that I asked, an answer came to me with minor modifications:
var cbDoThing = function cbDoThing(closed1, arg){
return closed1 +" " + arg;
}
function getClosure1(closed1) {
return function(arg) {
return cbDoThing(closed1, arg);
}
}
function getClosure2(closed1) {
return function(arg) {
// do other work
return cbDoThing(closed1, arg);
}
}
The cbDoThing does not access closed1 variable from the closure variable scope. Rather it is passed an extra argument. Then this function is called from each of the closures.
JsFiddle
Nice work. Javascript only walks down the prototypal chain, which means that cbDoThing has no reference or declaration of closed1. In this case, cbDoThing has only one prototype - Object. Without explicitly passing an argument to cbDoThing, it will not have any notion of the closed1.
Here is a thorough discussion of closures in javascript: http://jibbering.com/faq/notes/closures/
Refering to How do JavaScript closures work?.
Closure is:
a closure is the local variables for a function — kept alive after the function has returned, or
a closure is a stack-frame which is not deallocated when the function returns (as if a 'stack-frame' were malloc'ed instead of being on the stack!).
Just want to confirm are the following consider closure?
1) Binding javascript function within a function.
var Books = {
init:function(){
$('#box').bind('click',function(){
console.log('click');
});
}
};
Books.init();
2) Declare a function within a function
function sayHello(name) {
var text = 'Hello ' + name;
var sayAlert = function() { alert(text); }
}
var hello = sayHello();
I still can't differentiate which is closure for some times, is that all function within function consider closure or only the one that keep the returned inner function as variable/reference. Example:
function sayHello(name) {
var text = 'Hello ' + name;
var sayAlert = function() { alert(text); }
**return sayAlert;**
}
1 isn't as no variables are actually referenced, 2 and 3 are.
In 2 and 3 the variable called text is closed off - referenced outside its lexical scope. In 1 nothing is.
crockford on closures :
What this means is that an inner function always has access to the
vars and parameters of its outer function, even after the outer
function has returned.
All of those are closures.
I'm not sure what your confusion is.
Is there any way to refer to the function object that you're currently executing in? If it's not a method of any object or not called with .call() or .apply(), the this pointer is likely just window, not the function object.
I often use a design pattern like this for global variables that I want scoped to a particular function as this keeps them out of the top level namespace:
function generateRandom() {
if (!generateRandom.prevNums) {
generateRandom.prevNums = {}; // generateRandom.prevNums is a global variable
}
var random;
do {
random = Math.floor((Math.random() * (99999999 - 10000000 + 1)) + 10000000);
} while (generateRandom.prevNums[random])
generateRandom.prevNums[random] = true;
return(random.toString());
}
But, I'd rather not have to spell out the function name every time I want to use a variable scoped to that object. If the name of the function ever changes, there are then a lot of places to change the name.
Is there any way to get the currently executing function object?
Well, you could use arguments.callee()...
https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/arguments/callee
From MDN:
Description
callee is a property of the arguments object. It can be used to refer
to the currently executing function inside the function body of that
function. This is for example useful when you don't know the name of
this function, which is for example the case with anonymous functions.
Note: You should avoid using arguments.callee() and just give every
function (expression) a name.
BUT...
What you really want are Javascript Prototypes.
function RandomSomethingGenerator()
{
this.prevNums = {};
}
RandomSomethingGenerator.prototype.generate = function() {
var random;
do {
random = Math.floor((Math.random() * (99999999 - 10000000 + 1)) + 10000000);
} while (this.prevNums[random])
this.prevNums[random] = true;
return(random.toString());
};
Why do I say this?
1.) You're dirtying the global space with all those functions.
2.) Even if you like Jani's suggestion, and you want a "static" function like you have now, my suggestion would be the same, but with a twist: Create your global function, and wrap an instance of an object (built from a prototype) inside the closure and make the call to it (so, basically, make yourself a singleton).
As in this (adapted from Jani's answer):
var randomSomething = (function() {
var randomSomethingGenerator = new RandomSomethingGenerator();
return function() {
randomSomethingGenerator.generate();
};
})();
I don't think there's any way to do exactly what you ask, but you could use a closure for your function-local static variables instead.
You can easily achieve this using an IIFE:
var generateRandom = (function() {
//any function's static variables go here
var prevNums = {};
return function() {
//function code goes here
var random;
do {
random = Math....
}
prevNums[random] = true;
return random.toString();
};
})();
You want arguments.callee. From MDN - callee:
callee is a property of the arguments object. It can be used to refer to the currently executing function inside the function body of that function. This is for example useful when you don't know the name of this function, which is for example the case with anonymous functions.
For example:
> foo = function() { console.log(arguments.callee); };
> bar = function() { foo() };
> bar();
function () { console.log(arguments.callee) }
However, I think this is being deprecated. The above link says, "The 5th edition of ECMAScript forbids use of arguments.callee() in strict mode."
function getCtr(){
var i = 0;
return function(){
console.log(++i);
}
}
var ctr = getCtr();
ctr();
ctr();
I've been using Javascript from last five years, but this question made me dumb in last interview. I tried everything to my knowledge but can't figure it out.
Can you please help me with the output and reason for it so that I can be better equipped for future interviews if I have one.
var ctr = getCtr();
This calls getCtr(), which initializes i to 0, and stores a reference to the function
function() {
console.log(++i)
}
in ctr. Because that function was created in the scope of getCtr(), the variable i is still accessible in the scope of the function stored in ctr.
The first call to
ctr()
executes console.log(++i) which has a preincrement on i, so it prints out 1. The second call executes the same code, with the same preincrement, and prints out 2.
DISCLAIMER: Not a javascript developer. Forgive me if I've made an error or used some unpreferred wording.
So the code you posted outputs 1 2. Yet the code:
function getCtr(){
var i = 0;
return function(){
console.log(++i);
}
}
getCtr()();
getCtr()();
outputs only 1 1!
The difference is that if you save a reference to getCtr() by using the var ctr = getCtr();, you create what is called a closure.
So the difference between calling getCtr()() and ctr() is that ctr has i defined in its scope, and that scope is saved thanks to var ctr = getCtr();. Because the reference is saved, the function inside of ctr is able to always act on the same variable.
run this:
var m=0;
var d=0;
alert(m++ +":"+ ++d);
and you get "0:1"
IF it were me asking in an interview, the difference in where the ++ is is what I would be after :)
http://jsfiddle.net/MarkSchultheiss/S5nJk/
Closures
The return statement in that function saves i. So when var i = 0; is only called var ctr = getCtr();. Then ctr becomes the returned function:
function () {
console.log(++i)
}
and the variable ctr has i in the scope of the outer function, getCtr() and the return function is in the scope of getCtr() as well.
okay, getCtr is a function that returns an other function.
It also contains a var called "i" which is set to 0.
"i" is also available in the scope of the returned function.
the preincrement of "i" before logging it to the console causes that it increases by 1 every time the returned function, which is stored in "ctr", is called.
When executed, function getCtr returns an inner anonymous function.
This function is now referenced by variable ctr
Because the anonymous function was created inside getCtr it will have access to getCtr private scope object, which contains variable 'i'. This is known as a closure.
var ctr = getCtr()
Every time the anonymous function is executed it pre-increments i, and writes in in the console.
ctr()
Lets break it down using terms you might know from classical inheritance based OOP languages:
// In javascript functions are first-class objects
// This function is being used like a class would be in Java
function getCtr(){
// You can think of this as a private variable of the getCtr "class"
var i = 0;
// Because it is returned, this is effectively a public method of getCtr
return function(){
// Which increments i and then prints it.
console.log(++i);
}
}
// This makes the variable ctrl an instance of getCtr.
var ctr = getCtr();
// This calls ctr's only public method.
ctr();
ctr();
So the output would be "1, 2".
What this question is meant to do is test if you understand Javascript's prototypal inheritance, ability to have anonymous functions, and closures.
A clarified version of that could that would do the same thing would be:
var myProtoype = function() {
var privateVariable = 0;
var privateMethod = function () {
privateVariable++;
console.log(privateVariable);
}
return {
publicMethod: privateMethod
};
}
var myInstance = new myPrototype();
myInstance.publicMethod();
myInstance.publicMethod();
That function is a Javascript Module. You can have a good reading about it on Javascript: the Good Parts, which is a great book and I highly recommend. A Module uses Javascript closures to create private variables and if assigned to a var the var will retain it's vars each time it's called instead of redefining the vars.
A module works like this
function moduleName(privateVar1){
var privateVar1;
var privateVar2;
return {
exposedFunction1: function (var1) {
// Do stuff... using private vars
return something;
},
exposedFunction2: function (var1, var2) {
// Do stuff...
return something;
}
}
}
var moduleInstance = moduleName(privateVar1);
moduleInstance.exposedFunction(var1);