A callback is a function which is passed to another function as an argument and which is called from within it to continue the program. You're missing that callback function in your code. That's the simple bit.
Now, this sentence from your question needs a little more work:
a function that takes two numbers and has a callback that returns the last item
This is certainly fine for cases such as your example where there are no asynchronous processes involved...
const items = ['Pencil', 'Notebook', 'yo-yo', 'Gum'];
function last(arr, cb) {
const el = arr[arr.length - 1];
return cb(el);
}
const lastItem = last(items, function print(el) {
return `Last element is ${el}`;
});
console.log(lastItem);
...but generally you'll see that callbacks are primarily used to continue the flow of code after an asynchronous process has run, and you can't return values from a callback in that situation.
For example in this example we're using a setTimeout
to delay calling the callback for 2s:
const items = ['Pencil', 'Notebook', 'yo-yo', 'Gum'];
function last(arr, cb) {
const el = arr[arr.length - 1];
setTimeout(() => {
cb(el);
}, 2000);
}
last(items, function print(el) {
console.log(`Last element is ${el}`);
});
We're not returning anything because returning the setTimeout
makes no sense, neither does returning the callback from within the setTimeout
. Instead we call the callback with the value after 2s and the string is logged to the console.
It means that we can't return a value to a variable like we did with lastItem
in the first example, and the reason why "How do I return the response from an asynchronous call" is likely the most linked question on this site, and it was important that you understood that for your understanding of callbacks.
So, while you can return values from callbacks they are generally used continue the execution of a program after an async process.
Hope that helps.