Let's say I have this JavaScript closure:
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
and I call add three times:
add();
add();
add();
Now the counter in the self-invoking function is equal to 3. But why will the above not increment counter or keep the parent function's scope alive if the self-invoking function was instead a predefined or even an anonymous function?
By predefined function i mean standard function declaration,something like this:
function testingjsclosure()
{
var counter = 0;
return function(){return counter += 1;}
}
add = testingjsclosure();
There is no self-invoking function here.
The expression
function () { var counter = 0; return ...; }
has as value a function that has local state and returns a certain value. So
var add = (function () { var counter = 0; return ...; })();
calls it and assigns the returned value to add. That value is
function () {return counter += 1;}
which is a function that increments and returns that particular local variable. So calling add calls that function and so increments and returns that particular local variable.
But
add = testingjsclosure();
calls testingjsclosure with no arguments and assigns its return value to add.
function(){ ... } is like quote marks around an expression ... in that that expression is not evaluated until the variable that has the value of the function expression is called.
Whereas
function testingjsclosure() { ...}
is like writing
var testingjsclosure = function() { ...}
Related
I am try to understand why when i call function add() return statement will execute multiply times and var counter=0; just one time ?
document.body.onload=function(){
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
add();
add();
}
Your code consists of three functions:
One function is invoked when body is loaded.
function(){
var add = ...;
add();
add();
}
That function is defining and invoking an unnamed function for assigning its result to variable add. Due to its lack of a name it can't be reinvoked later.
function () {
var counter = 0;
return ...
}
By wrapping this function in (...)() it is invoked instantly.
That anonymous function's result is another function assigned to add in context of first function. Thus, add is now referring to the following function object (which is identical to "being a function" in Javascript):
function () {return counter += 1;}
It is important to see what function is invoked when. According to your excerpt
first function is defined here to be invoked by browser.
second function is invoked as part of invoked function #1.
third function is defined w/o invocation first, but invoked later via its "name" add.
So, what is happening:
The onload-function is invoked as expected.
The defining function (function factory) in second step is invoked once to create a value for add.
add() is using that function's result - the returned function with closure scope access to counter - instead of re-invoking that defining function.
You actually need to get the scopes of either execution right:
I am try to understand why when i call function add() return statement will execute multiply times and var counter=0; just one time ?
The return at beginning of line following var counter = 0; is invoked only once, too. But the return inside function returned by that former return is invoked multiple times.
Over here, I am returning a function which is closed over the 'i' variable, creating a closure.
var myFunc = function(){
var i = 0;
function increment(){
return ++i;
console.log(i);
}
return increment
}
now If I assign this function to other variables like
var newFunc = myFunc();
var newFunc2 = myFunc();
calling any of them will result in
newFunc() // 1
newFunc() // 2
newFunc() // 3
newFunc2() // 1 ??
Where is the value of var i getting stored?
is it getting stored in the execution context of each function so that it can be changed only when we call that specific function.
I saw you define the variable i inside the
myFunc
which means that the scope of the variable i will be within that function. So whenever you call this function, it will create create its own i.
Given the following function:
function countdown() {
var result = "";
// do something with the result variable
return result;
}
How can result variable be updated from within another function, before calling the countdown function?
function something(){
// update private variable "result"
}
function countdown(modifiedResult) {
var result = "";
// do something with the result variable
result = modifiedResult;
return result;
}
function something(modifiedResult){
// update private variable "result"
var updatedResult = countdown(modifiedResult);
alert(updatedResult);
}
something("I am updated value");
The variable result is private, and cannot be accessed from the outside.
One solution is to wrap the whole thing in a factory:
function countdownFactory () {
var result = 0;//since its named countdown i assumed it should be a number
return {
get: function () { return countdown},
set: function (value) {countdown = value}
};
}
To use this you would do:
var countdown = countdownFactory();
countdown.set(2);
countdown.get() // returns 2
JavaScript doesn’t have keywords for defining if a variable/function/object is private/public/protected/final/etc (assessor keywords)… But since it has closures and each closure has its own scope we can emulate some of these access controls, a private variable is simply a variable declared inside an “unreachable scope”.
learn more ....
http://asp-net-by-parijat.blogspot.in/2015/08/private-variables-and-functions-in.html
A closure should do it, but you need some access to the function. Here in this case it is countdown.setResult(), which puts the value to private variable result.
var countdown = function () {
var result = '';
function countdown() {
return result;
}
countdown.setResult = function (r) {
result = r;
};
return countdown;
}();
function something(){
countdown.setResult(42);
}
alert(countdown()); // empty string
something();
alert(countdown()); // 42
I am a bit new to javascript, i was just trying the below snippet:
_getUniqueID = (function () {
var i = 1;
return function () {
return i++;
};
}());
s = _getUniqueID();
console.log(s); // 1
console.log(_getUniqueID()); // 2
I was under the impression that i would have to do s() to get 1 as the result and i was thinking that _getUniqueID() returns a function rather than execute the funtion inside it. Can somebody explain the exact execution of this function please ?
What you're seeing here is a combination of Javascript's notion of closure combined with the pattern of an immediately invoked function expression.
I'll try to illustrate what's happening as briefly as possible:
_getUniqueID = (function () {
var i = 1;
return function () {
return i++;
};
}()); <-- The () after the closing } invokes this function immediately.
_getUniqueID is assigned the return value of this immediately invoked function expression. What gets returned from the IIFE is a function with a closure that includes that variable i. i becomes something like a private field owned by the function that returns i++ whenever it's invoked.
s = _getUniqueID();
Here the returned function (the one with the body return i++;) gets invoked and s is assigned the return value of 1.
Hope that helps. If you're new to Javascript, you should read the book "Javascript, the Good Parts". It will explain all of this in more detail.
_getUniqueID = (function () {
var i = 1;
return function () {
return i++;
};
}());
s = _getUniqueID();
console.log(s); // 1
console.log(_getUniqueID()); // 1
when you do () it calls the function,
a- makes function recognize i as global for this function.
b- assigns function to _getUniqueID
you do s = _getUniqueID();,
a - it assigns s with return value of function in _getUniqueID that is 1 and makes i as 2
when you do _getUniqueID() again it will call the return function again
a- return 2 as the value and
b makes value of i as 3.
This is a pattern used in Javascript to encapsulate variables. The following functions equivalently:
var i = 1;
function increment() {
return i ++;
}
function getUniqueId() {
return increment();
}
But to avoid polluting the global scope with 3 names (i, increment and getUniqueId), you need to understand the following steps to refactor the above. What happens first is that the increment() function is declared locally, so it can make use of the local scope of the getUniqueId() function:
function getUniqueId() {
var i = 0;
var increment = function() {
return i ++;
};
return increment();
}
Now the increment function can be anonymized:
function getUniqueId() {
var i = 0;
return function() {
return i ++;
}();
}
Now the outer function declaration is rewritten as a local variable declaration, which, again, avoids polluting the global scope:
var getUniqueId = function() {
var i = 0;
return (function() {
return i ++;
})();
}
You need the parentheses to have the function declaration act as an inline expression the call operator (() can operate on.
As the execution order of the inner and the outer function now no longer make a difference (i.e. getting the inner generator function and calling it, or generate the number and returning that) you can rewrite the above as
var getUniqueId = (function() {
var i = 0;
return function() {
return i ++;
};
})();
The pattern is more or less modeled after Crockford's private pattern
_getUniqueID = (function () {
var i = 1;
return function () {
return i++;
};
}());
console.log(_getUniqueID()); // 1 , this surprised me initially , I was expecting a function definition to be printed or rather _getUniqueID()() to be called in this fashion for 1 to be printed
So the above snippet of code was really confusing me because I was't understanding that the above script works in the following manner, by the time the IFFE executes _getUniqueID is essentially just the following:
_getUniqueID = function () {
i = 1
return i++;
};
and hence,
_getUniqueID() // prints 1.
prints 1.
Note: please note that I understand how closures and IFFE's work.
Reading an example from a book, can someone explain how the function call to fibonacci takes in the argument 'i' when the function itself doesn't declare any parameters?
var fibonacci = (function () {
var memo = [0, 1];
var fib = function (n) {
var result = memo[n];
if (typeof result !== 'number') {
result = fib(n - 1) + fib(n - 2);
memo[n] = result;
}
return result;
};
return fib;
}());
for(var i = 0; i <= 10; i += 1) {
document.writeln('// ' + i + ': ' + fibonacci(i));
}
You are creating a self-executing anonymous function (function(){}()); which inside it returns the fib function, which takes an argument. var fib = function(n){} ... return fib;
var fibonacci = (function () { // Self-executing anonymous function
var memo = [0, 1]; // local variable within anonymous function
var fib = function (n) { // actual fib function (takes one argument)
var result = memo[n];
if (typeof result !== 'number') {
result = fib(n - 1) + fib(n - 2);
memo[n] = result;
}
return result;
};
return fib; // return fib (fibonacci is now set to the function fib defined above, which takes one argument)
}());
This system (returning a function from a self-executing anonymous function) allows for you to define variable in a local scope that can still be used by the returned function, but not by functions outside the scope. Here is an example.
This technique is called closure in JavaScript. Read more about it on the MDN guide.
Because the function returns a function that does take a parameter.
To understand this, I think it is helpful to work with a simpler example. Take a look at the two memoized functions below. The only difference is the () after add : function (){ ... }() on the successful memorization code.
var failed_memoization = {
add : function (){
var counter;
return function(number){
if(counter){
counter = counter + number;
return counter;
}
counter = number;
return counter;
} //NOTE: NO function call brackets here
}
}
var successful_memoization = {
add : function (){
var counter;
return function(number){
if(counter){
counter = counter + number;
return counter;
}
counter = number;
return counter;
}
}() //NOTE: the function call brackets here!!
};
}
Now let's execute these two functions.
console.log('Failed Memoization');
console.log(failed_memoization.add(5)); //We wanted 5, but this prints the text of the function instead.... Okay, lets try something else
console.log(failed_memoization.add()(5)); //5
console.log(failed_memoization.add()(10)); //10 (Wanted it to be 5+10 = 15.
console.log('successful_memoization');
console.log(successful_memoization.add(8)); //8
console.log(successful_memoization.add(16)); //24 (This is what we wanted 8 + 16 = 24)
So what's going on here is that for successful_memoization when we put () to the end of its add : function(){...}(). As such, this function is executed immediately on the creation of the static object. In turn, executing that function returns the object function (number){...} wich results in the assignment: add : function (number){...} NOT add : function(){} as it initially appears.
What is also important to note is that var counter is declared outside return function(name){}. As it is still being used within add : function(number){...}, this variable is accessible within that function. For failed_memoization.add()(number), it uses a new counter each time we execute that function, because we execute the first function, and then the inner function on each call. For successful_memoization.add(number) we executed the outer function upon initialization, and so counter will persist through all subsequent calls and will not be overwritten.
There is a self-calling function that returns the function with the identifier fib which is then assigned to the identifier fibonacci. This way you can create a private variable memo which is only accessible by the function. So var fibonacci in fact is function(n){...}.
var fibonacci = (function() {
...
return fib;
})();
This is a self-executing function.
It declares a function expression which returns a function (fib), executes the outer function expression immediately (()), and assigns its return value (which is fib) to the fibonacci variable.
Function fibonacci does take one argument. Note that the unnamed function that starts on the first line is not the function that ends up being known as fibonacci. That unnamed function is immediately called since you have () immediately after closing brace }. This unnamed function returns fib, a local variable to which a single-argument function is assigned. Thus, fibonacci ends up referring to the function returned by the unnamed function, i.e. fibonacci is this:
var fib = function (n) {
var result = memo[n];
if (typeof result !== 'number') {
result = fib(n - 1) + fib(n - 2);
memo[n] = result;
}
return result;
};
Note that this function refers to local variables of the unnamed function for the purpose of memoizing.
The critical thing to notice was () which calls the unnamed function immediately, here are some examples that illustrate this technique:
var a = (function() { return 1; });
Variable a holds a function which returns 1.
var a = (function() { return 1; }());
Here however, variable a holds value 1.