Is an event listener an expression

I want to have better understanding of the different between function declarations and function expression, in particular when the function expression are used in call backs.

mdn says

The function keyword can be used to define a function inside an expression.

if i write for example

button.addEventListener("click", () =>  {

what is the expression?

mdn says

An expression is any valid unit of code that resolves to a value. so here i guess the event listener is the expression and thats why we can use a function expression inside of it , ie we dont need to write a function declaration ?

All functions are expressions, by definition, they can’t be anything else. Not all expressions are functions (eg example = 2 clearly isn’t a function).

“function declaration” and “function expression” are terms used in JavaScript to distinguish function someFunction() { return thing and const someFunction = function () { return thing; } (or const someFunction = () => thing). They’re both expressions, because they’re both functions. The former is hoisted (JS moves it to the top of the scope, so you can write code that uses the function before it’s defined in the file). With the latter you can omit the name (anonymous functions. Arrow functions cannot be named, so they’re always anonymous funtions). Arrow functions have few other extra rules to do with scope. Otherwise they’re identical for all practical purposes.

1 Like

so technically an eventlistener is a function and therefore an expression?

All functions can contain a callback function.
In your case you have a eventlistener (clicktag):

after Event (in your case its the “click” Event), you start a callback function, this function will run after you have click this element.
In this function you can set “parameters” like this:


This will get the key, which you have clicked on your keyboard.

Becouse its a callback function you can also write like this:

let myFunction = function(para){

This will be the same output

Well, yes.

And it doesn’t make any difference if you use a function declaration or a function expression for the callback: they will do the same thing. It will make a difference if you use an arrow function, but only if you are accessing this or arguments inside the that callback (that is due to the difference between arrow functions and functions declared using the function keyword), otherwise it’s exactly the same in that case as well.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.