JavaScript JavaScript and the DOM Responding to User Interaction Listening for Events with addEventListener()

ian izaguirre
ian izaguirre
3,220 Points

Why do we not need to add Let or Const inside the EventListener Function?

I Have Two Questions...

(1) How come the code below works, if inside the function we are assigning a new value to the variable "listItems" ?

let listItems = document.querySelector('li'); 

listItems.addEventListener('mouseover', () =>  {

 listItems.textContent = listItems.textContent.toUpperCase(); // No let ?

});
  • I would have thought the above code would not work and should be written like:
let listItems = document.querySelector('li');

let listItems.addEventListener('mouseover', () =>  {

let listItems.textContent = listItems.textContent.toUpperCase(); // Why is this wrong ?

});

(2)

How do I know which is best to use in this situation since this works:

let listItems = document.querySelector('li'); // Let

and this works:

const listItems = document.querySelector('li'); // Const

Even though inside the function we are assigning a new value to the variable "listItems" ? I guess my second question is related to my first question, since I would have thought const would not have worked in this case, even though it does.

3 Answers

cihangir bozdogan
cihangir bozdogan
12,160 Points

if you use the var/let/const key word once, you won't need to use it inside the other functions and handlers. if you create a variable inside the event handler you should use var/let/const keyword. var / is suitable for general use const / is for declaring the stable variables that we won't change later in our app let/ is the small scope variable. it is great for using inside functions and handlers..

Phillip Kerman
Phillip Kerman
Pro Student 285 Points

There's really no reason to use var anymore--provided you're targeting ES6 or have a compiler that changes it to var. Not like var will hurt you though. It's fair to say "let is the new var".

The harder concept I think is fully understanding scope and why you'd want to put a variable (using let) inside or outside a function.

This question is rather old, but in case anyone still reads it I want to point this out: we are not assigning a new value to the variable "listItems". You are changing the value of the textContent property. You are modifying a property of the object listItems refers to, not the reference itself. This, indeed, would give an error:

const listItems = document.querySelector('li');
//...
listItems = document.querySelector('h1');