Why does it work this way, but not this way?

Why does this code work

function eventAssignment(note) { note.onmousedown = function() { keyPlay(event) } note.onmouseup = function() { keyReturn(event) } }

But this code does not work

function eventAssignment(note) { note.onmousedown = keyPlay(event) note.onmouseup = keyReturn(event) }

The functions keyPlay and keyReturn are already defined as functions, so shouldn’t I be able to call the function with its name and parentheses? Why do I need to include the word function?

1 Like

You should be able to assign the function to the event with es6 syntax’s arrow function like so: () => keyPlay(event)
But the second code doesn’t work mainly because it’s assigning the result of calling the function keyPlay(event) to the event instead of assigning the function itself.
If somehow the function to be assigned returned number 2, then the onmousedown event would get assigned a number instead of a function like it’s supposed to.
I hope I’m not missing any key javascript concept here.

Maybe I’m missing some concepts related to closures or callbacks.

I see what you mean about calling the result of the function instead of the function itself.
Please could you provide a codebyte of how you would do it?

1 Like

So, for the second case I would use ES6’s syntax like this:

function eventAssignment(note) { note.onmousedown = () => keyPlay(event) note.onmouseup = () => keyReturn(event) }

Which assigns an anonymous function to the event, that returns keyPlay(event)

Ah makes sense, thanks i’ll try it out