Using a function as a parameter to another function - javascript

"use strict";
function square(x) {
return x * x;
}
function add(square,y) {
return square(4) +y
document.write(square + y)
}
add(4,1);
console.log(add(4,1));
I have to use a function as in the parameter of another function. I am trying to output 17.

Just call it as such:
add(square,1);
you may also want to change
function add(square,y) {
return square(4) +y
document.write(square + y)
}
to be:
function add(square,y) {
document.write(square(4) + y)
return square(4) +y
}
Per Andrew's comment, it might also be a good choice to change document.write calls to be console.log and open the browser console to read results.

Probably easier to visualize if you change the argument name in your function declaration to be more generic but also more identifiable as a function requirement.
The name you use here is not relevant to the name of the function you will actually pass in
function add(func, num) {
document.write(func(4) + num);
return func(4) + num;
}
add(square,1);
Then in another call you might do
add(myOtherCalcFunction, 6);

Related

How to pass functions as Arguments to another function in Javascript?

I have two functions, One function name is funOne. Another function name is funTwo.
Now I have done simple addition in funOne function and funTwo function.
Now I am trying to pass these funOne and funTwo functions as arguments to another function but output is not coming. Please correct my code to get output.
function fun(funOne, funTwo) {
return (funOne + funTwo)
function funOne(a, b) {
return (a + b)
}
funOne(1, 2)
function funTwo(x, y) {
return (x + y)
}
funTwo(3, 4)
}
console.log(fun)
Is this how you want your result ?
function fun(funOne, funTwo) {
return (funOne + funTwo)
}
function funOne(a, b) {
return (a + b)
}
function funTwo(x, y) {
return (x + y)
}
console.log(fun(funOne(1, 2), funTwo(3, 4)))
1- Putting return as first staement will never execute your other lines.
2- If you log a method in console.log without calling () then it will print whole method
3- QUESTION HEADLINE doesn't makes sense. If that is what you are trying to learn then please look Pass a JavaScript function as parameter

Difference between js functions by using parameters

What's the difference between:
// Example 1 sum(8,2)
console.log(sum(8,2)); // Outputs what??
// Example 2 sum(8)(2)
console.log(sum(8)(2)); // Outputs what??
function sum(x,y) {
return x+y;
}
function sum(x) {
return function(y){
return x+y;
}
}
Why is one used over the other and why?
What you are trying to do is called Function Currying
Try this:
function sum(x) {
return function(y) { return x + y; }
};
var sumWith4 = sum(4);
var finalVal = sumWith4(5);
finalVal = sumWith4(8);
One of the advantages is that it helps in reusing abstract function. For example in the above example I can reuse sumWith4 to add 4 to any number with out calling sum(4,5) explicitly. This was a very simple example. There would be scenarios where in part of the function would be evaluated based on the first param and the other part on the second. So you can create a partial function by providing it with the first param and then reuse the partial function repeatedly for multiple different second params.
I will be assuming that you mean to ask the difference between the invocation of functions which appear like:-
someFunction(x, y)
someFunction(x)(y)
This happens with the use of Closures which happens to be a concept wherein an inner function can carry the environment in which it was created.
var sum = function (x){
return function(y) {
return x+y;
};
};
var addWith5 = sum(5);
/*
This will return a function and not a value
addWith5 = function(y){return 5+y;};
*/
console.log(addWith5(5)); // this will return 11
/*
You can also use add function directly
*/
console.log(sum(5)(6)); // this will return 11
/*
The function returned by sum(5), gets called with the parameter (6)
*/
//Try using this, to make it more clear
function a(x){
return x;
}(5);
// returns 5
EDIT
Removed "closures is a JS concept."

JS Function With Two Parentheses and Two Params

I'm trying to understand how a function works that is run with two parentheses and two parameters. Like so:
add(10)(10); // returns 20
I know how to write one that takes two params like so:
function add(a, b) {
return a + b;
}
add(10,10); // returns 20
How could I alter that function so it could be run with one set of parameters, or two, and produce the same result?
Any help is appreciated. Literally scratching my head over this.
Thanks in advance!
How could I alter that function so it could be run with one set of parameters, or two, and produce the same result?
You can almost do that, but I'm struggling to think of a good reason to.
Here's how: You detect how many arguments your function has received and, if it's received only one, you return a function instead of a number — and have that function add in the second number if it gets called:
function add(a,b) {
if (arguments.length === 1) {
return function(b2) { // You could call this arg `b` as well if you like,
return a + b2; // it would shadow (hide, supercede) the one above
};
}
return a + b;
}
console.log(add(10, 10)); // 20
console.log(add(10)(10)); // 20
I said "almost" above because just because the add function received only one argument, that doesn't guarantee that the caller is going to call the result. They could write:
var x = add(10);
...and never call the function that x now refers to.
Welcome to the wonderful world of first order functions
In JavaScript, a function can return a function since a function is just another object. A simple implementation is something like:
function add(x){
return function addOther(y){
return x + y;
};
}
This is possible because of closures and first order functions.
This also lets you do partial application, libraries like Ramda utilize this to great extent.
var addThree = add(3)
addThree(5); // 8
To extend what both T. J. Crowder and Benjamin Gruenbaum said, libraries like Ramda (disclosure: I'm one of the authors) allow you to convert a simple function like this:
function add(a, b) {
return a + b;
}
into the style under discussion by wrapping it in a call to a curry function:
var add = R.curry(function add(a, b) {
return a + b;
});
add(3, 5); //=> 8
add(3)(5); //=> 8
var add3 = add(3);
add3(5); //=> 8
The best article I know on this subject is Hugh Jackson's Why Curry Helps. I wrote a more detailed one at Favoring Curry.
Update
Here is a version of curry somewhat simpler than the one in Ramda. It would do the above and quite a bit more, but doesn't do some of the things that Ramda does with placeholder values:
// here is a function that takes a function and returns a curried version
// of it, that is, a version that performs the sort of partial application
// you describe.
var curry = function(fn) {
// first, we detect how many arguments the function has.
var fnArity = fn.length;
var partialApply = function(args) {
// now, let's create a function that's curried
return function () {
// collect the previous args as the partial, and add the new
// ones you just received
var newArgs = (args || []).concat([].slice.call(arguments, 0));
// if we have "enough" arguments, we don't need any more partial
// application and we can call the function.
if (newArgs.length >= fnArity) {
return fn.apply(this, newArgs);
} else { // else we return a partially applied version
return partialApply(newArgs);
}
};
};
return partialApply([]); // a function is itself partially applied with 0 args
};
function add() {
var sum = 0;
for (var i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
function total() {
for (var i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return total;
}
total.toString = function () { return sum };
return total;
}
This will work for any no of arguments and parentheses.
https://medium.com/#imdebasispanda/super-function-with-closure-86a58a9a980b

Adding functions with arguments to javascript array and then executing them

I have a function as below:
function callme(x,y) {
return function() {
console.log("value of x = " + x);
console.log("value of y = " + y);
}
}
I would like to add the above function to an array and then execute them
var steps = [];
steps.push(callme(1,2));
steps.push(callme(2,3));
steps[0]; // should execute first function
steps[1]; // should execute second function
For some reason the parameters I am passing to the function are not getting stored.
Anyone anyclues as to what I might be doing wrong ?
You're not actually calling the methods. Calling methods involves using the bracket syntax as shown below:
steps[0](); // should execute first function
steps[1](); // should execute second function
Edit
Jared has kindly worked up a JSFiddle.
Second Edit
In your comments you've asked for added callback functionality. Even though this should probably be a separate question, I'll throw a bone for now:
function callme(x, y, callback) {
return function() {
console.log("value of x = " + x);
console.log("value of y = " + y);
callback();
}
}
I'm assuming you'll want to call the functions programmatically in order (from your array), so you'll probably need something like this:
var steps = [];
steps.push(callme(1, 2, next));
steps.push(callme(2, 3, next));
var i = -1;
function next(){
i++
if(i < steps.length){
steps[i]();
}
}
next();
It should be noted though that this sort of sequential calling of methods can be a slippery slope. Mainly because your callback method is being called before the last callback has finished executing, leading to possible stack overflow errors.
You're better off looking into design patterns: middleware and promises is a good place to start.
you should call like this
steps[0]();
steps[1]();
In order to execute each function, you need to invoke it.
So this line steps[0] should actually look like this steps[0]()
EDITED. Bad answer on my part as I somehow overlooked the fact that callme() indeed returns a function.

Returning functions in javascript, understanding scope & closures

I was looking at Mozillas developer site on javascript closure and they had this example of code.
function makeAdder(x){
return function (y) {
console.log(y + " this is y")
console.log(x + " this is x")
return x + y;
}
}
var add10 = makeAdder(10);
console.log(add10(2)); // 12
Now i understand the X attribute being set but what i dont get is how the scope of the y is being affected. I know its a return function but my brain went to mush trying to visualise how you could set a y when there was no ref to it. could someone explain?
makeAdder returns a function to which you can pass the y parameter. It is set at the time of invocation, as opposed to x which is set at the time of creation of the new function (at the time of the invocation of makeAdder).
For the case of this example, the output is equivalent to having written:
function add10(y) {
return 10 + y;
}
console.log(add10(2)); // 12
Nothing new is going on here. The sample code is mainly trying to illustrate that a closure is being created for x.
So makeAdder, here, is aptly named: when you pass 10 to it, it gives you a function that will add 10 to everything you pass to that new function.
var add10 = makeAdder(10);
var add20 = makeAdder(20);
console.log(add10(1) + add20(1)); // 32
Surely, for the purpose of adding, it might be easier to just have a function that accepts two parameters and adds them. But this is not a lesson in adding, it is a lesson in closures.
A real world scenario might be something like this:
var buttons = document.getElementsByClassName('myButton');
for(var i = 0; i < buttons.length; i++) {
buttons[i].onclick = function() {
alert('You clicked button ' + i);
};
}
In the above code, i will have iterated through the entire set before any of the buttons are clicked. Therefore, all buttons will alert whatever buttons.length is. Instead, you could do the following:
var makeAlert = function(x) {
return function() {
alert('You clicked button ' + x);
};
};
for(var i = 0; i < buttons.length; i++) {
buttons[i].onclick = makeAlert(i);
}
The difference here is that i is not being used when the button is clicked (which will be after the entire iteration), but it is used during the iteration, at a time when i will
have a different value for each button.
Instead of creating a variable, makeAlert, you will often see this type of code being written as an anonymous function, invoked immediately. The code below is essentially equivalent to the code above:
for(var i = 0; i < buttons.length; i++) {
buttons[i].onclick = (function(x) {
return function() {
alert('You clicked button ' + x);
};
})(i);
}
What you're asking for is a function that does something for you:
function giveMeAFunctionThatBeeps(){
return function () {
alert('Beep!');
}
}
var beeper = giveMeAFunctionThatBeeps();
beeper(); // beeps!
The actual giveMeAFunctionThatbeeps is just a factory that gives you a function that does what you want.
In the example they have provided, you're doing the same thing as the beeper but you're also passing in a value:
function giveMeAFunctionThatBeepsANumber(x){
return function () {
alert('Beep ' + x);
}
}
This returns a beeper (it's a factory remember), but the beeper alerts the value of x.
However, this value is set when you first create the beeper:
var beeper = giveMeAFunctionThatBeeps(5);
beeper(); // beeps 5!
The beeper is stuck beeping the value 5 now, and we can't do anything about it.
The next example is if you want to create a beeper that beeps any number:
function giveMeAFunctionThatBeepsANumber(){
return function (x) {
alert('Beep ' + x);
}
}
var beeper = giveMeAFunctionThatBeeps();
beeper(6); // beeps 6!
beeper(7); // beeps 7!
As now we're asking the factory to give us a function we can plug a number into.
Then lastly, the original example, is both of the above combined:
function giveMeAFunctionThatBeepsANumber(x){
return function (y) {
alert('Beep ' + (x + y));
}
}
var beeper = giveMeAFunctionThatBeeps(2);
When we create the beeper, we're passing in 2. Remember as above, we can't change this afterwards! It will always beep 2...
...but because it's a factory (preconfigured with value 2) returning a function that takes a parameter, we can customise it when we run it:
beeper(6); // beeps 8! because x was set when we created it, and y is what we pass in.
Functions can be seen as special objects that contain executable code as well as properties. Every function has a special [scope] property that represents the environment it was in when it was defined. If a function is returned from another function then this reference to the old environment is closed over by the new function in a "closure".
so when you call var add10 = makeAdder(10) what happens is that the returned function's x has the value 10 which is bound to it's scope, and the call console.log(add10(2)) prints 12.
Consider reading this article for visualizing what are closures. A more detailed explanation of closure could be found here.
The function makeAdder returns a function when it is called. This function that makeAdder returns accepts one parameter; which is called y.
The variable y exists only during the invocation of the function returned by the makeAdder. It is created each time is is called, and is destroyed when the function returns.
The variable x on the other hand is created when makeAdder is called, and persists due to the closure created by the function makeAdder returns. It will be destroyed when no more references to the function returned exists.
So add10 = makeAdder(10); is actually returning this function:
function(y) {
console.log(y + " this is y")
console.log("10" + " this is x")
return 10 + y;
}
Then add10(2) is calling that function, replacing y with 2 everywhere:
console.log("2" + " this is y")
console.log("10" + " this is x")
return 10 + 2;

Categories