'Why doesn't this JavaScript code(embedded as an HTML attribute)work?

Why doesn't this work?

<button onclick = "function(){alert('Hello');}">press me</button>

while this does:

<button onclick = "alert('Hello');">press me</button>


Solution 1:[1]

They both work. The first one defines a function, but doesn't call it. The second one actually calls alert.

If you're trying to define and call an anonymous function, try this:

<button onclick = "(function(){alert('Hello');})()">press me</button>

Solution 2:[2]

Because you're not calling the function--you're defining it.

I don't know why you would, but you could write this:

<button onclick="(function() { alert('Hello'); })()">press me</button>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Elliot Nelson
Solution 2