Understanding Javascript Functions and Closure [duplicate] - javascript

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Closed 9 years ago.
In the following example, how is y given the value of 1? I added some logging to see values and don't understand how/where y is assigned...
(function() {
function foo(x) {
var callNum = 0;
var baz = 3;
return function (y) {
callNum++;
console.log("callNum: " + callNum);
console.log("y: " + y);
console.log("baz: " + baz);
console.log("x: " + x);
console.log(x + y + (++baz));
}
}
var moo = foo(2); // moo is now a closure.
moo(1);
moo(1);
})();
Here's the fiddle output log:
callNum: 1
y: 1
baz: 3
x: 2
7
callNum: 2
y: 1
baz: 4
x: 2
8

foo() returns a function. This returned function accepts a single argument, the y you are concerned with.
So when you do this:
// returns a function that accepts `y` with `x` shared via closure
var moo = foo(2);
// execute the inner function, passing in a value for `y`.
moo(1);
foo(2) returns a function. x is now 2. moo is now a function that accepts a value for y, and you pass in 1. So y is now 1.
To think of it another way, you can invoke your inner function by doing:
foo(x)(y);
Or with the values you are using:
foo(2)(1);
So, in answer to your question, y gets set to 1 when you do:
moo(1);

In your code:
(function() {
function foo(x) {
var callNum = 0;
var baz = 3;
These are the parameters that matter (x, callNum and baz). They form closures involving the following function:
return function (y) {
This function has a closure to each of the outer local variables (including moo and foo).
callNum++;
console.log("callNum: " + callNum);
console.log("y: " + y);
console.log("baz: " + baz);
console.log("x: " + x);
console.log(x + y + (++baz));
}
}
There are also closures involving moo and both the above functions, however it's not used so is irrelevant to the outcome.
var moo = foo(2); // moo is now a closure.
The rest is answered by Alex.

Related

Using a constant to define a function within a function?

Main questions:
1. How does f refer to r and t within the formula but no declaration for them anywhere in the code. Also the references appear to be cyclical.
2. Why is f2 set to f(x) what does that accomplish?
let x = 3;
let y = 7;
const f = function(r) {
return function(t) {
return x + y + Math.abs(r) + t;
}
};
const f2 = f(x);
x = 2;
alert(f2(17));
This code works but I do not understand what it is doing.
Thank you for your help.
How does f refer to r and t within the formula but no declaration for them anywhere in the code.
You can declare variables using function arguments. This is what they are doing here.
A simplified example:
function example(f) {
console.log("f is " + f);
}
example("one");
example(2);
Why is f2 set to f(x) what does that accomplish?
It calls f(x) and assigns its return value.
That return value is the function after the return keyword.
Now f2 is a function.
See also How do closures work

JavaScript Closures - Program flow [duplicate]

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Closed 5 years ago.
Can anyone explain how this code works?
function makeAdder(x) {
return function(y) {
return x + y;
};
}
var add5 = makeAdder(5);
var add10 = makeAdder(10);
console.log(add5(2)); // 7
console.log(add10(2)); // 12
Reference: https://mozilla.org/en/docs/Web/JavaScript/Closures
When you call your makeAdder(5), it returns the reference to a new function.
function(y) {
return x + y;
};
So add5 keeps the reference. After it when you call add5(2), you pass the 2 to the function. In it when it wants to return x + y, it starts to find the variables. Starting from x, it looks and see's that the x is not defined in it and goes to the scope in which inner function was defined ` here
function makeAdder(x) {
return function(y) {
return x + y;
};
}
It see's than x was defined here, because you call and pass x during var add5 = makeAdder(5);. After it goes to find y and finds in it's scope. And after all returns x + y.
The idea is this, every function has a reference to it's creater (where it was defined) and when it doesn't find a variable, it goes to find in it's greater and so till to global scope.
function makeAdder(x) {
return function(y) {
return x + y;
};
}
When you do var add5 = makeAdder(5); the add5 becomes a function which was returnd my makeAdder,
the add5 will be following
function(y){
return 5 + y;
}
so when you do add5(2) it will do 5 + 2 and will return 7;
makeAdder(5)
x => 5 and y is not having value so x+y => 5+0 => 5
var add5 = makeAdder(5);
add5(2);
we have created variable for the function makeadder with x => 5
so now we pass y => 2 and x => 5 so x+y => 5+2 => 7
This property of outer function variable accessible in inner function is called closure property in javascript. Also adding to that y variable is not accessible to outer function.

nested function losing variable reference [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 6 years ago.
In the following code:
function outer() {
var x = 'foo';
function inner() {
var y = x; // y == 'foo'
var x = 'bar'; // x == 'bar', y == undefined
}
}
Why does the variable y become undefined within inner()? shouldn't it refer to x in outer()?
If the line var x = 'bar'; is removed then y does indeed have the value 'foo'.
The inner function is interpreted as if it were written like this:
function inner() {
var y;
var x;
y = x; // y == undefined
x = 'bar'; // x == 'bar'
}
The declarations are hoisted, but the initializations are processed top to bottom. Thus, throughout the entire inner function, the symbols x and y both refer to the variables declared locally in that function; in particular x is the local x, not the one in the enclosing context. When the initializer expression for y is evaluated, therefore, x is the local x, which has not yet been initialized; its initializer expression comes after the initializer for y.

Indirect call to eval in strict mode. What happens to x?

I've been studying for a job interview, and started digging into JavaScript. Came up with this.
So:
"use strict";
var x = 0;
var y = 0;
eval("x=3;y=11;"); //direct call to eval in global scope
console.log("x: " + x); // outputs 3
console.log("y: " + y); // outputs 11
But:
"use strict";
var x = 0;
(0, eval)("x=3;y=11;"); //indirect call to eval in global scope
console.log("x: " + x); // outputs 0 because the strict mode won't allow the reassignment?
console.log("y: " + y); // outputs 11
I don't know/understand what happens with the x when the eval is executed. I know with strict mode off the assignment goes through no problem. Would anyone be willing to explain this to me? Thanks!
It appears to be how Node.js handles variables (they do not default to global). The indirect call to eval is assigning to the global object.
"use strict";
var x = 0;
(0,eval)("x=3;y=11;");
x++;
console.log("x: " + x); // outputs 1
console.log("global x: " + global.x); // outputs 3
console.log("y: " + y); // outputs 11

newbie in javascript closure, and the closure test's result is unexpect

newbie in javascript closure
i follow a example from internet, and try to change some of it
i think it should give me 16,17,18,19
but the result was unexpect
here is my code.
i do not know why i first call bar2(10),it alert 17, does it should give me 18?
function foo(x) {
var tmp = 3;
return function (y) {
alert(x + y + (++tmp));
}
}
var bar = foo(2);
bar(10);//alert16
bar(10);//alert17
var bar2 = foo(3);
bar2(10);//alert17
bar2(10);//alert18
Because tmp is a variable local to the function you return from foo -- that means when you call foo for the second time, it gets reset to 3. 3 + (3+1) + 10 = 17.
The result 17 is correct.
Each call to foo produces a new function with a new closed-over variable tmp.
Perhaps you thought the second call to foo uses the same tmp as in the first call? It doesn't. That is why you get 17: 3 + 10 + 4.
bar(y) = n = x + y + tmp
bar(10) = 16 = 2 + 10 + 4
bar(10) = 17 = 2 + 10 + 5
bar2(10) = 17 = 3 + 10 + 4
bar2(10) = 18 = 3 + 10 + 5

Categories

Resources