Call back function

I am not getting the call back function topic .I read it on the codeacademy many time but still not able to solve the tasks .What should I do ?Suggest some sources if any to get that topic with ease .

Is call back function something like Reccursion??

No, a callback function is one which is passed to another function as an argument.

If you consider the .forEach() iterator method that you can use on an array:

let myArray = [2,4,6,8,"motorway"];

myArray.forEach(item => {
    // this is the callback function
    console.log(item);
}

here we have defined the callback function inside the call to the .forEach() method. The callback could be written separately.

function myCallback(item) {
    // this is the callback function
    console.log(item);
}

let myArray = [3,5,7,9,"double white line"];

myArray.forEach(myCallback);
1 Like

Hi
This exercise highlighted something i’ve been struggling with.
In the bottom example you had the following code:

myArray.forEach(myCallback);

Why does the function myCallback not need parentheses in this case?

I would have expected myArray.forEach(myCallback())

I’m working on the following exercise and through watching the instructor do it he omitted the parentheses and tried to explain why but i didn’t understand
keyPlay, keyReturn and eventHandler are all functions that have been defined in the code:


// Write a named function with event handler properties

const eventHandler = function(note) {

note.onmousedown = keyPlay;

note.onmouseup = keyReturn;

};

// Write a loop that runs the array elements through the function

notes.foreEach(eventHandler);

In JavaScript, functions are objects. The parentheses will call (or run) the function - omitting them will just return the code you wrote inside the function.

function sayHello() {
	console.log('hello');
}

sayHello(); //  calls the function and prints 'hello'

let greet= sayHello; // sets greet equal to the code in sayHello

greet(); // calls the function and prints 'hello'

In this example you are passing the code of the function:

And here you are calling the function getting the return value of myCallback():

This is saying set note.onmousedown equal to the code inside of keyPlay, like how I set greet to sayHello in the first example.

2 Likes

Really helpful, thank you.
Makes sense now.

1 Like