JavaScript45 min read

100+ JavaScript Interview Questions & Answers for 2026

The ultimate guide to acing your JavaScript interviews. From closures and event loops to 100+ rapid-fire questions.

Dev Kant Kumar
Dev Kant Kumar
February 3, 2026
Updated for 2026

100+ JavaScript Interview Questions

The definitive guide. From simple data types to complex microtask queues, mastering these 100+ questions will separate you from 90% of candidates.

JavaScript Interview Questions 2026 Cover

Let's be real-JavaScript interviews can be brutal. You think you know the language, then someone asks you to explain the output of a tricky closure loop or how the microtask queue really works.

In the world of modern web development, the difference between a junior developer and a senior engineer often comes down to deep theoretical understanding. It's not just about writing code; it's about knowing how the code executes.

This isn't just a list of questions copied from a textbook. This is a collection of real-world questions, practical scenarios, and "gotchas" that are frequently asked in technical interviews. Whether you're aiming for a role at a top-tier tech company or a fast-paced startup, mastery of these topics is essential.

How to use this guide

This isn't a list to memorize. It's a curriculum. It is broken down into Deep Dive sections for the heavy concepts (Closures, Promises) and a Rapid Fire section for quick fact-checking.
01

JavaScript Fundamentals

JavaScript The Building Blocks

What are the data types in JavaScript? Explain each with examples.

JavaScript is a dynamically typed language, meaning you don't need to define the type of a variable usually. There are 8 standard data types in the latest ECMAScript standard.

1. Primitives (Immutable)

String

Represents textual data.

const name = "Dev";
Number

Integers & floats. (Max: ±2^53 - 1).

let age = 25;
BigInt (ES11)

For large integers > 2^53 - 1. Suffix n.

const big = 900n;
Boolean

Logical entity.

true / false
Undefined

Variable declared but not assigned.

Null

Intentional absence of any object value.

Symbol (ES6)

Unique, immutable identifier for object properties.

const id = Symbol('id');

2. Non-Primitive (Reference)

Object

Used to store keyed collections of varying data and more complex entities. Includes Arrays, Functions, Dates, etc.

const user = { name: "Dev" };

The 'typeof null' Bug

Always remember: typeof null returns "object". This is a historical bug in JavaScript. Correct check: value === null.

Explain var vs let vs const in depth.

Before ES6 (2015), var was the only way to declare variables. let and const were introduced to fix issues with hoisting and scope leakage.

var
  • Scope: Function
  • Hoisting: Yes (undefined)
  • Reassign: Yes
  • Redeclare: Yes
let
  • Scope: Block {}
  • Hoisting: TDZ*
  • Reassign: Yes
  • Redeclare: No
const
  • Scope: Block {}
  • Hoisting: TDZ*
  • Reassign: No
  • Redeclare: No

*TDZ (Temporal Dead Zone): The time between entering the scope and the actual variable declaration.

Example.js
JAVASCRIPT
1// 1. Scope Difference
2if (true) {
3 var a = 10;
4 let b = 20;
5}
6console.log(a); // 10 (Leaked!)
7console.log(b); // ReferenceError
8
9// 2. Hoisting
10console.log(x); // undefined
11var x = 5;
12
13// console.log(y); // ReferenceError (TDZ)
14let y = 5;
UTF-8Ln 14, Col 0

What is Hoisting? Declaration vs Expression?

Hoisting moves declarations to the top of the scope.

Function Declaration

Fully hoisted. Can be called before definition.

Function Expression

Variable hoisted as undefined. Assignment stays.

Example.js
JAVASCRIPT
1greet(); // "Hello!"
2function greet() { console.log("Hello!"); }
3
4// sayBi(); // TypeError: sayBi is not a function
5var sayBi = function() { console.log("Bye!"); };
UTF-8Ln 5, Col 0

Explain Type Coercion and Equality (== vs ===).

Implicit Coercion happens when operators convert types automatically.

Coercion Examples

  • '2' + 2 '22'
  • '2' - 2 0
  • true + 1 2

Equality check

  • 0 == false true
  • 0 === false false
  • null == undefined true

Rule of thumb

Always use === (Strict) unless checking for null/undefined specifically.

What are Truthy and Falsy values?

Values that resolve to true or false in boolean contexts.

The 6 Falsy Values
false0""nullundefinedNaN
Truthy Examples
[]{}"0""false"-1Infinity
02

Functions & Scope

The Heart of JS

Deep Dive: What is a Closure? Why is it powerful?

A Closure is created when a function is defined inside another function, allowing the inner function to access the outer function's variables-even after the outer function has finished executing.

Core Concept

Lexical Scope

Inner functions contain the scope of parent functions even if the parent has returned.

Data Privacy

Closures are often used to emulate private variables (Module Pattern).

Interview Analogy

Think of a closure like a backpack. When a function leaves the scope where it was created, it takes a "backpack" of variables from that scope with it.
Example.js
JAVASCRIPT
1function outer() {
2 const secret = "I am hidden";
3
4 function inner() {
5 console.log(secret); // Accessing 'secret' from closure
6 }
7
8 return inner;
9}
10
11const myFunc = outer(); // outer() finishes execution here.
12myFunc(); // logs "I am hidden" (It still remembers!)
UTF-8Ln 12, Col 0

Output Challenge: The Loop Closure Trap

This is a classic interview favorite. It tests your understanding of var (function scope) vs let (block scope) inside loops.

The Problem (Values are 3, 3, 3)

var i is shared across all iterations. By the time setTimeout runs, the loop has finished and i is 3.

The Fix (Values are 0, 1, 2)

let i creates a new binding (new i) for each iteration of the loop.

Example.js
JAVASCRIPT
1// ❌ BAD (Outputs 3, 3, 3)
2for (var i = 0; i < 3; i++) {
3 setTimeout(() => console.log(i), 100);
4}
5
6// ✅ GOOD (Outputs 0, 1, 2) - ES6 Solution
7for (let i = 0; i < 3; i++) {
8 setTimeout(() => console.log(i), 100);
9}
10
11// 🧠 OLD SCHOOL (IIFE Solution)
12for (var i = 0; i < 3; i++) {
13 (function(j) {
14 setTimeout(() => console.log(j), 100);
15 })(i);
16}
UTF-8Ln 16, Col 0

Explain Call, Apply, and Bind. When to use which?

These methods allow you to explicitly set the value of this for a function.

Call

Invokes function immediately.

Args: Comma separated (this, arg1, arg2)

Apply

Invokes function immediately.

Args: Array (this, [arg1, arg2])

Bind

Returns a new function.

Does not execute immediately. Useful for events.

Example.js
JAVASCRIPT
1const person = { name: "Dev" };
2function say(greeting) { console.log(greeting + ", " + this.name); }
3
4// Call
5say.call(person, "Hello"); // "Hello, Dev"
6
7// Apply
8say.apply(person, ["Hi"]); // "Hi, Dev"
9
10// Bind
11const sayHello = say.bind(person, "Hola");
12sayHello(); // "Hola, Dev"
UTF-8Ln 12, Col 0

What is Currying? Write a curry function.

Currying is the process of transforming a function that takes multiple arguments into a sequence of functions that each take a single argument.f(a, b, c) becomes f(a)(b)(c).

Functional Programming
Reusability
Example.js
JAVASCRIPT
1// Regular function
2function add(a, b) {
3 return a + b;
4}
5
6// Curried function
7function curriedAdd(a) {
8 return function(b) {
9 return a + b;
10 };
11}
12
13// Arrow syntax (cleaner)
14const arrowAdd = a => b => a + b;
15
16console.log(curriedAdd(2)(3)); // 5
17console.log(arrowAdd(5)(10)); // 15
UTF-8Ln 17, Col 0

What is an IIFE (Immediately Invoked Function Expression)?

A function that runs as soon as it is defined. Before ES6 Modules, this was the primary way to create module patterns and avoid polluting the global namespace.

Example.js
JAVASCRIPT
1(function() {
2 var privateVar = "I am safe";
3 console.log("I run immediately!");
4})();
5
6// console.log(privateVar); // ReferenceError
UTF-8Ln 6, Col 0
03

Async JS & The Event Loop

Mastering Concurrency

Critical Context

This is where 50% of candidates fail. You must understand that JavaScript is single-threaded but handles async operations via the Event Loop.

How does the Event Loop actually work? (Microtasks vs Macrotasks)

The Event Loop is the mechanism that allows JS to perform non-blocking operations. It coordinates the execution of code between the Call Stack and various Queues.

1. Call Stack

LIFO (Last In, First Out). Where your synchronous code runs.

2. Web APIs

Where browser handles async things (DOM events, fetch, setTimeout).

3. Microtask Queue

High Priority. Promises (`.then`), `queueMicrotask`, MutationObserver.

4. Task Queue (Macrotask)

Low Priority. `setTimeout`, `setInterval`, `setImmediate`.

The Golden Rule: The Event Loop checks if the Stack is empty. If yes, it runs ALL Microtasks until the queue is clear, and THEN runs just ONE Macrotask.

Output Challenge: Async Priority

Predict the order of logs. Remember: Sync > Microtask > Macrotask.

1. console.log('1')Sync
2. Promise.resolve().then(...)Microtask
3. setTimeout(...)Macrotask
Example.js
JAVASCRIPT
1console.log('1'); // Sync
2
3setTimeout(() => console.log('2'), 0); // Macrotask
4
5Promise.resolve().then(() => console.log('3')); // Microtask
6
7console.log('4'); // Sync
8
9// Output Order:
10// 1
11// 4
12// 3
13// 2
UTF-8Ln 13, Col 0

Explain Promise.all vs allSettled vs race vs any

Modern JS provides powerful concurrency methods for handling multiple promises.

Promise.all()

"All or Nothing"

  • Resolves when all resolve.
  • Rejects immediately if one rejects.
Promise.allSettled()

"Wait for Everyone"

  • Waits for all to finish (success or fail).
  • Returns array of objects `{ status, value/reason }`.
Promise.race()

"First One Wins"

  • Settles as soon as the first promise settles (resolves OR rejects).
Promise.any() (ES2021)

"First Success Wins"

  • Resolves as soon as the first promise fulfills.
  • Rejects only if all reject (AggregateError).

What is Async/Await and how does error handling work?

async/await is syntactic sugar built on top of Promises. It makes asynchronous code look and behave like synchronous code.

Key Rules
  • An async function always returns a Promise.
  • await pauses the execution of its surrounding async function until the Promise settles.
  • It does not block the main thread (Call Stack).
Example.js
JAVASCRIPT
1async function fetchData() {
2 try {
3 const response = await fetch('/api/user');
4 const data = await response.json();
5 return data;
6 } catch (error) {
7 console.error("Oops!", error); // Handles rejection here
8 }
9}
10
11// Without async/await (Promise Chains)
12fetch('/api/user')
13 .then(res => res.json())
14 .then(data => ...)
15 .catch(err => ...)
UTF-8Ln 15, Col 0
04

Objects & Prototypes

The Object-Oriented Nature

What is the Prototype Chain? Explain Prototypal Inheritance.

JavaScript is prototype-based, not class-based (classes are just syntactic sugar). Every object has a hidden property [[Prototype]] (accessed via __proto__) that points to another object.

The Chain Lookup

myArr.map() (Does myArr have it? No.)
Array.prototype (Found it here!)
Object.prototype (End of chain is null)

Performance

Searching up the prototype chain takes time. Accessing properties that don't exist traverses the entire chain until null is reached.
Example.js
JAVASCRIPT
1const animal = {
2 eats: true,
3 walk() { console.log("Animal walk"); }
4};
5
6const rabbit = {
7 jumps: true,
8 __proto__: animal // Inherits from animal
9};
10
11rabbit.walk(); // "Animal walk" (Found on prototype)
12console.log(rabbit.eats); // true
UTF-8Ln 12, Col 0

How does 'this' work? (The 4 Rules)

The value of this depends on how the function is called, not where it is defined.

1. Implicit Binding

Called with a dot obj.func().

this = obj
2. Explicit Binding

Using call, apply, bind.

this = argument passed
3. New Binding

Called with new keyword.

this = new empty object
4. Default Binding

Standalone call func().

this = window / undefined
*Arrow functions don't have their own this. They inherit it from the surrounding (lexical) scope.

What is the difference between Shallow Copy and Deep Copy?

Copying objects in JS can be tricky because simple assignment (=) only copies the reference, not the value.

Shallow Copy

Copies the top-level properties. Nested objects are still references (shared).

...spreadObject.assign

Deep Copy

Creates a completely independent clone, including all nested objects.

structuredClone()JSON.parse(JSON.stringify())
Example.js
JAVASCRIPT
1const original = { fit: "gym", dates: { day: 1 } };
2
3// Shallow Copy
4const shallow = { ...original };
5shallow.dates.day = 99;
6console.log(original.dates.day); // 99 (Affected! 😱)
7
8// Deep Copy
9const deep = structuredClone(original);
10deep.dates.day = 500;
11console.log(original.dates.day); // 99 (Safe! 🛡️)
UTF-8Ln 11, Col 0
05

ES6+ Modern Features

The Modern Standard

Explain ES6 Classes and how they differ from the prototype method.

Classes in JS are "syntactic sugar" over the existing prototype-based inheritance. They provide a cleaner, more familiar syntax for creating objects and dealing with inheritance.

Features

  • Constructor: Special method for initialization.
  • Super: Calls parent constructor/methods.
  • Static: Methods called on the class, not instances.
  • Getters/Setters: Encapsulate property access.

Under the Hood

class Animal remains a function.
Methods defined in the class are added to Animal.prototype.

Example.js
JAVASCRIPT
1class Animal {
2 constructor(name) {
3 this.name = name;
4 }
5
6 speak() {
7 console.log(this.name + ' makes a noise.');
8 }
9}
10
11class Dog extends Animal {
12 speak() {
13 super.speak(); // Calls parent speak
14 console.log(this.name + ' barks.');
15 }
16}
17
18const d = new Dog('Rex');
19d.speak();
20// "Rex makes a noise."
21// "Rex barks."
UTF-8Ln 21, Col 0

What are ES6 Modules? (Import / Export)

Modules allow splitting code into separate files. They rely on import and export statements. They run in strict mode automatically.

Named Exportexport const add = ...

Import with curly braces:
import { add } from './math'

Default Exportexport default User

Import without braces, any name:
import User from './user'

Difference between ?? (Nullish Coalescing) and || (Logical OR)

A common bug source. || falls back on Falsy (0, "", false), whereas ?? falls back only on Nullish (null, undefined).

Example.js
JAVASCRIPT
1const count = 0;
2
3// The PROBLEM with ||
4const amount = count || 10;
5console.log(amount); // 10 (Oops! 0 is falsy, but valid)
6
7// The FIX with ??
8const correctAmount = count ?? 10;
9console.log(correctAmount); // 0 (Correct! 0 is not null/undefined)
UTF-8Ln 9, Col 0

More ES6+ Essentials

Q1. What are Template Literals?
String literals allowing embedded expressions (`${exp}`), multi-line strings, and string interpolation. Enclosed by backticks.
Q2. What is Object Destructuring?
Extracting properties from objects into distinct variables. `const { name } = user;`
Q3. What is Array Destructuring?
Unpacking values from arrays. `const [first, second] = arr;`
Q4. What is the Spread Operator (...)?
Expands an iterable into individual elements. Used for copying arrays/objects or passing args.
Q5. What is the Rest Operator (...)?
Collects multiple elements into a single array (e.g., function arguments `(...args)`).
Q6. What are Default Parameters?
Initializing function parameters with default values if no value or `undefined` is passed.
Q7. What is `for...of` loop?
Loops over iterable objects (Arrays, Strings, Maps, Sets) delivering values (unlike `for...in` which delivers keys).
Q8. What is a Symbol?
A primitive data type returning a unique, immutable identifier, often used for private object properties.
Q9. What is an Iterator?
An object with a `next()` method returning `{ value, done }`.
Q10. What is a Generator function?
A function denoted by `function*` that can pause execution (`yield`) and resume later.
Q11. What is Optional Chaining (?.)?
Safely accesses nested properties. `obj?.prop` returns `undefined` instead of throwing error if `obj` is nullish.
Q12. What is Nullish Coalescing (??)?
Returns the right-side operand when left is `null` or `undefined` (unlike `||` which checks for falsy).
06

Advanced Concepts

Senior Level Topics

Explain Debouncing vs Throttling. When to use each?

Both techniques limit the rate at which a function gets called. They're crucial for performance optimization.

Debouncing

Waits for a pause in events before executing. Perfect for search inputs, auto-save.

User types: a- b- c- [pause] → Function runs

Throttling

Guarantees execution at most once per time period. Ideal for scroll events, button clicks.

User scrolls: ✅- ❌- ❌- ❌- ✅- ❌
Example.js
JAVASCRIPT
1// Debounce Implementation
2function debounce(func, delay) {
3 let timeoutId;
4 return function(...args) {
5 clearTimeout(timeoutId);
6 timeoutId = setTimeout(() => func.apply(this, args), delay);
7 };
8}
9
10// Throttle Implementation
11function throttle(func, limit) {
12 let inThrottle;
13 return function(...args) {
14 if (!inThrottle) {
15 func.apply(this, args);
16 inThrottle = true;
17 setTimeout(() => inThrottle = false, limit);
18 }
19 };
20}
21
22// Usage
23const searchInput = document.getElementById('search');
24searchInput.addEventListener('input', debounce(handleSearch, 300));
UTF-8Ln 24, Col 0

What is Memoization? Implement a memoize function.

Memoization is an optimization technique that stores the results of expensive function calls and returns the cached result when the same inputs occur again.

Performance
Cache
Pure Functions

When to Memoize

Use memoization for pure functions with expensive calculations that are called repeatedly with the same arguments.
Example.js
JAVASCRIPT
1// Basic Memoization Function
2function memoize(fn) {
3 const cache = new Map();
4
5 return function(...args) {
6 const key = JSON.stringify(args);
7
8 if (cache.has(key)) {
9 console.log('Returning from cache:', key);
10 return cache.get(key);
11 }
12
13 const result = fn.apply(this, args);
14 cache.set(key, result);
15 console.log('Computing and caching:', key);
16 return result;
17 };
18}
19
20// Example: Expensive Fibonacci
21const fib = memoize(n => {
22 if (n < 2) return n;
23 return fib(n - 1) + fib(n - 2);
24});
25
26console.log(fib(10)); // Fast after first call
UTF-8Ln 26, Col 0

Explain common JavaScript Design Patterns.

Design patterns are reusable solutions to commonly occurring problems. In JavaScript interviews, knowing these shows you understand software architecture.

Module Pattern

Encapsulates private data and exposes public API using closures and IIFE.

Example.js
JAVASCRIPT
1const Module = (function() {
2 let privateVar = 'secret';
3
4 return {
5 getPrivate: () => privateVar,
6 setPrivate: (val) => privateVar = val
7 };
8})();
UTF-8Ln 8, Col 0

Observer Pattern

Defines a one-to-many dependency between objects. When one object changes state, all dependents are notified.

Example.js
JAVASCRIPT
1class Subject {
2 constructor() {
3 this.observers = [];
4 }
5
6 subscribe(observer) {
7 this.observers.push(observer);
8 }
9
10 notify(data) {
11 this.observers.forEach(obs => obs.update(data));
12 }
13}
UTF-8Ln 13, Col 0

Factory Pattern

Creates objects without specifying the exact class. Useful for creating similar objects with different configurations.

Example.js
JAVASCRIPT
1class User {
2 constructor(name, type) {
3 this.name = name;
4 this.type = type;
5 }
6}
7
8class UserFactory {
9 static createUser(name, type) {
10 return new User(name, type);
11 }
12}
UTF-8Ln 12, Col 0

What are common causes of Memory Leaks in JavaScript?

Memory leaks occur when your application retains references to objects that are no longer needed, preventing garbage collection.

Global Variableswindow.leak = largeObject
Forgotten TimerssetInterval without clearInterval
Detached DOMRemoved elements with JS references
ClosuresOuter scope references in callbacks

React Native Context

In React Native, memory leaks are critical because mobile devices have limited memory. Always cleanup useEffect subscriptions, event listeners, and intervals.
Example.js
JAVASCRIPT
1// Common Memory Leak Pattern
2function createLeak() {
3 const largeData = new Array(1000000).fill('data');
4
5 // ❌ BAD: Closure keeps largeData alive forever
6 setInterval(() => {
7 console.log('Running...', largeData.length);
8 }, 1000);
9}
10
11// ✅ GOOD: Cleanup properly
12function createNoLeak() {
13 const largeData = new Array(1000000).fill('data');
14
15 const timer = setInterval(() => {
16 console.log('Running...');
17 }, 1000);
18
19 // Cleanup function
20 return () => {
21 clearInterval(timer);
22 largeData.length = 0; // Clear large array
23 };
24}
UTF-8Ln 24, Col 0

What is Event Delegation and why is it important?

Event delegation is a technique where instead of adding event listeners to multiple child elements, you add a single listener to a parent element and use event bubbling to handle events.

❌ Without Delegation

  • • 100 buttons = 100 event listeners
  • • Higher memory usage
  • • Dynamic elements need new listeners

✅ With Delegation

  • • 100 buttons = 1 event listener
  • • Better performance
  • • Works with dynamic elements
Example.js
JAVASCRIPT
1// ❌ BAD: Individual listeners
2document.querySelectorAll('.btn').forEach(btn => {
3 btn.addEventListener('click', handleClick);
4});
5
6// ✅ GOOD: Event delegation
7document.getElementById('container').addEventListener('click', (e) => {
8 if (e.target.classList.contains('btn')) {
9 handleClick(e);
10 }
11});
12
13// React Native Example (FlatList optimization)
14<FlatList
15 data={items}
16 renderItem={({ item }) => <Item data={item} />}
17 keyExtractor={item => item.id}
18 // FlatList handles event delegation internally
19/>
UTF-8Ln 19, Col 0
07

Output-Based Challenges

Test Your Understanding

Pro Tip

These questions test your mental execution ability. Interviewers use these to see if you understand JavaScript's behavior, not just syntax.

🏆 Challenge 1: The Classic Var Loop

This question has eliminated countless candidates. Test your understanding of var scoping vs let block scoping.

What's the Output?

for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); }

Answer & Explanation

3, 3, 3

var i is function-scoped and shared across all iterations. By the time setTimeout callbacks run, the loop has finished and i equals 3.

Example.js
JAVASCRIPT
1// Why this happens:
2console.log('Before loop:'); // Before loop starts
3
4for (var i = 0; i < 3; i++) {
5 console.log('Iteration:', i); // 0, 1, 2
6 setTimeout(() => console.log('Timeout:', i), 100);
7}
8
9console.log('After loop:', i); // 3 (loop finished)
10
11// setTimeout callbacks all see the same i = 3
12
13// FIX 1: Use let (ES6)
14for (let i = 0; i < 3; i++) {
15 setTimeout(() => console.log(i), 100); // 0, 1, 2
16}
17
18// FIX 2: IIFE (Old school)
19for (var i = 0; i < 3; i++) {
20 (function(j) {
21 setTimeout(() => console.log(j), 100); // 0, 1, 2
22 })(i);
23}
UTF-8Ln 23, Col 0

🏆 Challenge 2: Hoisting Madness

This tests your understanding of hoisting for variables, function declarations, and function expressions.

What's the Output?

console.log(a); console.log(b); console.log(c); var a = 1; let b = 2; const c = 3; function d() { return 4; } var e = function() { return 5; }; console.log(d()); console.log(e());

Answer & Explanation

undefined
ReferenceError
ReferenceError
4
TypeError

- var a is hoisted as undefined
- let b, const c are in TDZ
- Function d is fully hoisted
- Function expression e is undefined

Example.js
JAVASCRIPT
1// What JavaScript actually does:
2// 1. Variable declarations are hoisted
3var a; // undefined
4// let b; // TDZ (can't access)
5// const c; // TDZ (can't access)
6
7// 2. Function declaration is fully hoisted
8function d() { return 4; }
9var e; // undefined
10
11// 3. Execution starts
12console.log(a); // undefined
13// console.log(b); // ReferenceError (TDZ)
14// console.log(c); // ReferenceError (TDZ)
15
16a = 1;
17b = 2; // TDZ ends here
18c = 3; // TDZ ends here
19
20console.log(d()); // 4 (works, function is hoisted)
21console.log(e()); // TypeError (e is undefined)
22e = function() { return 5; };
UTF-8Ln 22, Col 0

🏆 Challenge 3: Event Loop Priority Puzzle

Test your understanding of the Event Loop, microtasks vs macrotasks, and execution order.

What's the Output?

console.log('1'); setTimeout(() => console.log('2'), 0); Promise.resolve().then(() => console.log('3')); Promise.resolve().then(() => { console.log('4'); setTimeout(() => console.log('5'), 0); }); console.log('6');

Answer & Execution Order

1, 6, 3, 4, 2, 5

🔄 Sync: 1, 6 (immediate)

📋 Microtasks: 3, 4 (Promise resolves)

🗂️ Macrotasks: 2 (setTimeout)

🔄 New Microtask: 5 (from Promise in microtask)

Example.js
JAVASCRIPT
1// Event Loop Breakdown:
2// 1. Call Stack: ['1'] → logs 1
3console.log('1'); // Sync
4
5// 2. Set up async operations
6setTimeout(() => console.log('2'), 0); // Macrotask Queue
7Promise.resolve().then(() => console.log('3')); // Microtask Queue
8
9// 3. Call Stack: ['6'] → logs 6
10console.log('6'); // Sync
11
12// 4. Call Stack empty → Process Microtasks first
13Promise.resolve().then(() => {
14 console.log('4'); // Microtask
15 setTimeout(() => console.log('5'), 0); // New Macrotask
16});
17
18// 5. Microtasks done → Process one Macrotask
19setTimeout(() => console.log('2'), 0); // Logs 2
20
21// 6. Check Microtasks again (none)
22// 7. Next Macrotask
23setTimeout(() => console.log('5'), 0); // Logs 5
UTF-8Ln 23, Col 0

🏆 Challenge 4: The 'this' Keyword Maze

This tests the 4 rules of this binding and how arrow functions change the game.

What's the Output?

const obj = { name: 'Dev', regular: function() { console.log(this.name); }, arrow: () => { console.log(this.name); }, nested: { name: 'Nested', regular: function() { console.log(this.name); }, arrow: () => { console.log(this.name); } } }; const standalone = obj.regular; obj.regular(); standalone(); obj.arrow(); obj.nested.regular(); obj.nested.arrow();

Answer & 'this' Analysis

"Dev"
undefined
undefined
"Nested"
undefined

1️⃣ obj.regular() - Implicit: this = obj

2️⃣ standalone() - Default: this = undefined (strict mode)

3️⃣ obj.arrow() - Arrow: inherits lexical this

4️⃣ obj.nested.regular() - Implicit: this = nested

5️⃣ obj.nested.arrow() - Arrow: inherits lexical this

Example.js
JAVASCRIPT
1// 'this' binding breakdown:
2
3// 1. Implicit Binding ✅
4obj.regular(); // this = obj → "Dev"
5
6// 2. Default Binding (strict mode)
7const standalone = obj.regular;
8standalone(); // this = undefined → undefined.name = TypeError
9
10// 3. Arrow Function - No own 'this'
11obj.arrow(); // Inherits from global scope → undefined
12
13// 4. Nested Implicit Binding ✅
14obj.nested.regular(); // this = obj.nested → "Nested"
15
16// 5. Nested Arrow Function - No own 'this'
17obj.nested.arrow(); // Inherits from global scope → undefined
18
19// Arrow functions don't create their own 'this'
20// They inherit 'this' from the surrounding scope (lexical scope)
UTF-8Ln 20, Col 0

🏆 Challenge 5: Advanced Closure Counter

This tests closure understanding with functions returning functions that maintain state.

What's the Output?

function createCounter() { let count = 0; return { increment: () => ++count, decrement: () => --count, reset: () => count = 0, getValue: () => count }; } const counter1 = createCounter(); const counter2 = createCounter(); counter1.increment(); counter1.increment(); counter2.increment(); console.log(counter1.getValue()); console.log(counter2.getValue()); counter1.reset(); console.log(counter1.getValue()); console.log(counter2.getValue());

Answer & Closure Analysis

2
1
0
1

🧠 Each createCounter() creates independent closure

📊 counter1 increments to 2

📊 counter2 increments to 1 (separate from counter1)

🔄 counter1.reset() affects only counter1

📊 counter2 remains at 1

Example.js
JAVASCRIPT
1// Visualizing the closures:
2
3// counter1 closure:
4// count: 0 → 1 → 2
5const counter1 = createCounter();
6counter1.increment(); // count = 1
7counter1.increment(); // count = 2
8
9// counter2 closure (completely separate):
10// count: 0 → 1
11const counter2 = createCounter();
12counter2.increment(); // count = 1
13
14// Each counter maintains its own 'count' variable
15// They don't interfere with each other because
16// they have separate closure scopes
17
18// Reset only affects counter1's closure
19counter1.reset(); // counter1.count = 0
20// counter2.count is still 1
UTF-8Ln 20, Col 0

How to Approach Output Questions

  1. Identify the concept being tested (closures, hoisting, event loop, etc.)
  2. Mental execution - trace the code step by step
  3. Consider edge cases - what happens with undefined, null, etc.
  4. Explain the 'why' - interviewers want your reasoning, not just the answer
08

Bonus Materials

Beyond The Interview

Quick Reference Cheat Sheet

Data Types

Primitives:7 types
typeof null:"object"
Check Array:Array.isArray()

This Binding

obj.method():obj
call/apply:first arg
new Func():new object
Arrow func:lexical

Event Loop

Sync First:
Microtasks:Priority
Macrotasks:Later
Rule:All micro → one macro

Common Real World Interview Questions

React Native Focus

  • "Implement debounce for search input in React Native"

    They wanted useCallback and optimization discussion

  • "Why does this useEffect cause infinite re-renders?"

    Missing dependencies or incorrect closure usage

JavaScript Deep Dive

  • "Write Promise.race() from scratch"

    Testing Promise understanding and async patterns

  • "Optimize this React component for performance"

    Memo, useCallback, useMemo in action

What's Next? Your Learning Path

Immediate Next Steps (This Week)

  • 1
    Master the Event Loop (draw it daily)
  • 2
    Practice 10 output questions
  • 3
    Implement 3 array polyfills
  • 4
    Find a study partner

Advanced Topics (Next Month)

  • React.js Interview Questions
  • React Native Specific Topics
  • TypeScript Advanced Patterns
  • System Design for Mobile Apps

You've Got This!

Remember, every senior developer was once a junior struggling with closures and the event loop. The difference isn't talent - it's consistency. Study a little every day, draw concepts, explain them to others, and practice relentlessly.

"The best time to plant a tree was 20 years ago. The second best time is now." - Chinese Proverb

You Made It!

Ready to Ace Your Interview?

You've just covered 100+ JavaScript interview questions that differentiate junior developers from senior engineers. From fundamental data types to complex event loop mechanics, you now have the knowledge that gets you hired.

8 Complete Sections
25+ Code Examples
5 Output Challenges
Real Experience

Continue Your Learning Journey

01

React.js Interview Guide

Hooks, Virtual DOM, Performance, State Management - Everything you need for React interviews.

Coming Soon
02

React Native Guide

Native modules, Performance optimization, Platform-specific code - Mobile development mastery.

In Progress
03

System Design

Scalability, Database design, Caching, Architecture patterns for senior roles.

Planned

Your Journey Starts Now

Knowledge is useless without application. Practice these concepts, build projects, contribute to open source, and most importantly - never stop learning. The tech world waits for no one, but it rewards those who persist.

"The expert in anything was once a beginner. The difference is persistence, not talent."

Frequently Asked Questions

How long should I study?

Dedicate 1-2 hours daily for 2-3 weeks. Focus on understanding concepts, not memorizing.

Are these questions outdated?

Updated for 2026. JavaScript fundamentals don't change much, but I've included ES2021+ features.

Can I use this for React interviews?

Absolutely! React is built on JavaScript. Understanding these fundamentals is crucial for React interviews.

Where can I practice more?

I highly recommend building small projects. Try implementing a debounced search bar or a deep clone function in a real app.

One Final Word

Remember, interviews are conversations, not interrogations. Be yourself, show your thought process, and don't be afraid to say "I don't know, but here's how I'd figure it out." That's what senior developers do every day.

Recommended Resources
How To Practice Coding Every Day
Han Shavir

Build a Consistent Coding Habit

Stop guessing and start building. This e-book provides practical strategies, exercises, and routines to help you code regularly and improve steadily.

Get E-Book
How to Read and Understand Other People's Code
Han Shavir

Master Unfamiliar Codebases

Struggling to make sense of someone else's code? Learn practical strategies to navigate, analyze, and master unfamiliar codebases with confidence.

Get E-Book

Tags

#JavaScript#Interview#Web Development#2026#Front-end#ES6
Dev Kant Kumar

Dev Kant Kumar

Author

Full Stack Developer passionate about crafting high-performance user experiences. I write about Agentic AI, React, and the future of web development.

💬 Discussion

Recommended Resources
How To Practice Coding Every Day
Han Shavir

Build a Consistent Coding Habit

Stop guessing and start building. This e-book provides practical strategies, exercises, and routines to help you code regularly and improve steadily.

Get E-Book
How to Read and Understand Other People's Code
Han Shavir

Master Unfamiliar Codebases

Struggling to make sense of someone else's code? Learn practical strategies to navigate, analyze, and master unfamiliar codebases with confidence.

Get E-Book