-3

I'm trying to understand why this code below executes my function as soon as the document is loaded:

var list = document.getElementsByTagName('li');
function yep() {
    window.alert('yep');
}
list[0].onclick = yep();

But this does not:

list[0].onclick = yep;

Why does () make a difference when executing a function in this situation?

Dan Lowe
  • 51,713
  • 20
  • 123
  • 112
Baksa Gimm
  • 123
  • 9
  • 2
    The `()` is how a function is invoked. Just like your `alert('yep')` is doing except no argument. –  Jan 02 '16 at 21:56

3 Answers3

1

Putting () after a reference to a function means that you want to call the function. Leaving them off means you just want to work with the reference to the function as a value in and of itself.

Pointy
  • 405,095
  • 59
  • 585
  • 614
1

yep is a reference to a function.

yep() is a directive telling the Javascript engine to execute the yep function.

That's why one executes immediately and the other does not.

Dan Lowe
  • 51,713
  • 20
  • 123
  • 112
1

The parenthesis () execute function immediately. On your second line you are assigning the value of list[0].onclick to the function name but not executing it.

Ahmad Alfy
  • 13,107
  • 6
  • 65
  • 99