How does this higher order function work in JavaScript? - javascript

This code is confusing me.
Where does the inner function get the value for x.
function createMultiplier(multiplier) {
return function(x) {
return x * multiplier
}
}
let doubleMe = createMultiplier(2);

This is called currying, what happens is that in the function createMultiplier you get a function and then when you execute that function you pass the parameter x
If you want to execute the function inside the function immediately, you can use this code createMultiplier(2)(5)
If you use console logs you can understand better what happens, I made an example bellow, so you can see first you only get a function and then you can pass the parameter x
function createMultiplier(multiplier) {
return function(x) {
return x * multiplier
}
}
const doubleMe = createMultiplier(2);
console.log(doubleMe)
const result = doubleMe(5)
console.log(result)

The inner function will get the value x. When you invoke: doubleMe(16), for example.
When you call createMultiplier(2) you are setting the multiplier value.

It might be helpful to try and visual what happens when you call createMultiplier(2).
This will create a function that would look like this:
function doubleMe(x) {
return x * 2; // 2 is the multiplier that we supplied to 'createMultiplier'
}
let answer = doubleMe(4);
// answer = 8;
another example:
let tripleMe = createMultiplier(3);
// is the same as writing this
function tripleMe(x) {
return x * 3;
}
let answer = tripleMe(3);
// answer = 9;

Related

What are the parameters in arow function in JS?

please help the newbie figure it out.
There is such a code:
function makeDouble (x) {
return x * 2;
}
var doMath = (x, func) => func(x + 5);
var num = 5;
The task is:
*Using only makeDouble, doMath, and num, make the value of num equal to 20.
num = _____________________________________________________*
I can’t understand why there are two parameters in the parameters of an arrow function, but in the body of this function itself there is only one parameter. What am I doing wrong?
You can translate the arrow function as:
function doMath(x, func) { return func(x+5); }
So you pass a value (x) and a function (func) to the doMath function. func can be any function, for example makeDouble... You can call it like:
doMath(1, makeDouble)
And the result will be (1+5)*2 = 12.
I think you can figure out the rest based on this.
Both parameters in doMath() are being used. The first is argument x will be applied as an argument in the function call of the second argument func and the value returned from that function call will be returned by doMath() itself.
The answer is
num = doMath(num, makeDouble)
There are also 2 parameters in the body of the function.
Let's look a little bit closer
func(x+5)
func is a second parameter of the function and x that we pass to it is a first parameter
Here, func is a callback function. In javascript, you can pass a function as a parameter just like you pass any other variable, for e.g, an integer, object or an array. So here in doMatch you're passing a number and a callback function. When doMatch executes, it calls func with the parameter 10 (5+5). Func, now, will be executed and will return 2*10 (20)
function makeDouble (x) {
return x * 2;
}
var doMath = (x, func) => func(x + 5);
var num = 5;
console.log(doMath(num, makeDouble))
function makeDouble (x) {
return x * 2;
}
const doMath = (x, func) => func(x + 5);
const num = 5;
let result = doMath(num, makeDouble);
console.log(result);// 20
doMath(x, func) is an arrow function which takes two parameters. The first para meters is your numeric value, and the second is a function which in this case is makeDouble(x). Inside the arrow function, the makeDouble(x) function is called with the numeric parameter + 5 like makeDouble( num + 5). In this case, num is added five inside the constructor, so this time makeDouble returns the product of 10 * 2. Also, I would suggest to revise the use of var. Currently the use of let and const is preferred over var.
Arrow functions can take other functions as parameters, which is great to work with recursion and functional programming.
Thank very much you all!
My problem was that I did not notice that the makeDouble() function in the parameters of the arrow function did not return the value, but the content of the function itself. And then in the body of the arrow function, it can be to call the makeDouble() function as a parameter.

The difference between returning a function vs statement inside a function

I'm reading Eloquent JS and the example of closures has a code of block that returns a function returning a value. What is the difference between that and returning the value right away.
// returning value
function wrapValue(n) {
let local = n;
return local;
}
let wrap1 = wrapValue(1);
let wrap2 = wrapValue(2);
console.log(wrap1);
// → 1
console.log(wrap2);
// → 2
// returning a value with a function
function wrapValue2(n) {
let local = n;
return () => local;
}
let wrap3 = wrapValue2(3);
let wrap4 = wrapValue2(4);
console.log(wrap3());
// → 3
console.log(wrap4());
// → 4
For the purpose of just logging the same value without doing anything else to it, there is absolutely no difference whatsoever.
But there are scenarios where you have to do some other operation later on upon returning the value like so
function doubleTheValue(n){
const val = n * 2;
return () => val * 2;
}
const doubleValueAgain = doubleTheValue(2);
console.log(doubleValueAgain());
So to answer your question, if you try to return a function instead of just the value, then you have to call the returned result again just to get the value.

Javascript high order functions - How do pass a variable from to function to it's parent function

I'm trying to solve this algorithm. I think I'm very close.
I need the seven function to pass the a variable to the timesFive function. OR is there a way I can pass the * 5 operation from timesFive to seven in order to get the desired result?
I'm not allowed to have variables outside of these two function scopes.
I can add another argument to timesFive as long as b remains the first argument.
function seven(action) {
var a = 7;
return action;
}
function timesFive(b) {
console.log(a); // How can I access "a"?
return a * 5;
}
console.log(seven(timesFive())); // Desired result: 35
timeFive should return a function and seven should expect a function as a parameter. Then seven can simply call the function that timesFive() returns (so basically returning the * 5 operation as you mentioned in your question):
function seven(action) {
var a = 7;
return action(a);
}
function timesFive() {
return (a) => a * 5;
}
console.log(seven(timesFive())); // Desired result: 35
BTW
You'll often see these kind of exercises written in a way that mimics the functional notation from math, like:
const seven = (action) => action(7);
const timesFive = () => (a) => a * 5;
console.log(seven(timesFive())); // Desired result: 35

Currying function work in javascript

Can someone please explain the below 'Currying' function. When I set a break point, I can see values 'b' and 'c' are undefined and returned. But how does the system get the value 7 for 'b' and 9 for 'c' in this case. Its printing the correct result for 5*7*9, ie 315 in console.
function multiply(a){
return function (b){
return function (c) {
return a*b*c ;
}
}
}
var answer = multiply(5)(7)(9);
console.log(answer);
When you call multiply(5) a function is returned and that function is immediately called with multiply(5)(7) and have access to a and b, then a new function is returned and is also immediately called when multiply(5)(7)(9) and has access to a, b, and c.
The answer to why the nested functions have access to parent function parameters is closures. Please check this other question/answers about closures in javascript: link.
You can understand currying if you assign each intermediate result to a variable. Rewrite the function calls like this:
var x = multiply(5)
var y = x(7);
var answer = y(9);
Now it is more clear that the result of calling multiply(5) is a function. We call it with x(7) which passes the value of 7 to b. This results in another function which we call with y(9) which in turn passes the value of 9 to c and returns the final result.
When you call the multiply function, the important thing is each function returns an anonymous function. It will be easier if you give them names.
function multiplyA(a){
return function multiplyB(b){
return function multiplyC(c) {
return a*b*c ;
}
}
}
// When you call multiplyA(5)(7)(9)
// From the first, multiplyA(5) returns multiplyB with scope with multiplyA
// just like below
const a = 5;
const multiplyB = function(b){
return function multiplyC(c) {
return a*b*c ;
}
}
// Once more call multiplyB(7)
// It also returns function named multiplyC
const a = 5;
const b = 7;
const multiplyC = function(c) {
return a * b * c;
}
// Finally call mulitplyC(9) means 5 * 7 * 9
To understand it, closure and function scope will be helpful.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

write a twice function that multiplies one number four times by itself in the format below

I want to write a function called twice that takes a function f and a value x as its parameters and returns f(f(x)). For example,
twice(function (x) { return x * x; }, 3)
should return 81. How do I do it?
Call the anonymous function twice which is passed as an argument. On the second call use the returned value of first execution as the argument.
function twice(funct, a) {
return funct(funct(a));
}
console.log(
twice(function(x) {
return x * x;
}, 3)
);
What is stopping you? You already has the answer with you. It is working pretty fine.
function twice(f, x) {
return f(f(x));
}
var result = twice(function(n){return n*n;}, 3);
console.log(result);

Categories

Resources