Why Does a Function Execute Immediately with Parentheses, Whereas Without Parentheses, It Waits Within setTimeout()?

Consider this code snippet:

function sayHello() {
  console.log("Hello!");
}

// This line executes sayHello immediately
setTimeout(sayHello(), 4000);

// This line schedules sayHello to be executed after a 4-second timeout
setTimeout(sayHello, 4000);

In this code, sayHello() is called right away, but sayHello is scheduled to run after a 4-second delay. Let's explore why this happens.

Let's break it down.

setTimeout(sayHello(), 4000);

In this line, sayHello() is invoked immediately, and the result (which is undefined in this case, as sayHello doesn't explicitly return anything) is passed to setTimeout.

As a result, "Hello!" is logged to the console instantly, and the setTimeout essentially has no effect regarding the timing.

setTimeout(sayHello, 4000);

In this line, sayHello is passed as a reference to the function without being invoked. This means that the function will only be executed after the specified timeout of 4 seconds.

So, the key difference lies in the parentheses after sayHello. When you use sayHello(), you are calling the function immediately. On the other hand, sayHello without parentheses is just a reference to the function, which can be passed around and executed later.

Learn Higher-Order Functions

Write code that is easier to understand and maintain.

You've heard about higher-order functions, but every explanation you've come across is either too technical or too vague. You're searching for something clear and practical, with examples that will help you practice and truly master the concept.

Higher-order functions are key to writing better code, essential for your projects, and expected in interviews. But getting started can be tough.

But what if you could? What if you had access to easy-to-understand content that not only explains higher-order functions but also provides hands-on practice? You’d finally feel confident using them in your projects, knowing exactly what they do and how to leverage them effectively.

It’s true, finding the right resources to learn higher-order functions can be challenging… but it doesn’t have to be.

Get my guide, where you’ll:

  • Understand why higher-order functions are worth learning and how they can transform your approach to writing JavaScript.
  • Gain clarity as I break down higher-order functions into simple, everyday language.
  • Master three important higher-order functions: map, filter, and reduce, with plenty of examples to solidify your understanding.
  • Apply your knowledge with real-world examples that demonstrate how these concepts work together, so you can use them easily in your projects or write better code in your interviews.

Get the Guide