Search code examples
javascriptvariablesglobal-scope

Why does the variable executes the window object right away and not store it instead?


I would like to understand what's happening with the code in which a variable is not stored immediately, but instead executed first before it can be called. An example code can be this (in the global scope):

var alertMe = alert("I\'m being executed then stored to be called again, but why?"); 

Solution

  • Because you are storing the result of calling the function, not storing a function.

    This would be what you are after:

    var alertMe = function () { 
            alert("I\'m being executed then stored to be called again, but why?"); 
        };
    

    And then when you want to call it:

    alertMe();