BVernon
BVernon

Reputation: 3757

Javascript practice test question: anonymous functions

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?

  1. 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
    

  1. 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.
    

Upvotes: 5

Views: 2195

Answers (1)

Gabriel Lupu
Gabriel Lupu

Reputation: 1447

You obviously picked the wrong book, I wouldn't dwell to much on it.

  • A: Anonymous functions can’t be called by any other code. not correct. Functions that cannot be invoked? What's the point?

  • B: Anonymous functions have a clearly defined name. Couldn't have been the correct answer because 'anonymous' and 'clearly defined name' are kind of opposites.

  • C: Anonymous functions can be passed as parameters. Seems to be the correct answer: function named(fn) { console.log(fn()) } Named function being invoked using an anonymous function as it's argument:

    named(function() { return 'anonymous response' }) will log anonymous response.

  • D can be true & not true depending on interpretation:

    • true: If you pass to an a tag onClick="" prop a function like this () => alert('This will not work!') it won't work;
    • false: It works if you pass to an a tag onClick prop a function like this (() => alert('This works!'))() (try running the bellow snippet inside an html file)

<a href="#" onclick="(() => alert('This works!'))()">Click Me</a>

Upvotes: 3

Related Questions