5

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.
    
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
BVernon
  • 3,205
  • 5
  • 28
  • 64
  • `[].map(function myFunctionName(){})` <-- name – VLAZ May 28 '20 at 05:44
  • 2
    @VLAZ because of scope that may not be accessible anywhere else, but in my understanding that's not an anonymous function since it has a name. By all means please share any evidence to the contrary if my idea of anonymous isn't entirely accurate though. – BVernon May 28 '20 at 05:48
  • 1
    @VLAZ Just double checked, and the book says, verbatim, "As expected, an anonymous function has no name". – BVernon May 28 '20 at 05:52
  • It's a named function expression, yes but there is no "anonymous function" in JavaScript. If we do take it to mean "function without a name" then the actual number of things that fall into this category is smaller than expected `var myFunc = function() {}` for example is not *explicitly* named but it *does* have a name. It takes it from the identifier it's assigned to. There is no real difference semantically from a named or non-named function expression aside from being able to call it from within. – VLAZ May 28 '20 at 05:53
  • @VLAZ Right, there's a webpage that addresses that very issue here: https://blog.scottlogic.com/2011/06/10/javascript-anonymous-functions.html. However, consider the verbatim text of the book I'm reading which I just shared above... and also the text of the answer which says "B. Incorrect: Anonymous functions don't have a name." And then consider the nature of my question... I'm not *just* asking if D would be the correct answer outside of the context of the book, but rather within the context I provided given by the book. – BVernon May 28 '20 at 05:57
  • 3
    What does D even mean actually? – Kaiido May 28 '20 at 06:02
  • @Kaiido that is a very good question. I've been trying to figure out what they mean by "*can’t be assigned to a DOM element declaratively*" and I really don't understand. – VLAZ May 28 '20 at 06:03
  • @VLAZ They mean you can't assign an anonymous function via CSS or in HTML. I think it could be argued that whatever you assign to an event in HTML is intrinsically an anonymous function by definition... but I can also see from their perspective that `onclick = "function() { alert('test');" }` wouldn't accomplish anything. – BVernon May 28 '20 at 06:11
  • Then what is really the relevance of anonymous functions? It seems like a very strange thing to examine on given that they really don't matter. I initially thought that by "anonymous" they meant "function expressions" as there is difference for how they work but anonymous vs named is irrelevant for the majority of time. This question here is might even be the most attention they've gotten ever. – VLAZ May 28 '20 at 06:19
  • @VLAZ Javascript is something I write when I have to though not my strongest skill, but I can say that coming from the perspective of other languages a definition based on having a name is typically both very appropriate and accurate. As for "function expressions" I'm not sure what you mean... in c# that might refer more to the the literal code in the function rather than what the code actually accomplishes. But in any case, the ultimate purpose of this question was to confirm (or reject) my notion that the book is being contradictory or whether I am just misunderstanding something. – BVernon May 28 '20 at 06:33
  • @BVernon a function expression is an actual thing in JavaScript. You have two ways of creating functions - as a *declaration* (a statement) or *expression*. [This question goes into more detail](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname) but there is semantic difference between the two. Names being one - declarations *always* have a name, for expressions the name is optional. If you create an ad-hoc function as a callback `foo(function() {})` then that's an expression. – VLAZ May 28 '20 at 06:37
  • The double negative (“isn’t an attribute”, “can’t be called”) makes it hard to figure out which answers this quiz is looking for, but assuming you understand that A and C are incorrect (i.e. anonymous functions _can_ be called by other code, and they _can_ be passed as… well, _arguments_, actually), it’s unclear why you’d assume B to be correct. – Sebastian Simon May 28 '20 at 07:36
  • 1
    Anonymous functions are called that way (double pun) because they have _no name_. `const myFunc = (0, function(){});` creates a truly anonymous function (`myFunc.name === ""`) via expression (not declaration). _Some_ function expressions have an inferred, _some_ an explicit name. – Sebastian Simon May 28 '20 at 07:36
  • 2
    **D** makes zero sense (so it’s “correct”, but so is “Anonymous functions aren’t cute kittens that save our planet from giant alien robots”). You can’t _assign_ functions to DOM elements. Assignments to DOM nodes fail. What is a _declarative_ assignment? In the context of the book, it appears to refer to DOM events, and what it calls [“Declarative event handling”](https://i.stack.imgur.com/OHQKS.png) is more widely known as _HTML event attributes_ or _inline event handlers_ (bad practice—use `addEventListener` instead). But you _can_ use my `myFunc` example from above: **it’s wrong as well**! – Sebastian Simon May 28 '20 at 08:02
  • 2
    @BVernon Sure, the example (with corrected syntax) `onclick="function(){ alert('test'); }"` doesn’t accomplish anything, but `onclick="(function(){ alert('test'); })();"` does. _That’s_ calling an anonymous function. Your example fails, because the function is just not called. Try `onclick="myNamedFunction"` or `onclick="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. – Sebastian Simon May 28 '20 at 08:11

1 Answers1

3

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>
Gabriel Lupu
  • 1,397
  • 1
  • 13
  • 29
  • Your answer to C contradicts the previous discussion in the comments, although I haven’t clarified that explicitly a year ago: a function expression or declaration has a parameter list, i.e. `function` _⟨parameter list⟩_ _⟨function body⟩_. When invoking the function, an argument list is passed to it. “Passing as parameters” isn’t really a thing. But even if the book meant _arguments_, then your example still passes an anonymous function. `fn.name === ""`. An argument binding like `fn` isn’t a function name; but even if interpreted as such, you can remove `fn` and read `arguments[0]` instead. – Sebastian Simon Apr 24 '21 at 21:01
  • 1
    @SebastianSimon I think he got confused about the question half way through. That is, the question asked which is *wrong* and not which is right. I think he forgot that. When I selected this as the answer, I think I must have overlooked that or I would have mentioned it. Nonetheless, if you take this into consideration, I believe he is otherwise correct. – BVernon Aug 08 '22 at 06:20