0

Goal

Console must log a message only on clicking the button.


Set-up

const button_l = document.querySelector('.btn-left');

method-1 (Using arrow function as a callback)

button_l.addEventListener('click', () => {
    console.log('I am in')
});

method-2 (Using function as a callback)

button_l.addEventListener('click', changeSlide());

function changeSlide() {
    console.log('Am I globally present?');
}

Problem Facing

  1. Using method-1 gives the desired results.
  2. Using method-2, the function is called on page load, but when I remove the parentheses (from changeSlide() to changeSlide), it functions as it should, why is it so?

I think it is something very fundamentally obvious that I do not know.

I appreciate a link/reference to any helpful theory/understanding.

Ritik Jangir
  • 87
  • 2
  • 11
  • 1
    `button_l.addEventListener('click', changeSlide());` -> `button_l.addEventListener('click', changeSlide);` remove the `()` at the end, otherwise you immediately call the function. – VLAZ Oct 30 '21 at 08:03
  • https://teamtreehouse.com/community/why-do-we-call-the-functions-without-parentheses-ie – Ayush Singh Oct 30 '21 at 08:49
  • Thankyou @AyushSingh I was calling the function and not referencing it. I have a fragmented understanding now, I'll read more about it. :) – Ritik Jangir Oct 30 '21 at 09:22

0 Answers0