Is onEvent() a function

Does a onEvent() that only has code in it count as a function or does the onEvent() need to directly call a function

I’m not sure I understand your question. Also, is there a context behind your question? If I’m interpreting correctly, it sounds like you are asking what usage (if any) of onEvent() would qualify it as a function definition/call.

I don’t have an answer for that (partially because I’m still not sure I understand the question), but if someone else is to answer, perhaps some confusion comes from how creating a new onEvent block automatically includes a function block inside it. Why it does that is a mystery to me (probably related to the actual JavaScript language, which I’m not familiar with outside this curriculum).

@ccollica jumping in here to see if I can help.

The onEvent() block takes three parameters. The first two are the id of the element and the type of event that should be “listened” for. The third parameter is a function. If you were going to read the onEvent block like a sentence it would read “on the event that this id experiences this event, call this function”.

In our curriculum this usually looks like this

and you’re probably wondering what that green function() is doing there. By using that syntax you are creating a function without a name that the onEvent() block can call. This is really useful if you’re only going to want to use that function one time, at this point in your code. To answer your question, yes, it is a function, but it’s a very specific kind called an “anonymous function” since it has no name and therefore can’t be called elsewhere in your program.

If you wanted to, you can actually call functions you’ve explicitly declared (and therefore named) elsewhere in your program. For example you could rewrite the code above like this

In this example the makeSomeNoise function will be the one called by the onEvent() block, but you have the added benefit that you could use makeSomeNoise() elsewhere in your program if you wanted to. Note the weird syntax in this example, however, where you don’t use the parentheses.

In short, yes, an onEvent() block is always calling a function, it’s just that usually in our curriculum it’s an anonymous function that is created once and not named inside the onEvent() itself.

Let us know if you need further clarification!

4 Likes