Ckoh
Ckoh

Reputation: 51

pset8; cs50; javascript; when to use a named function and when to use an anonymous function in callback

In pset8, I have thought out 2 solutions for showing the information window when the user clicks on the marker.

 google.maps.event.addListener(marker, 'click', function() {
            showInfo(marker, articlesContent);
};

and

google.maps.event.addListener(marker, 'click', showInfo(marker, articlesContent));

why does the former/latter work or not work? I mean isn't showInfo also a function? Then why do you need to come up with another anonymous function to call the other function?

Apologies if this a newbie kind of mistake but I am completely new to Javascript and have been struggling for days for this pset. Would appreciate if someone could help me out!

Upvotes: 1

Views: 118

Answers (1)

Felipe Freitag Vargas
Felipe Freitag Vargas

Reputation: 61

In the first case, you are passing the function as a parameter. In the second case, you are calling the function.

Example of the first case: https://jsfiddle.net/anqpby6s/

document.getElementById("myBtn").addEventListener("click", function(){
    alert("Hello World!");
});

Notice the alert is called only when you click the button.

Example of the second case: https://jsfiddle.net/bwsps4b8/

document.getElementById("myBtn").addEventListener("click", alert("Hello World!"));

Notice the alert is called immediately when the code is run - that is not what you want.

You can research about Javascript Callbacks to go further into it, I found this in-depth article in a quick search: http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/

Upvotes: 3

Related Questions