i have a task to do (based on nothing we have learnt.. this is part of the challange, but i cannot do it nor know what i am supposed to search i have tried everything.
this is the task:
/**
* Create a function that accepts two numbers,
* and calls the callback with the sum of those numbers
* @param {number} x
* @param {number} y
* @param {Function} callback
*/
function sumAsync(x, y, callback) {
}
export default sumAsync;
can someone point me to the right direction? are they asking a function inside a function? if so, where can i read about it and know how to do so?
CodePudding user response:
This should work:
/**
* Create a function that accepts two numbers,
* and calls the callback with the sum of those numbers
* @param {number} x
* @param {number} y
* @param {Function} callback
*/
function sumAsync(x, y, callback) {
callback(x y);
}
EDIT:
Explanation:
This will call the function that you set as callback parameter, you can use it as: sumAsync(2, 3, console.log);
so your function will call the callback function (console.log
here) with the parameter x y
, so console.log(x y);
and print 5
.
CodePudding user response:
can someone point me to the right direction? are they asking a function inside a function? if so, where can i read about it and know how to do so?
Javascript allows you to pass functions as variables. What that means is you can create a function and then pass it to another function, which then calls it (this is a 'callback').
function updateString(someString) {
return someString ' - got updated';
}
function modifyString(someString) {
return someString ' - got modified';
}
function complexStringPlusCallback(myString, callbackFunction) {
myString = myString.split().reverse().join();
myString = callbackFunction(myString);
myString = myString.toUpperCase();
return myString;
}
// notice that we pass in `updateString` rather than `updateString()`
console.log(complexStringPlusCallback('abc', updateString));
console.log(complexStringPlusCallback('123def', modifyString));
In this scenario, passing a callback function means we can change the middle part of complexStringPlusCallback
without needing to make two functions (or three if we added a third possible callback).
There are a lot of reasons callbacks are used. They let you pass functions to modules or objects which will call them when an event occurs, for example - so you can have a function be automatically called whenever a user clicks on a button.
If you want further reading on the topic, a function that takes a function as a parameter is called a 'higher-order function'.
I'm going to assume getting the sum of the two numbers is trivial and won't address that part.