JavaScript Closures - Program flow [duplicate] - javascript

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.

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

JS Closures - What is the value of x?

This is a thought exercise. I'm not doing anything with this code and the purpose is to better understand how closures work.
Thought Process:
x === 10 in global scope.
outer() function is called.
x === 20 in the global scope and local scope.
inner() function is called.
right side of 'var x' is expressed.
In x + 20, because x is not defined in local scope, it searches outer scope and finds x === 20.
var x = 20 + 20.
var x === 40.
return x.
result === 40.
However, the answer is 20. Why is this?
var x = 10;
function outer () {
x = 20;
function inner () {
var x = x + 20;
return x;
}
inner();
}
outer();
var result = x;
When the inner() function is called, the first thing that happens is var x.
This means the JavaScript interpreter first creates a variable named x to which it assigns undefined.
Then it runs the assignment expression x + 20, which is equivalent to undefined + 20 which is NaN.
Your variable result has nothing to do with your inner() function as you have a local variable (because of that var x) and you ignore the returned result.
In other words, your code is equivalent to just this:
var x = 10;
function outer () {
x = 20;
}
outer();
var result = x;
Because your inner function defined a local var x which will hide the global variable outside. And the outer function uses the global variable x and assign it to 20. Obviously, the global x is 20. Javascript will define every local variable before you call the function in the prototype chain.
var x = 10;
function outer () {
x = 20;
function inner () {
alert(x); // alert undefined
var x = x + 20;
return x;
}
inner();
}
outer();
var result = x;

js variable value in a function from which scope [duplicate]

This question already has answers here:
Javascript scoping of variables
(3 answers)
Closed 6 years ago.
i have this code in java script
var x = 5;
function f(y) { return (x + y) - 2 };
function g(h) { var x = 7; return h(x) };
{ var x = 10; z = g(f) };
z value is 15. why?
the expression (x+y)-2 is being evaluated as (10+7)-2.
why does x get the value of 10, and not the value of the previous
block, where x = 7?
thanks for the help
You can completely delete the first assignment. It gets overwritten before you call g(f).
Also, you can remove the parentheses of the last block as there is no block scope in JS (actually block scope got introduced with let, so you wanna use that instead).
var x = 5;
function f(y) {
// global variable x is 10 -> 10 + 7 - 2 = 15
return (x + y) - 2;
}
function g(h) {
// x gets declared locally - local value will be used
var x = 7;
return h(x); // f gets called with y = 7
}
x = 10; //global x gets changed
z = g(f);
... and always place your semicolons. Even though they maybe look optional but in some cases they are obligatory.
Value of variable x is 10 at global execution context.
When function f is finally called the value of the argument which is y, this y actually represent value of x at local execution context of function g, here x is 7.
var x = 5;
function f(y) {
return (x + y) - 2 ;
}; // value of global var x is 10, value of parameter passed is 7
// this value comes from the local var x of g function's execution context.
function g(h) {
var x = 7; return h(x); };
{ var x = 10; z = g(f); };
console.log(z);

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.

Understanding Javascript Functions and Closure [duplicate]

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.

Categories

Resources