jan
jan

Reputation: 255

Higher Order Functions and Passing Functions as Arguments

I'm new in JavaScript and just trying to figure out abut this code of line.

As far as I know, the word operator is just a random word that could have been anything. But how does it know that the users is referencing to the word add/subtract/multiply/divide when those word also could have been anything else, and lets say its a bunch of other function in that .js file. How does operator return the right inputs?

function add(num1, num2) {
    return num1 + num2;
}
​
function subtract(num1, num2) {
    return num1 - num2;
}
​
function multiply(num1, num2) {
    return num1 * num2;
}
​
function divide(num1, num2) {
    return num1 / num2;
}
​
function calculator(num1, num2, operator) {
    return operator(num1, num2);
}

Upvotes: 0

Views: 360

Answers (3)

paulsm4
paulsm4

Reputation: 121649

You need to call calculator to actually do anything.

See if this snippet helps:

function add(num1, num2) {
  return num1 + num2;
}
 
function subtract(num1, num2) {
  return num1 - num2;
}
 
function multiply(num1, num2) {
  return num1 * num2;
}
 
function divide(num1, num2) {
  return num1 / num2;
}
 
function calculator(num1, num2, operator) {
  return operator(num1, num2);
}

var a = calculator(3, 2, add);
var b = calculator(3, 3, multiply);
alert('a=' + a + ', b=' + b);

The key is to understand that in JavaScript, functions (like add) are first-class objects, which can be used as parameters just like integers (2 or 3), strings, etc. You can read more here: What is meant by 'first class object'?.

Upvotes: 0

Lionel Rowe
Lionel Rowe

Reputation: 5926

operator could be any function, not just one of the ones listed there. It could even have side effects. It all depends how calculator is called.

For example:

// exactly the same `calculator` function
function calculator(num1, num2, operator) {
    return operator(num1, num2)
}

// new `write` function
function write(num, fontSize) {
    document.write(`<span style="font-size: ${fontSize}px">${num}</span>`)
}

// execution happens here
calculator(99, 200, write)

Upvotes: 0

Robo Robok
Robo Robok

Reputation: 22683

It's the same as just using the variable under any name:

function foo(bar) {
    return bar + 1;
}

const something = foo(123); // 124

You use the bar name inside function, even though the external context doesn't know anything about that name.

In JavaScript you can pass function as any other values, which is makes it possible, for example, to use functions inside other functions:

function zoo() {
    return 3;
}

function foo(bar) {
    return bar() + 1;
}

const something = foo(zoo); // 4

Inside foo(), we call the something() function, even though foo() doesn't know anything about that function. It's all about the context and passing values.

Upvotes: 0

Related Questions