The following is a practice question for a Javascript exam followed by the answer.
I am confused because my initial reaction was to choose B. I understand that D is also correct, but when I am taking timed exams I will sometimes stop reading the rest of the answers if I find what I believe is a correct answer (depending on how confident I am it is correct). In this case, I was supremely confident that B was a correct answer.
I am still trying to figure out why I was wrong for picking B, and the "answer" only seems to confirm my choice. Am I taking crazy pills (i.e. how am I misreading this???)? Or is this just a mistake in the book I'm reading?
Which of the following isn’t an attribute of an anonymous function?
A. Anonymous functions can’t be called by any other code. B. Anonymous functions have a clearly defined name. C. Anonymous functions can be passed as parameters. D. Anonymous functions can’t be assigned to a DOM element declaratively
Correct answer: D
A. Incorrect: Anonymous functions can’t be called. B. Incorrect: Anonymous functions don’t have a name. C. Incorrect: Anonymous functions can be passed as parameters. D. Correct: Anonymous functions can’t be assigned to a DOM element declaratively.
addEventListenerinstead). But you can use mymyFuncexample from above: it’s wrong as well!onclick="function(){ alert('test'); }"doesn’t accomplish anything, butonclick="(function(){ alert('test'); })();"does. That’s calling an anonymous function. Your example fails, because the function is just not called. Tryonclick="myNamedFunction"oronclick="function myNamedFunction(){ alert('test'); }"— two named functions that don’t accomplish anything in their context. So anonymous functions can absolutely be called within HTML event attributes.