Skip to main content

Python type() Function

When learning Python, you will work with different types of data, such as numbers, text, decimal values, and Boolean values. Python provides several built-in functions to help you work with these data types. One of the most useful functions is the type() function . The type() function tells you the data type of a value or variable. It helps you understand what kind of data Python is working with and can make debugging your programs easier. For example, consider these variables: age = 20 price = 99.50 name = "Rahul" is_student = True Although all four variables store data, their data types are different. Python allows us to check these types using type() . Let's understand how it works with simple examples. 1. What Is the type() Function in Python? The type() function is a built-in Python function that returns information about the type of an object. In beginner-level programming, you can use it to check whether a value is an integer, a floating-point number, a string,...

JavaScript Under the Hood: Understanding the Call Stack, Event Loop and Web APIs

Most beginners learn JavaScript by writing variables, functions, loops, and events. However, professional developers also understand what happens behind the scenes when JavaScript code executes.

Consider the following code:

console.log("Start");

setTimeout(
function()
{
    console.log("Timer");
},
0
);

console.log("End");

Many beginners expect the output to be:

Start

Timer

End

But the actual output is:

Start

End

Timer

Why does this happen?

To answer this question, we must understand:

  • JavaScript Runtime

  • Call Stack

  • Web APIs

  • Callback Queue

  • Event Loop

These concepts form the foundation of modern JavaScript and are frequently asked in interviews.


Why Understanding JavaScript Internals is Important

Understanding JavaScript internals helps developers:

  • Write better code

  • Debug applications

  • Improve performance

  • Understand asynchronous programming

  • Master Promises and Async/Await

Without understanding these concepts, asynchronous JavaScript often feels confusing.


JavaScript is Single-Threaded

JavaScript executes code using a single thread.

This means:

One Task

at a Time

JavaScript can execute only one statement at a given moment.

Example:

console.log("A");

console.log("B");

console.log("C");

Output:

A

B

C

Execution occurs sequentially.


What is JavaScript Runtime?

The JavaScript Runtime is the environment where JavaScript executes.

In browsers, it consists of:

JavaScript Engine

Call Stack

Web APIs

Callback Queue

Event Loop

JavaScript Runtime Architecture

            Browser

 ┌───────────────────────┐
 │   JavaScript Engine   │
 └──────────┬────────────┘
            │
      ┌─────▼─────┐
      │ Call Stack│
      └─────┬─────┘
            │
 ┌──────────▼───────────┐
 │      Web APIs        │
 └──────────┬───────────┘
            │
      ┌─────▼─────┐
      │ Callback  │
      │  Queue    │
      └─────┬─────┘
            │
      ┌─────▼─────┐
      │Event Loop │
      └───────────┘

What is the JavaScript Engine?

The JavaScript Engine executes JavaScript code.

Popular engines:

BrowserEngine
ChromeV8
EdgeV8
FirefoxSpiderMonkey
SafariJavaScriptCore

The engine reads and executes JavaScript instructions.


What is the Call Stack?

The Call Stack is a data structure that keeps track of function execution.

Whenever a function is called:

Function Added

to Stack

When execution finishes:

Function Removed

from Stack

The stack follows:

LIFO

Last In First Out

Call Stack Example

function one()
{
    two();
}

function two()
{
    three();
}

function three()
{
    console.log("Hello");
}

one();

Output:

Hello

Step-by-Step Dry Run

Initial Stack:

Empty

When one() executes:

one()

Inside one():

two()

one()

Inside two():

three()

two()

one()

Inside three():

console.log()

three()

two()

one()

After execution:

Empty

Everything is removed from the stack.


Visual Representation

┌────────────┐
│console.log │
├────────────┤
│ three()    │
├────────────┤
│ two()      │
├────────────┤
│ one()      │
└────────────┘

Stack Push Operation

Adding a function:

Push

Example:

one();

Adds:

one()

to the stack.


Stack Pop Operation

Removing a function:

Pop

After function completion:

one()

is removed.


What is Stack Overflow?

When functions keep calling themselves endlessly, the stack becomes full.

Example:

function test()
{
    test();
}

test();

Output:

Maximum Call Stack Size Exceeded

Why Stack Overflow Happens

Execution:

test()

↓

test()

↓

test()

↓

test()

↓

Forever...

Stack memory becomes exhausted.


What are Web APIs?

JavaScript itself does not provide features like:

  • Timers

  • DOM Manipulation

  • HTTP Requests

  • Geolocation

These are provided by the browser.

They are called:

Web APIs

Examples of Web APIs

  • setTimeout()

  • setInterval()

  • fetch()

  • DOM Events

  • Geolocation

  • Local Storage


Example

setTimeout(
function()
{
    console.log("Hello");
},
3000
);

The timer is handled by:

Web API

not by the Call Stack.


How setTimeout Works

Example:

console.log("Start");

setTimeout(
function()
{
    console.log("Timer");
},
2000
);

console.log("End");

Execution Flow

Step 1:

console.log("Start")

Output:

Start

Step 2:

setTimeout

moves to:

Web API

Timer begins.


Step 3:

console.log("End")

Output:

End

After 2 Seconds:

Callback enters:

Callback Queue

What is Callback Queue?

The Callback Queue stores completed asynchronous callbacks.

Example:

setTimeout(
function()
{
    console.log("Timer");
},
2000
);

After timer completion:

Callback Queue

↓

console.log("Timer")

What is the Event Loop?

The Event Loop continuously checks:

Is Call Stack Empty?

If YES:

Move Callback Queue Task

to Call Stack

Event Loop Workflow

Call Stack Empty?

      ↓

      YES

      ↓

Take First Callback

from Queue

      ↓

Move to Stack

      ↓

Execute

Complete Example

console.log("Start");

setTimeout(
function()
{
    console.log("Timer");
},
0
);

console.log("End");

Output:

Start

End

Timer

Why Doesn't Timer Execute First?

Even though delay is:

0

The callback still goes through:

Web API

↓

Callback Queue

↓

Event Loop

↓

Call Stack

Therefore:

Start

End

Timer

Understanding Promises

Promises use a different queue.

Example:

console.log("Start");

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

console.log("End");

Output:

Start

End

Promise

Microtask Queue

Promises are placed in:

Microtask Queue

which has higher priority.


Queues in JavaScript

Microtask Queue

(Promises)

↓

Callback Queue

(setTimeout)

Microtasks execute first.


Example

console.log("Start");

setTimeout(
() => console.log("Timer"),
0
);

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

console.log("End");

Output:

Start

End

Promise

Timer

Why Promise Executes First

Priority:

Microtask Queue

↓

Callback Queue

Promises always execute before timers.


Complete Execution Diagram

JavaScript Code

       ↓

Call Stack

       ↓

Web APIs

       ↓

Callback Queue

       ↓

Event Loop

       ↓

Call Stack Again

Real-Life Example

Consider ordering food online.

Place Order

↓

Restaurant Prepares Food

↓

Continue Other Work

↓

Food Ready Notification

↓

Collect Food

This is similar to asynchronous JavaScript.


Real-World Applications

These concepts are used in:

  • API Calls

  • React Applications

  • Node.js Servers

  • Chat Applications

  • Banking Systems

  • E-Commerce Platforms

Every modern JavaScript application depends on the Event Loop.


Common Interview Questions

What is the Call Stack?

A data structure that manages function execution.


What is Event Loop?

A mechanism that moves completed asynchronous tasks into the Call Stack.


Why is JavaScript Single-Threaded?

It executes one task at a time using a single Call Stack.


Why does setTimeout(0) not execute immediately?

Because the callback must first:

Pass Through

Web APIs

↓

Callback Queue

↓

Event Loop

Which Executes First?

Promise

or

setTimeout

Answer:

Promise

because Microtask Queue has higher priority.


Best Practices

  • Avoid infinite recursion.

  • Understand asynchronous behavior.

  • Use Promises and Async/Await properly.

  • Keep Call Stack small.

  • Avoid blocking operations.


Advantages of Understanding JavaScript Internals

  • Better debugging

  • Improved performance

  • Strong interview preparation

  • Easier asynchronous programming

  • Professional JavaScript development


Conclusion

The Call Stack, Web APIs, Callback Queue, Microtask Queue, and Event Loop are the core components of JavaScript's execution model.

Understanding these concepts helps explain how JavaScript handles asynchronous operations while remaining single-threaded.

Once you master these internals, concepts like Promises, Async/Await, API calls, and framework behavior become much easier to understand.

Comments

Popular posts from this blog

Understanding Comments in Java: A Beginner’s Guide

When learning Java programming, one of the first concepts you’ll come across is comments . Comments may not affect how a program runs, but they play a crucial role in making code more understandable, readable, and maintainable. Let’s dive deeper into what comments are, why they’re important, and the different types of comments in Java. What are Comments in Java? A comment in Java is a piece of text written within a program that is ignored by the compiler . In other words, comments are notes for humans, not instructions for machines. They help developers explain the purpose of code, describe logic, or temporarily disable certain lines of code without deleting them. Why are Comments Important? 📌 Readability – Comments make code easier to understand for you and others. 📌 Maintenance – When you revisit your code after months, comments remind you what you were doing. 📌 Collaboration – In team projects, comments explain code to fellow developers. 📌 Debugging – You c...

Java Program to Check Voting Eligibility

In this program, we’ll take the user’s age as input and check whether the person is eligible to vote or not. In India, the minimum age required to vote is 18 years . 💻 Program Code // Java Program to Check Voting Eligibility import java.util.Scanner; public class VotingEligibility { public static void main(String[] args) { // Create Scanner object to take input from user Scanner sc = new Scanner(System.in); // Ask user to enter age System.out.print("Enter your age: "); int age = sc.nextInt(); // Check eligibility if (age >= 18) { System.out.println("You are eligible to vote."); } else { System.out.println("You are not eligible to vote yet."); System.out.println("You can vote after " + (18 - age) + " year(s)."); } sc.close(); // Close the scanner } } 🧠 Explanation import java.util.Scanner; → Imp...

Java Program to Calculate Total Marks and Average of Five Subjects

💡 Program Explanation In this program: The user will input marks of five subjects . The program will calculate the total marks and average . It will then display both results clearly. 🧑‍💻 Java Code: // Java Program to Calculate Total Marks and Average of Five Subjects import java.util.Scanner; // Importing Scanner class for user input public class TotalAndAverage { public static void main(String[] args) { // Creating Scanner object to take input from user Scanner sc = new Scanner(System.in); // Declaring variables for five subjects double subject1, subject2, subject3, subject4, subject5; // Taking marks input for each subject System.out.print("Enter marks of Subject 1: "); subject1 = sc.nextDouble(); System.out.print("Enter marks of Subject 2: "); subject2 = sc.nextDouble(); System.out.print("Enter marks of Subject 3: "); subject3 = sc.nextDo...