Why using ".addEventListener()" makes my variable "undefined"?

I'm practicing in using this method and try to output my variable "button"

let button = document.querySelector(“button”).addEventListener(“click”, e => {
e.preventDefault();
console.log(“hello”);
});

console.log(button);

.addEventListener() method doesn’t return element, therefore cannot be used in a chain, more specifically it returns undefined and hence your button is undefined. Try separating the chain:

let button = document.querySelector('button');
button.addEventListener('click', (e) => { ... });
button.click();
1 Like