In the first example, you create a named function. The name of the function is FirstNameFunction.
In the second example, you create an anonymous function (a function that does not have a name). However, you also define a variable called FirstNameFunction that contains a reference to an anonymous function. In this case, FirstNameFunction is not the function itself, but simply a variable that refers to it.
The reason these differences are important when assigning an event handler, as you did on the first line, is because global functions with a name can be referenced from anywhere in the code, if their declaration has been analyzed and interpreted before you try to use them. Variables, on the other hand, can only be used when they are in scope. This means that after they are identified, and before they go out of scope. Therefore, you should be able to use the second declaration method with the appointment of an event handler if you declare a variable that points to an anonymous function before calling the event handler, and you do this in the same area.
It works:
var FirstNameFunction = function (){ alert("Hello"); } PopupFirstNameButton.addEventListener('click', FirstNameFunction, false);
It does not mean:
PopupFirstNameButton.addEventListener('click', FirstNameFunction, false); // FirstNameFunction is undefined!! var FirstNameFunction = function (){ alert("Hello"); }
Also this:
function declareFunction() { var FirstNameFunction = function (){ alert("Hello"); } }
source share