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.

Controlled vs Uncontrolled Components in React (Beginner Friendly)

When you start learning React, one of the first confusing topics you’ll face is the difference between Controlled and Uncontrolled Components. Don’t worry — by the end of this post, you’ll understand this clearly with simple examples.


🎯 What Does It Mean?

In simple words:

  • Controlled Component → React is in charge of the input’s value.
  • Uncontrolled Component → The browser (DOM) is in charge of the input’s value.

Think of it like this:

  • In Controlled Components, React acts like a teacher, checking every word you write in your notebook.
  • In Uncontrolled Components, React acts like a teacher who lets you write freely and only checks your notebook at the end.

📝 Controlled Components

In a controlled component, the form input is linked to React state. That means React always knows what’s inside the input, and it updates automatically when you type.

Example: Controlled Input

import React, { useState } from "react";

function ControlledForm() {
  const [name, setName] = useState(""); // React state

  const handleSubmit = (e) => {
    e.preventDefault();
    alert("Submitted Name: " + name);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={name} // value comes from React state
        onChange={(e) => setName(e.target.value)} // update state
        placeholder="Enter your name"
      />
      <button type="submit">Submit</button>
    </form>
  );
}

export default ControlledForm;

👉 Here:

  • The input value is always controlled by React.
  • When you type, React updates the state and then shows the updated value back in the input.
  • React is the single source of truth.

📝 Uncontrolled Components

In an uncontrolled component, the input manages its own value just like in plain HTML. You don’t use state, instead you use a ref to get the value when needed.

Example: Uncontrolled Input

import React, { useRef } from "react";

function UncontrolledForm() {
  const nameRef = useRef(); // reference to input

  const handleSubmit = (e) => {
    e.preventDefault();
    alert("Submitted Name: " + nameRef.current.value);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        ref={nameRef} // React does not control this input
        placeholder="Enter your name"
      />
      <button type="submit">Submit</button>
    </form>
  );
}

export default UncontrolledForm;

👉 Here:

  • The browser keeps track of what you type.
  • React doesn’t know the input value until you read it with ref.
  • DOM is the source of truth.

🔑 Key Differences

FeatureControlledUncontrolled
Value managed byReact stateDOM (browser)
How to read valueFrom stateFrom ref.current.value
React controlHigh (can validate instantly)Low
Use caseValidation, dynamic forms, live feedbackSimple forms, quick data grab

🚀 When Should You Use Which?

  • ✅ Use Controlled Components when you need:
    • Form validation (e.g., check if email is valid while typing)
    • Live updates (e.g., show typed text somewhere else instantly)
    • Complex or large forms
  • ✅ Use Uncontrolled Components when you need:
    • Simple, one-time form submissions
    • Quick prototypes
    • Minimal React state management

🎓 Final Takeaway

  • Controlled → React is the boss. It decides what’s in the input.
  • Uncontrolled → Browser is the boss. React just asks for the value when needed.

👉 As a beginner, it’s usually best to start with Controlled Components because they give you more power and flexibility. But knowing Uncontrolled Components will help you understand how React works with the DOM.


TypeScript: Index signature for type ‘string’ is missing in type …

The error “Index signature for type ‘string’ is missing in type” occurs in TypeScript when we are trying to access a property using a dynamic string, but the object type doesn’t define an index signature to accommodate that.

For Example, The above Error will come in the following scenario

In the above example, typescript throws an error because key could be any string, but the Person type only explicitly defines name and age. To fix this we can add an index signature to the type as follows.

Javascript program to find the sum of elements in a sequence up to a given range.

  • From the above program we need to ensure that the range should not exceed the length of the array. If it is exceeding we will assign the range to the array length.
  • Given range is 5. So the sum of first five elements should calculate as 4 + 7 + 6 + 1 + 2 which is equal to 20.

We can also write this program by using slice and reduce methods as follows

  • Here arr.slice(0, range) extracts the elements from 0 to 5. i.e, [4, 7, 6, 1, 2];
  • reduce method starts with an initial value of 0 and adds each number to the accumulator and returns 20 as the output.

Heart Beat Animation with ReactJS and CSS

Heart.css

/* Align the heart to the center of the page */
.heart-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

/* creating two circles */
.heart::before,
.heart::after {
    content: "";
    width: 100px;
    height: 100px;
    background-color: #e63946;
    position: absolute;
    border-radius: 50%;
}

.heart::before {
    top: -50px;
}

.heart::after {
    left: 50px;
}

/* Creating square */
.heart {
    position: relative;
    width: 100px;
    height: 100px;
    background-color: #e63946;
    transform: rotate(-45deg);
    animation: beat 1s infinite;
}

/* Heart Beat Animation */
@keyframes beat {
    0%, 100% {
        transform: scale(1) rotate(-45deg);
    }
    50% {
        transform: scale(1.2) rotate(-45deg);
    }
}
  • By using div with className(.heart) we have created heart shape
  • By using the div with the className(.heart-container) we have aligned the heart to the center of the page.
  • Heart Shape: We have created the heart by positioning two circular divs (::before and ::after) next to a square div, then rotating the main .heart div by -45deg.
  • Animation: The @keyframes beat animation makes the heart scale up and down, creating a “beating” effect.
  • 0%, 100%: The heart starts and ends at its original scale (1), so it returns to the original size after each beat.
  • 50%: The heart scales up to 1.2 times its original size, creating the “pumping” effect in the middle of each beat cycle.