What is the meaning of for(item of buttons) in Javascript?

let screen = document.getElementById('screen');
buttons = document.querySelectorAll('button');
let screenValue = '';
for (item of buttons) {
    item.addEventListener('click', (e) => {
        buttonText = e.target.innerText;
        console.log('Button Text is ', buttonText);

Please tell me the meaning of for(item of buttons), and the meaning of (e) in the arrow function

for of is a kind of loop, it iterates over the values of an object

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

the e in the loop is the name given to the parameter of that callback function
addEventListener passes an event object to the callback, which includes the target of the event

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

I didn’t understand the item word in the code. There is no such id or attr named item, but It was written in for ,of statement. Does the word ‘item’ is a sort of function or any other thing in JavaScript?

it’s a variable, it can be named anyway you want

1 Like

it’s called a loop statement. In this case it’s a for…of loop (as opposed to a for loop or a while loop or a do…while loop).

for (THING of LIST_OF_THINGS) {
  // do something with THING
  // which is one of the things
  // in LIST_OF_THINGS
}

So item is going to be each of the buttons in turn, one by one.

Loop starts. First button gets assigned to the variable item. Do something with item. Second button gets assigned to the variable item. Do something with item. And so on.

Note the syntax is wrong unless the variable item has already been declared, it should be for (const item of buttons) {


Event listener functions work by taking an identifier for the event you want to listen for (in this case a “click”) plus a function.

When the “click” happens, the function runs.

When the “click” happens, it creates an Event object with useful information about the event. It gets passed to the function that runs, so if you’re going to use it, that function needs to have it as an argument. e is just what that argument has been called.

1 Like

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