Using a constant to define a function within a function? - javascript

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

Related

Printing curried function doesn't show the captured parameter

If I define a curried function like this:
const gt = x => y => y > x
I would expect gt(5) returns y => y > 5
but gt(5) (or gt(5).toString()) returns y => y > x
How do I get the captured parameter?
I would expect gt(5) returns y => y > 5
That isn't how JavaScript works. The code of the function returned by gt(5) is y => y > x, it's just that that code executes in an environment where the identifer x resolves to a binding that has the value 5 because it's a closure over that environment. toString on functions returns a string version of the source code of the function (or a function declaration around the [ native code ]) (spec), so you still see y => y > x. The string returned by toString doesn't include the environment in which that code runs.
See also:
How do JavaScript's closures work? - here on SO
Closures are not complicated - on my old anemic blog (uses some outdated terminology, I should probably fix that)
As #VLAZ points out in a comment, you can override the default toString on a function to give it the behavior you want. If you don't mind duplication (which almost inevitably leads to maintenance issues):
const gt = x => {
const fn = y => y > x;
fn.toString = () => `y => y > ${x}`;
return fn;
};
console.log(String(gt(5)));
...or if you want to define toString with the same enumerability, etc., as the version on the prototype:
Object.defineProperty(fn, "toString", {
value: () => `y => y > ${x}`,
writable: true,
configurable: true,
});
Doing that in the general case requires a proper JavaScript parser to do the substitution.
It's not possible to just print a variable captured in a closure, however there is a workaround for curry. I will be referring to Brian Lonsdorf's article on Medium Debugging Functional which goes into more details about curry and compose. I heartily recommend reading the article itself, as I will only use the essentials.
Brian Lonsdorf proposes a custom implementation of a general curry function. The original version is taken from an article by Erin Swenson-Healy.
Here is the modified version:
function fToString(f) {
return f.name ? f.name : `(${f.toString()})`;
}
function curry(fx) {
var arity = fx.length;
function f1() {
var args = Array.prototype.slice.call(arguments, 0);
if (args.length >= arity) return fx.apply(null, args);
function f2() {
return f1.apply(null, args.concat(Array.prototype.slice.call(arguments, 0)));
}
f2.toString = function() {
return fToString(fx)+'('+args.join(', ')+')';
}
return f2;
};
f1.toString = function() { return fToString(fx); }
return f1;
}
const gt = curry((x, y) => y > x);
const sum3 = curry((x, y, z) => x + y + z);
const ltUncurried = (x, y) => y < x;
const lt = curry(ltUncurried);
console.log(gt(1)); // ((x, y) => y > x)(1)
console.log(sum3(1)); // ((x, y, z) => x + y + z)(1)
console.log(sum3(1, 2)); // ((x, y, z) => x + y + z)(1, 2)
console.log(sum3(1)(2)); // ((x, y, z) => x + y + z)(1, 2)
console.log(lt(1)); // ltUncurried(1)
(I have modified fToString() to include brackets around f.toString() for better readability)
This is quite flexible as it allows currying any function but also provides better logging of said function. The toString implementation can be modified if required for whatever you deem are the most important details.
const gt = x => y => y > x
gt(1);
If you had pass only 1 argument like gt(1) and if you Check in console, x = 1, y is not available at this time. So the execution context (call stack) will show only the x argument and for the gt() method it will only show the code (y > x).
And here below gives us a hint that gt(1) will first bind x to 1, and return a new function f(y) = y > x = y > 1
You didn't second pass second argument, It means now the function f(y) = 1 + y is executed, and this time, it will check for the y where y is not available at that time. And the argument x’s value 1 is still preserved in the context via Closure.
It's look like same as below closure function :-
function add(x) {
return function (y) {
return y > x
}
}
var d = add(1)(2); ===>>>> true

Why does this JavaScript code return an error?

I know in JavaScript only function declarations are hoisted, which means it should print 30 after running the function sum.
However it says diff is not defined, shouldn't it be hoisted?
sum(10, 20);
diff(10, 20);
function sum(x, y) {
return x + y;
}
let diff = function(x, y) {
return x - y;
}
It's because as you said, only function declarations are hoisted, not function expressions (assigning a nameless function to a variable). Following code works:
sum(10, 20);
diff(10, 20);
function sum(x, y) {
return x + y;
}
function diff(x, y) {
return x - y;
}
To declare diff the way you did, you must lift it to the top of your code:
let diff = function(x, y) {
return x - y;
}
sum(10, 20);
diff(10, 20);
function sum(x, y) {
return x + y;
}
Yes, let and const are hoisted but you cannot access them before the actual declaration is evaluated at runtime.
You are accessing the function before you initialize it.
So this should work,
let diff = function(x, y) {
return x - y;
}
function sum(x, y) {
return x + y;
}
console.log(sum(10, 20));
console.log(diff(10, 20));
let diff will hoist but at the moment when function diff(10, 20); will be called variable diff will not jet be defined with the function.
Google this topic function declaration vs function expression
Because Function Expressions are not hoisted like Function Declarations
Function expressions in JavaScript are
not hoisted, unlike function declarations. You can't use function
expressions before you create them:
console.log(notHoisted) // undefined
// even though the variable name is hoisted, the definition isn't. so it's undefined.
notHoisted(); // TypeError: notHoisted is not a function
var notHoisted = function() {
console.log('bar');
};
https://developer.mozilla.org/en-US/docs/web/JavaScript/Reference/Operators/function#function_expression_hoisting
You will need to use a Function Declaration if you want it to be hoisted.

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.

JavaScript Closures and parent parameters

I have the following code which is a little bit messy but I would like to understand two points -
f and g are both inner function(a,b) which remember the hello(c,b) parameters from the time they were created.
Let say I call g with some parameter - and then change his parent parameters , do I also change f parent parameters? of that f and g have separated stack framework?
when I call hello.change("a") - how can I know what's his the parent parameters x and c? are f or g effect the change function?
x = "unimaginably";
var c = "inconceivably";
function hello(c,b) {
var x = 30;
b.change = function (d){
console.log("d is =" + d);
c=d;
console.log("x is =" + x);
return this.x;
}
return function (a,b) {
//x is the varible in the wrap function
console.log("x= " + x);
if(x == undefined) {x = a}
else if (b != undefined) {x = b}
else if (c != undefined) {x = c}
return x;
}
}
f = hello("impossible" , hello);
g = hello("impossible" , hello);
f.x = "mistake";
g.x = "error";
hello.x = "arguably";
x = f("no","yes");
x = g( "maybe" , "possibly");
x = hello.change("undoutly");
Let say I call g with some parameter - and then change his parent parameters, do I also change f parent parameters? of that f and g have separated stack framework?
No. The closure scopes of f and g are different, because they were created in different calls to hello (each of which created its own c, b, x variable set).
when I call hello.change("a") - how can I know what's his the parent parameters x and c? are f or g effect the change function?
In your case g, because that's the last function whose creation hello call wrote to hello.change.

Two operation in one function

function test(a, b){
a = a + 2;
b = b + 5;
}
var a = 1;
var b = 2;
test(a, b);
console.log(a);
console.log(b);
This return 1 and 2, but i would like 3 and 7.
Is possible to make two operation in one function? This working if i use return, but how to use return to two operation?
live: http://jsfiddle.net/anCq6/
The reason you are getting 1 and 2 instead of 3 and 7 is because there are two different a and b variables. There's the a and b you declared outside the function, and there is the a and b which represent the values you passed into the function. (Basically, the parameters declared in the function's parentheses are newly declared variables.)
If you want to change the external a and b, change your test function to the following:
function test(x, y) {
a = x + 2;
b = y + 5;
}
Or, alternatively, don't pass a reference into the function, so that the a and b in the inner scope refer to the same a and b as the outer scope:
function test() {
a = a + 2;
b = b + 5;
}
Just send it back as an object...
function test(a, b){
a = a + 2;
b = b + 5;
return {a:a,b:b};
}
var a = 1;
var b = 2;
var test = test(a, b);
alert(test.a);
alert(test.b);
DEMO HERE
This doesn't work because since numbers are passed by value and not by reference, you're modifying the local copies of those variables, however the ones in the outer scope remain unmodified.
If you remove the a and b parameters from your function, you'll get the behavior that you want since the a and b parameters that are being modified will be the ones in the outer scope.
What are references?
Here's a pretty decent answer - Javascript by reference vs. by value
In short, only objects and arrays are passed by reference. Although in reality it's more complex than this depending on how functions are defined and syntax, at this point you can assume that anything that's defined by calling new or the syntactic shorthands [] ( array ) and {} ( object ) are passed by reference. Other types like numbers and strings are passed by value.
Another solution: because of how variable scope works in JavaScript, you can just remove the parameters of "test" function and it will work.
function test(){
a = a + 2;
b = b + 5;
}
function test(){
a = a + 2;
b = b + 5;
}
var a = 1;
var b = 2;
test();
console.log(a);
console.log(b);

Categories

Resources