![]() |
VOOZH | about |
JavaScript functions are reusable blocks of code designed to perform a specific task.
Here, we’ve compiled the most important JavaScript asynchronous function interview questions to help you prepare.
In JavaScript, scope determines where variables and functions are accessible in your code. There are different types of scope you need to understand:
var are scoped to the enclosing function. They are not visible outside that function.let and const. These are visible only within the { ... } block they are declared in (for loops, if-statements etc.).Hoisting is JavaScript’s behavior where variable and function declarations are moved to the top of their scope during the compilation phase.
var variables: The declaration is hoisted, but the initialization stays in place. Accessing them before initialization gives undefined (not an error).let and const: They are also hoisted, but remain in the Temporal Dead Zone (TDZ) until initialization. Accessing them before definition results in a ReferenceError.A higher-order function is a function that either takes other functions as arguments, returns a function as its result, or both
Examples:
map, filter, reduce are higher-order functions because they take callback functions as arguments. Function that returns another function:
Output:
36class. They are tied to an instance (via this) or to the class itself (if declared static).call, apply, bind).An IIFE is a function that is defined and executed immediately after its creation. It’s written as a function expression wrapped in parentheses, followed by () to invoke it.
Example:
Output:
IIFE executed!Use cases / benefits:
A pure function is a function that:
Benefits:
Functions can be defined in different forms, such as:
1. Function Declaration
2. Function Expression
3. Arrow Function (ES6)
this, arguments, or super.4. Anonymous Function
5. Named Function Expression
6. Function Constructor
7. Generator Function (ES6)
function*.8. Async Function (ES8)
await inside.9. Async Arrow Function
10. Object Method Shorthand (ES6)
11. Class Method
Currying is a technique in functional programming where a function that takes multiple arguments is transformed into a series of functions, each taking one (or fewer) arguments.
Example:
Output:
9In this example, sum(2)(3) returns a new function that remembers a = 2 and b = 3. When you later call it with 4, it computes 2 + 3 + 4 = 9.
Memoization is an optimization technique where you cache the results of expensive function calls so that if the same inputs are given again, the cached result is returned instead of recomputing.
Example:
Output:
55
55
In this example, the first call to fib(10) computes the result recursively. The second call to fib(10) retrieves the result directly from the cache, avoiding repeated calculations.
Recursion is when a function calls itself (directly or indirectly) to solve a problem by breaking it into smaller subproblems.
Example:
Output:
120In this example, factorial(5) keeps calling itself until it reaches the base case (factorial(0)). Each call resolves step by step, producing the result 120.
Recursion is preferable when:
Downsides:
setInterval using only setTimeout and functions?We can create a recursive setTimeout that schedules itself after each execution, mimicking setInterval.
Example:
Output:
Tick 1
Tick 2
Tick 3
Instead of running at fixed intervals, this implementation schedules the next setTimeout only after the function runs, giving you more control and avoiding issues where tasks might overlap.
{} to define a function body.{} as a block statement, not an object — so the function returns undefined.A generator is a special kind of function that can pause execution and later resume. Generators are defined with the function* syntax and return an iterator.
Example:
Output:
{ value: 1, done: false }
{ value: 2, done: false }
{ value: 3, done: true }
In this example, the generator gen yields values one by one each time next() is called, pausing execution between calls.
Differences from regular functions:
Example:
Output:
Hello Alice
Hello Bob, age 25
Hello, Guest
In this example, instead of real overloading, the function handles different cases by checking arguments.length.
undefined) is passed....): Collects all remaining arguments into an array....): Expands an iterable (like an array or object) into individual elements.Explanation:
arguments is an array-like object available in all non-arrow functions.Return this from methods to enable chaining.
undefined.In JavaScript, functions are first-class objects, meaning they can be treated like any other value. You can:
This flexibility is a key reason JavaScript supports functional programming patterns.
Shallow Copy: Copies reference for nested objects/arrays.
Deep Copy: Creates independent clone.
Shallow copy copies only the first level (nested objects remain linked), while deep copy recursively duplicates everything creating a fully independent clone.
Here, we’ve compiled the most important JavaScript Asynchronous Function .Here, we’ve compiled the most important JavaScript Asynchronous function interview questions to help you prepare:
JavaScript can work in two ways: synchronous and asynchronous, and they differ in how tasks are executed.
async/await.Start 0 1 2 End Start End Async task done
In the synchronous example, execution waits for the loop to finish before moving on. In the asynchronous example, setTimeout schedules a task to run later, allowing "End" to log immediately.
JavaScript schedules asynchronous work into two main queues: microtasks and macrotasks, and they differ in priority and when they are executed.
| Microtasks | Macrotasks |
|---|---|
| Small tasks queued in the microtask queue (executed immediately after the current call stack is empty, before next macrotask). | Tasks queued in the macrotask (callback) queue, executed after microtasks are cleared. |
Examples: Promise.then, catch, finally, queueMicrotask(), MutationObserver. | Examples: setTimeout, setInterval, setImmediate (Node.js), requestAnimationFrame, I/O events. |
| Executed with higher priority (always before macrotasks). | Executed after all microtasks are done. |
| Good for short, immediate follow-ups to the current code. | Good for scheduling larger, delayed tasks. |
Example:
Start End Microtask: Promise.then Macrotask: setTimeout
JavaScript provides different timing functions: setTimeout, setInterval, and requestAnimationFrame, but they differ in purpose and execution style.
| setTimeout | setInterval | requestAnimationFrame |
|---|---|---|
| Runs a function once after a delay. | Runs a function repeatedly at fixed intervals. | Runs a function before the next repaint (synced with screen refresh). |
| Use: delayed execution. | Use: periodic execution (polling, auto-save). | Use: smooth animations, game loops. |
Canceled with clearTimeout(id). | Canceled with clearInterval(id). | Canceled with cancelAnimationFrame(id). |
AJAX (Asynchronous JavaScript and XML) is a technique that allows web pages to communicate with a server in the background without reloading the whole page.
XMLHttpRequest (older) or fetch (modern) to send and receive data from a server.async/await handles it.JavaScript provides two main ways to make network requests
| Fetch API | XMLHttpRequest (XHR) |
|---|---|
Promise-based (then, async/await) : cleaner and modern | Callback-based : more verbose and harder to manage |
| Simple, chainable, works well with async/await | Requires manual state checks (readyState, status) |
Built-in methods like .json(), .text(), .blob() | Manual parsing needed (responseText, responseXML) |
| Supports streaming responses natively | Must wait for full response before processing |
| Rejects only on network errors (HTTP errors need manual check) | Provides detailed status codes (e.g., 404, 500) |
| Better integration with CORS, Service Workers, and modern APIs | Older, limited flexibility with modern web APIs |
| Modern browsers (IE not supported) | Supported in all browsers, including older ones |
AbortSignal.timeout() and AbortSignal.any()?JavaScript’s AbortSignal API helps cancel asynchronous tasks like fetch. New methods like AbortSignal.timeout() and AbortSignal.any() extend its usefulness.
Promise.withResolvers()Promise.withResolvers() is a new helper method in JavaScript (part of the modern spec) that creates a promise together with its resolve and reject functions, packaged neatly in one object.
Normally, when you create a new Promise, you have to pass an executor function with resolve and reject. With Promise.withResolvers(), you get them directly without writing that boilerplate.
A callback is a function passed into another function as an argument, which is later invoked to complete some operation.
Callbacks are commonly used for:
Example:
Output:
Data receivedIn this example, the callback function is executed after setTimeout finishes, so "Data received" is printed.
While callbacks are powerful, they come with several drawbacks:
Example:
Output:
Final result: 42In this example, each task depends on the previous one, leading to deeply nested code — this is the classic callback hell problem.
setTimeout, fetch, event listeners). These run tasks in the background, and when finished, they hand results back to the single JavaScript thread through the event loop.Both debounce and throttle control how often a function executes, especially for events that fire frequently.
Example:
If you keep resizing the window rapidly:
async / await? How do they work under the hood?async / await are syntactic sugar over Promises that make asynchronous code look and behave more like synchronous code, improving readability.
async function always returns a Promise.await before a Promise to pause execution until the Promise resolves (or rejects).await suspends execution of the async function and yields control back to the event loop. Once the awaited Promise settles, execution resumes.try/catch instead of chaining .then() and .catch().Example:
Output:
Data receivedIn this example, await pauses the execution of getData until fetchData resolves. This avoids using .then() chaining and makes the code easier to read.
Why it’s asked: Understanding the event loop is critical for debugging async behavior, performance issues, and promise/async/await execution order.
Promise.allSettled() differ from Promise.all()?Promise.all() fails fast: if any promise rejects, the whole thing rejects.Promise.allSettled() waits for all promises to settle (either fulfilled or rejected) and returns an array of results.async functions and generator functions with yield.| Async Functions | Generator Functions (function*) |
|---|---|
| Returns a Promise | Returns an Iterator object |
Pauses at await until the Promise resolves | Pauses at yield until next() is called |
| Used for handling asynchronous operations | Used for creating iterables and sequences of values |
| Automatically resumes after awaited Promise settles | Resumes only when next() is explicitly called |
Error handling via try/catch or .catch() | Error handling via iterator’s throw() method |
| Works naturally with Promises and async tasks | Mostly synchronous unless combined with async helpers |
| Typical use: network requests, timers, async I/O | Typical use: lazy evaluation, infinite sequences, custom iteration |
async function*) work?for await…of to iterate over async streams of data.Promise.race()?Promise.race() executes multiple promises simultaneously and settles as soon as the first promise resolves or rejects.fetch, timers, or custom Promises) cannot be stopped natively once started unless you use control mechanisms.AbortController (for fetch or any async operation that supports signals)clearTimeout / clearInterval)"Fetch aborted: The user aborted a request."Mastering these functions and asynchronous JavaScript concepts not only helps you write cleaner, more efficient code but also prepares you to confidently tackle the most common and challenging interview questions.