Why JavaScript Promise Executes Before setTimeout (Event Loop Explained) ?

Many JavaScript developers expect setTimeout(fn, 0) to run before everything else.

But when Promise and setTimeout are together, the output often surprises people.

Let’s understand this using a simple quiz example and a step-by-step explanation.


πŸ“Œ The Code (Quiz Question)

console.log("Start");

setTimeout(() => {
  console.log("Timeout");
}, 0);

Promise.resolve().then(() => {
  console.log("Promise");
});

console.log("End");

❓ Question:

What will be the output?

A) Start End Timeout Promise
B) Start Promise End Timeout
C) Start End Promise Timeout
D) Start Timeout Promise End

βœ… Correct Answer: C) Start End Promise Timeout


🧠 Step-by-Step Execution (Very Important)

To understand this output, you need to know how JavaScript event loop works.

JavaScript uses:

  • Call Stack
  • Microtask Queue
  • Task Queue
  • Event Loop

Let’s go line by line.


πŸ”Ή Step 1: Synchronous Code Runs First

console.log("Start");

➑️ Output:

Start


πŸ”Ή Step 2: setTimeout Goes to Task Queue

setTimeout(() => {
  console.log("Timeout");
}, 0);

Even with 0ms, the callback:

  • Does NOT execute immediately
  • Goes to the Task Queue

πŸ”Ή Step 3: Promise Goes to Microtask Queue

Promise.resolve().then(() => {
  console.log("Promise");
});

This callback goes into the Microtask Queue.

⚠️ Important:

Microtasks always have higher priority than tasks.


πŸ”Ή Step 4: Continue Synchronous Code

console.log("End");

➑️ Output so far:

Start
End


πŸ”Ή Step 5: Event Loop Priority Rules

After synchronous code finishes:

1️⃣ Event loop executes all microtasks first
2️⃣ Then executes tasks (setTimeout)

So execution order:

  • Promise callback
  • setTimeout callback

🧾 Final Output

Start
End
Promise
Timeout

βœ”οΈ Correct option: C


⚑ Key Rule to Remember (Interview Gold)

Microtasks (Promises) always run before Macrotasks (setTimeout).


🧠 Simple Real-World Analogy

Imagine a company office 🏒

  • Regular tasks β†’ Emails (setTimeout)
  • Urgent tasks β†’ Phone calls (Promise)

Even if email is scheduled early, phone calls are answered first.

πŸ‘‰ Promise = urgent
πŸ‘‰ setTimeout = regular


❌ Common Misunderstanding

❌ setTimeout(fn, 0) runs immediately
❌ Promise waits for setTimeout

βœ… Truth:

  • Promise β†’ Microtask queue
  • setTimeout β†’ Task queue
  • Microtasks always win

🎯 Interview Tip

If asked:

β€œWhy does Promise execute before setTimeout?”

Answer:

Because Promise callbacks go into the microtask queue, and the event loop always processes microtasks before macrotasks.

React useEffect Explained Clearly (With Simple Examples)

If you are learning React, chances are useEffect confused you at least once.

Questions like:

  • Why does useEffect run twice?
  • When should I use it?
  • What is dependency array?
  • How is it different from lifecycle methods?

Don’t worry.
In this post, I’ll explain useEffect in the simplest way possible, using real-world analogies and clear examples.


What is useEffect in React?

πŸ‘‰ useEffect is used to perform side effects in React components.

Side effects include:

  • Fetching data from an API
  • Updating the DOM
  • Setting timers
  • Subscribing to events
  • Logging data

Simply put:

useEffect runs code when something changes in your component.


Basic Syntax of useEffect

useEffect(() => {
  // side effect code
}, []);

It has two parts:

  1. Effect function – what you want to do
  2. Dependency array – when you want to do it

Case 1: useEffect Without Dependency Array

useEffect(() => {
  console.log("Component rendered");
});

What happens?

βœ… Runs after every render

⚠️ Usually not recommended, can cause performance issues.


Case 2: useEffect With Empty Dependency Array []

useEffect(() => {
  console.log("Component mounted");
}, []);

What happens?

βœ… Runs only once, after first render

Equivalent to:

componentDidMount()

πŸ‘‰ Most common use case: API calls


Example: Fetching Data

useEffect(() => {
  fetch("/api/users")
    .then(res => res.json())
    .then(data => setUsers(data));
}, []);

βœ”οΈ Fetches data only once
βœ”οΈ Avoids infinite loops


Case 3: useEffect With Dependencies

useEffect(() => {
  console.log("Count changed");
}, [count]);

What happens?

βœ… Runs only when count changes

πŸ‘‰ Useful for reacting to state or prop changes


Example: Search Input

useEffect(() => {
  fetchResults(searchText);
}, [searchText]);

βœ”οΈ Runs only when user types
βœ”οΈ Optimized & efficient


Cleanup Function in useEffect 🧹

Some effects need cleanup.

Example:

  • Timers
  • Event listeners
  • Subscriptions
useEffect(() => {
  const timer = setInterval(() => {
    console.log("Running...");
  }, 1000);

  return () => {
    clearInterval(timer);
  };
}, []);

πŸ‘‰ Cleanup runs when:

  • Component unmounts
  • Dependencies change

Why Does useEffect Run Twice in React?

In React Strict Mode (development):

  • React runs effects twice
  • This helps detect bugs

🚨 It does NOT happen in production


Common Mistakes with useEffect ❌

❌ Missing dependency array

useEffect(() => {
  setCount(count + 1);
});

➑️ Causes infinite loop


❌ Incorrect dependencies

useEffect(() => {
  fetchData();
}, []);

But fetchData uses props/state β†’ bug!


When Should You Use useEffect?

Use useEffect when:
βœ… You interact with outside world
βœ… You perform side effects
❌ Not for simple calculations


Summary Table πŸ“Œ

ScenarioDependency
Run once[]
Run on every renderNo array
Run on change[state/props]
Cleanup neededreturn () => {}

Final Thoughts

If you remember just one line, remember this:

useEffect syncs your React component with the outside world.

Mastering useEffect will:

  • Improve performance
  • Prevent bugs
  • Make you a better React developer

How to convert first letter of the word to UpperCase in JavaScript ?

We can convert the first letter of the word to uppercase by using chatAt and slice methods as follows.

Here, charAt(0).toUpperCase will convert the first letter of the word to uppercase and word.slice(1) will return the remaining characters of the word except first letter.

How to find smallest number with the highest frequency in the array ? – JavaScript

We have multiple approaches to find smallest number with the highest frequency.

1. Using Object.entries :

Explaination:

We got output as 2 because 2 appeared three times (2’s frequency is three). for 3 also we are having frequency three. But we need to find the smallest number with the highest frequency. So Answer is 2.

Above code gives output as { ‘1’: 2, ‘2’: 3, ‘3’: 3, ‘4’: 2, ‘5’: 1 }. Here this object is in the form of key, value pairs, Where Keys are the given numbers in the array and values are their counts. acc[val] || 0 returns undefined values as 0 and + 1 increments the count.

When we wrap the above code inside Object.entries, it returns an Array of arrays as follows. [ [ ‘1’, 2 ], [ ‘2’, 3 ], [ ‘3’, 3 ], [ ‘4’, 2 ], [ ‘5’, 1 ] ]

Finally we are finding highest frequency. If multiple numbers have the same frequency then we are choosing the smallest number by applying the reduce method.

Above code gives output as [ ‘2’, 3 ]. From here we need to extract the value 2. So we are using [0]. and it will give ‘2’ and then finally we are converting string to number by using console.log(Number(result)).

2. Using step by step Approach :

The following code counts frequency and gives this output : { ‘1’: 2, ‘2’: 3, ‘3’: 3, ‘4’: 2, ‘5’: 1 }

Next we will find max frequency which is 3 with the following line of code

Finally we will filter by max frequency and find smallest number with the following code.

Explain JavaScript Call() method with Examples.

  • The Call method is a predefined javaScript method.
  • In JavaScript, the call method is used to invoke(call) a function with a specified this context and arguments provided individually.

Example 1 : (Using Call() method to invoke a function and specifying the this value )

Example 2 : (Using Call() method to invoke a function without first argument)

Note: If we are omitting the first parameter, then it returns undefined.

Example 3 : (Using Call() method to invoke a function without first argument But with globalThis)

Example 4 : (Using Call() method to invoke a function with multiple arguments)