Why does function invocation work differently with variable assignment in JavaScript?

I’m having trouble understanding how function calls work in JavaScript. I have this code that doesn’t seem to work:

var createHandler = function () {
    return function() {
        console.log('Hello World!');
    }
}

createHandler();

But when I modify it like this, it works perfectly:

var createHandler = function () {
    return function() {
        console.log('Hello World!');
    }
}

var myHandler = createHandler();
myHandler();

I don’t understand why storing the returned function in a variable makes it work. What’s the difference between these two approaches? Can someone explain what’s happening behind the scenes?

You’re not actually running the returned function in your first example. When you call createHandler(), it returns a function, but since you’re not storing it or calling it right away, that function just gets thrown away. JavaScript doesn’t automatically run functions just because another function returns them. In your working example, you’re doing two things: getting the function with createHandler(), then running it with myHandler(). Want to skip the variable? Use createHandler()() to immediately call the returned function. This pattern shows up everywhere in JavaScript and will help you understand closures and higher-order functions later.

The difference lies in how you handle the function returned by createHandler(). In the first instance, you invoke createHandler(), but you don’t utilize the function it produces, effectively discarding it. In contrast, by storing that returned function in myHandler and invoking it later with myHandler(), you ensure it executes. Think of createHandler() as a function factory: you must either save what it produces for future use or invoke it immediately using createHandler()(). The placement of parentheses is crucial here—one set calls the outer function, while the other calls the inner one.

ah, i get it! in the first example, createHandler() runs but the returned function is ignored. it’s like making a sandwich but not eating it, haha. you either need to save the output first and then call it, or do createHandler()() to run both at once.