What are the parameters in arow function in JS? - javascript

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.

Related

Learn Javascript : Higher Order Function

anyone can explain this code..? especially "action(i)" in for scope. i'm new in JS
function repeat(n,action){
for(let i= 1; i<=n; i++){
action(i);
}
}
repeat(10, console.log);
repeat(3, alert);
The code above simply repeats a given function (the action function) n amount of times, passing i (the current iteration) into the function
e.g.:
repeat(10, console.log);
That repeats console.log 10 times. console.log is a function, which is passed in as the action function. Then it is run 10 times.
Higher order function are functions that take other functions as parameter(s). It is based on functions being so-called first-class-members in Javascript, which says, among other things, this: functions can be passed to other functions, as parameters.
In your example the passed function inside the repeatfunction is called action, which is defined by your repeat function signature (n,action) (regardless of any name the actual function that is being passed in might already have), so whatever function gets passed into repeat is callable inside it using action().
Please note that there is no way to guarantee that the actual call will have a function as a second parameter; noone can prevent somebody from making calls like repeat('foo', 'bar') or even repeat(). It is your job as a developer to make your function failsafe in this regard, or to take the shit in, shit out standpoint.
A more simplified example would be this:
function showMessage(message, showMethod) {
showMethod(message);
}
showMessage('Hello world shown by console.log', console.log);
showMessage('Hello world shown by alert', alert);
showMessage('Hello world shown by console.error', console.error);
showMessage is a function that shows a message, which it expects to be the first parameter when it is called.
The actual function that should be used to display the passed message needs to be passed into showMessage as a second parameter.
When called, showMessage runs the function that was passed as a second parameter (which is renamed to showMethod inside showMessage), passing message to it.
Another more practical use case could be this:
function add(x, y) { return x + y; }
function subtract(x, y) { return x - y; }
function multiply(x, y) { return x * y; }
function divide(x, y) { return x / y; }
function calculate(x, y, calcFunction) {
const result = calcFunction(x, y);
return result;
}
console.log(calculate(2, 5, add));
console.log(calculate(2, 5, subtract));
console.log(calculate(2, 5, multiply));
console.log(calculate(2, 5, divide));

How does this higher order function work in 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;

Passing arguments to a function within a function - javascript

I am trying to pass an argument to a function within a function;
function add() {
let x = arguments[0];
function s(num) {
return num + x;
}
}
add(2)(3) //second argument to be passed to 'function s'.
so im wanting the call to return 5.
What is the best approach to this? thanks in advance.
Currying is the name of the construction that allows you to partially apply the arguments of a function. It means that instead of passing multiple arguments to a function and expect a final result, you can pass a subset of this arguments and get back a function that is waiting for the rest of the arugments.
As already pointed by #KevBot, your example is missing the return of the second function and would be:
function add() {
let x = arguments[0];
return function s(num) {
return num + x;
}
}
add(2)(3);
ES6 Curryed Hello World:
curryedHelloWorld = (greeting) => (name) => `${greeting}, ${name}!`;
curryedHelloWorld("Hello")("Tygar");
You can even uncurry the curryedHelloWorld example making it the opposite way:
helloworld = (greeting, name) => curryedHelloWorld(greeting)(name);
helloworld("Hello", "Tygar");

Currying - How is returned function called with a second argument in JavaScript?

How does the second argument get called in liftf(add)(1)?
function add (first, second) {
return first + second;
}
function liftf (binary) {
return function (first) {
return function (second) {
return binary(first, second);
};
};
}
var inc = liftf(add)(1);
I understand how lift(add) is called and stored.
I am confused on how a function is returned but then called with (1).
I first explored if it operated on the same principle of an IIFE but it doesn't seem to. IFFE's would be (function() {}()) vs funciton() {}().
The 'chained' function arguments confuse me and I want to understand what's going on.
Thanks!
If an expression evaluates to a function, then that function can be invoked with parentheses and the list of arguments.
Since the expression liftf(add) returns a function, you call the returned function with the parameter 1 in parentheses: liftf(add)(1)
Another way to look at it is if you set liftf(add) to a variable, then you could call the function stored in that variable:
var additionFunc = liftf(add) // Stores the new function in additionFunc
var result = additionFunc(1) // Evaluates the new function
Let's also look at IIFEs. Suppose we have one like this:
(function(x) {return x + 1})(5)
The (function() { /* ... */ }) expression evaluates to a function, which is then evaluated by the parentheses and argument (5).
Let's look at a simpler example of currying:
function add(x) {
return function (y) {
return x + y;
};
}
If you called it with only one argument, like so:
add(2);
It would expand to:
function (y) {
return 2 + y;
}
Which would expect a y argument (if you called it). You could run that like this:
function (y) {
return 2 + y;
}(5)
Or more succintcly:
add(2)(5);
Each function just expands to a new anonymous function when currying, so even though it looks weird, once you expand the code out, it will start to make sense.

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