user6827598
user6827598

Reputation:

Using a function as a parameter to another function

"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.

Upvotes: 0

Views: 52

Answers (2)

charlietfl
charlietfl

Reputation: 171679

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);

Upvotes: 2

httpNick
httpNick

Reputation: 2624

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.

Upvotes: 2

Related Questions