100 ES6 (Modern JavaScript) Interview Questions and Answers (2026)
The most asked ES6 (Modern JavaScript) interview questions with structured answers — a quick answer, a clear explanation and working code for each. Covers basics for freshers through advanced, scenario and coding questions for experienced developers.
Updated November 2026 Reviewed by Abhishek Kumar 120 min read
100 ES6 (Modern JavaScript) interview questions, grouped by level: freshers, intermediate, experienced and coding.
Every answer starts with a one-line “Quick answer” you can say out loud, followed by the explanation and runnable code.
Use the filter bar to practise only the level you are interviewing for, then test yourself with the free ES6 (Modern JavaScript) quiz.
100 shown
Basic ES6 (Modern JavaScript) Interview Questions for Freshers
15 questions
Start here if you are a fresher or switching to ES6 (Modern JavaScript). These fundamentals are asked in almost every first-round and campus interview.
1
How interviewers ask it“In simple words, what is JavaScript? Explain it like you would to a new teammate.”
Quick answerJavaScript is a high-level, interpreted scripting language used to create dynamic and interactive web pages. It is one of the core technologies of the World Wide Web.
Client-side: Runs in the browser
Server-side: Runs on Node.js
Event-driven: Responds to user actions
Prototype-based: Uses prototypal inheritance
Functional: Supports functional programming
JavaScript
// Hello World in JavaScriptconsole.log("Hello, World!");
Quick answerJavaScript is an interpreted language, meaning it is executed line by line by the browser's JavaScript engine. However, modern JavaScript engines use Just-In-Time (JIT) compilation for performance optimization.
Interpreted: Executed at runtime without compilation
JIT Compilation: Modern engines compile hot code
Runtime: Code runs in the browser or Node.js
Dynamic: Types are determined at runtime
JavaScript
// Variables in JavaScriptvar old = "function scoped";
let block = "block scoped";
const constant = "cannot be reassigned";
console.log(old);
console.log(block);
console.log(constant);
Quick answerAn object is a collection of key-value pairs. Objects can contain properties and methods, and can be created using object literals or constructors.
Quick answerDOM (Document Object Model) is a programming interface for HTML documents. It represents the page structure as a tree of objects that can be manipulated with JavaScript.
Tree Structure: Document -> Elements -> Attributes
Quick answerAn event is an action that occurs in the browser, such as user interaction or system events. JavaScript can respond to events using event listeners.
Quick answerundefined is a primitive value that indicates a variable has been declared but not assigned a value. It is the default value of uninitialized variables.
Type: typeof undefined returns "undefined"
Assignment: Automatically assigned to uninitialized variables
Quick answerNaN (Not-a-Number) is a special numeric value that indicates an invalid or unrepresentable number. It is returned when mathematical operations fail.
Questions for candidates with 1–3 years of experience — the concepts interviewers use to check that you have actually built things with ES6 (Modern JavaScript).
16
How interviewers ask it“Walk me through hoisting in modern JavaScript. Where does it come up in real systems?”
Quick answerHoisting is JavaScript's behavior of moving declarations to the top of their scope during compilation. Variables and functions are hoisted differently.
Function Declarations: Fully hoisted
var Variables: Hoisted but initialized as undefined
let/const Variables: Hoisted but in Temporal Dead Zone
Quick answerA closure is a function that has access to variables from its outer (enclosing) scope even after the outer function has returned. It "closes over" the variables.
Creation: Function defined inside another function
Access: Can access outer function's variables
Use Cases: Private variables, currying, event handlers
Memory: Variables remain in memory as long as closure exists
Quick answerScope determines the visibility and accessibility of variables in different parts of the code. JavaScript has global, function, and block scope.
Global Scope: Variables accessible everywhere
Function Scope: Variables accessible within function
Block Scope: Variables accessible within block (let/const)
Quick answerA callback function is a function passed as an argument to another function and executed later, often after an asynchronous operation completes.
Definition: Function passed as parameter
Execution: Called inside the receiving function
Use Cases: Event handlers, async operations, array methods
Callback Hell: Nested callbacks leading to unreadable code
JavaScript
// Array Methods in JavaScriptconst arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// map - transform each elementconst doubled = arr.map(x => x * 2);
console.log(doubled);
// filter - select elementsconst evens = arr.filter(x => x % 2 === 0);
console.log(evens);
// reduce - aggregateconst sum = arr.reduce((acc, x) => acc + x, 0);
console.log(sum);
// forEach - iterate
arr.forEach(x =>console.log(x));
// find - find first matchconst first = arr.find(x => x > 5);
console.log(first);
// findIndex - find index of first matchconst index = arr.findIndex(x => x > 5);
console.log(index);
// some - check if any matchconst hasEven = arr.some(x => x % 2 === 0);
console.log(hasEven);
// every - check if all matchconst allEven = arr.every(x => x % 2 === 0);
console.log(allEven);
// includes - check if value existsconst includes = arr.includes(5);
console.log(includes);
// sort - sort arrayconst sorted = [...arr].sort((a, b) => a - b);
console.log(sorted);
// reverse - reverse arrayconst reversed = [...arr].reverse();
console.log(reversed);
// slice - create subarrayconst sliced = arr.slice(2, 5);
console.log(sliced);
// splice - modify arrayconst spliced = [...arr];
spliced.splice(2, 3, 99, 100);
console.log(spliced);
// concat - merge arraysconst merged = arr.concat([11, 12, 13]);
console.log(merged);
// flat - flatten nested arraysconst nested = [1, [2, 3], [4, [5, 6]]];
const flattened = nested.flat(2);
console.log(flattened);
Quick answerJSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate.
Format: Key-value pairs, arrays, nested objects
Methods: JSON.stringify() and JSON.parse()
Data Types: Strings, numbers, booleans, arrays, objects, null
Quick answerA promise is an object representing the eventual completion or failure of an asynchronous operation. It provides a cleaner way to handle async code than callbacks.
Quick answerEvent bubbling is the propagation of an event from the target element up through the DOM tree to the root. It allows parent elements to handle events from children.
Direction: Child . Parent . Root
Stop: stopPropagation()
Prevent: preventDefault()
Capturing Phase: Opposite direction (root -> child)
JavaScript
// Template Literals in JavaScript// Basic template literalconst name = "Alice";
const greeting = `Hello, ${name}!`;
console.log(greeting);
// Multi-line stringsconst multiLine = `
This is a
multi-line
string
`;
console.log(multiLine);
// Expression interpolationconst a = 5, b = 10;
console.log(`${a} + ${b} = ${a + b}`);
// Nested templatesconst isAdmin = true;
const message = `User is ${isAdmin ? `an admin` : `a regular user`}`;
console.log(message);
// Tagged templatesfunctionhighlight(strings, ...values) {
return strings.reduce((acc, str, i) => {
return acc + str + (values[i] ? `<b>${values[i]}</b>` : "");
}, "");
}
const highlighted = highlight`Hello ${name}, you are ${age} years old`;
console.log(highlighted);
// Raw stringsconst raw = String.raw`Hello\nWorld`;
console.log(raw); // Hello\nWorld (not escaped)// Template literals in loopsconst items = ["Apple", "Banana", "Orange"];
const list = items.map(item =>`<li>${item}</li>`).join("");
console.log(list);
Quick answerEvent delegation is a technique where a parent element handles events for its children using event bubbling. It reduces the number of event listeners needed.
Benefits: Fewer listeners, handles dynamic elements
Quick answerArrow functions provide a shorter syntax for writing functions and have lexical this binding. They are commonly used for callbacks and functional programming.
Quick answerThe filter() method creates a new array with elements that pass a test implemented by a provided function. It does not modify the original array.
Syntax: array.filter(callback)
Return: New array with elements that pass the test
Quick answerCurrying is the technique of transforming a function that takes multiple arguments into a sequence of functions that each take a single argument.
Benefits: Partial application, function composition
Implementation: Return functions for each argument
Quick answerDebouncing is a technique that limits how often a function is called by delaying its execution until after a specified time has passed since the last call.
Quick answerThe event loop is a mechanism that handles asynchronous callbacks in JavaScript. It continuously checks the call stack and task queues to execute pending tasks.
Quick answerA memory leak occurs when memory that is no longer needed is not released. JavaScript's garbage collector handles most memory, but leaks can still happen.
Causes: Global variables, forgotten timers, closures
Detection: Browser DevTools memory profiler
Prevention: Clean up, use WeakMap/WeakSet
Impact: Performance degradation, crashes
JavaScript
// Memory Leaks in JavaScript// Common memory leak sources// 1. Global variablesfunctionleak() {
globalVar = "I'm global"; // Implicit global
}
leak();
// 2. Forgotten timersfunctiontimerLeak() {
let element = document.getElementById("leak");
setInterval(() => {
console.log(element.id);
}, 1000);
}
// 3. Event listeners not removedfunctioneventListenerLeak() {
let element = document.getElementById("leak");
element.addEventListener("click", functionhandler() {
console.log("Clicked");
});
// element removed but listener remains
}
// 4. Closures holding referencesfunctionclosureLeak() {
let largeData = newArray(1000000);
returnfunction() {
console.log(largeData.length);
};
}
const leakyClosure = closureLeak();
// 5. DOM referencesfunctiondomReferenceLeak() {
let element = document.getElementById("leak");
document.body.removeChild(element);
// element still holds reference
}
// Prevention// 1. Use 'use strict'// 2. Clear timersclearTimeout(timeoutId);
clearInterval(intervalId);
// 3. Remove event listeners
element.removeEventListener("click", handler);
// 4. Nullify references
element = null;
// 5. Use WeakMap and WeakSetconst cache = newWeakMap();
const obj = {};
cache.set(obj, "value");
// When obj is garbage collected, entry is removed
Quick answerA module is a reusable piece of code that exports specific functionality and can be imported by other modules. ES6 introduced native module support.
Export: export keyword
Import: import keyword
Default Export: export default
Dynamic Import: import() for lazy loading
JavaScript
// ES6 Modules Advanced// module.jsexportconst data = { id: 1, name: "Alice" };
exportfunctionprocess() { return"processing"; }
// Default exportexportdefaultclassUser {
constructor(name) { this.name = name; }
}
// Import with aliasimportUser, { data as userData, process } from'./module.js';
// Re-exportingexport { data, process } from'./module.js';
export * from'./module.js';
// Import namespaceimport * asModulefrom'./module.js';
console.log(Module.data);
// Dynamic import (lazy loading)asyncfunctionloadModule() {
constmodule = awaitimport('./module.js');
console.log(module.default);
}
// Module import for side effectsimport'./styles.css';
// JSON imports (with import assertions)import data from'./data.json' assert { type: "json" };
console.log(data);
// Module variablesconsole.log(import.meta.url); // Current module URLconsole.log(import.meta); // Module metadata// Exporting typesexport interface User {
name: string;
age: number;
}
// Export with dynamic bindingexportlet counter = 0;
exportfunctionincrement() {
counter++;
}
Quick answerIIFE (Immediately Invoked Function Expression) is a function that is defined and executed immediately after creation. It creates a private scope.
Syntax: (function() {})()
Purpose: Private variables, module pattern
Arrow IIFE: (() => {})()
Use Cases: Module pattern, avoiding global scope
JavaScript
// IIFE (Immediately Invoked Function Expression)// Basic IIFE
(function() {
console.log("IIFE executed!");
})();
// IIFE with parameters
(function(name) {
console.log(`Hello, ${name}!`);
})("Alice");
// Arrow function IIFE
(() => {
console.log("Arrow IIFE");
})();
// IIFE with return valueconst result = (function() {
let count = 0;
return {
increment() { count++; },
decrement() { count--; },
getCount() { return count; }
};
})();
// IIFE for private variablesconst counterModule = (function() {
let privateCounter = 0;
functionchangeBy(val) {
privateCounter += val;
}
return {
increment() { changeBy(1); },
decrement() { changeBy(-1); },
value() { return privateCounter; }
};
})();
// IIFE for module patternconst myModule = (function() {
// Privateconst privateData = [];
// Publicreturn {
add(item) {
privateData.push(item);
},
get() {
return [...privateData];
}
};
})();
// IIFE in loops (pre-ES6)for (var i = 0; i < 3; i++) {
(function(index) {
setTimeout(() => {
console.log(index);
}, 100);
})(i);
}
// With let (no IIFE needed)for (let i = 0; i < 3; i++) {
setTimeout(() =>console.log(i), 100);
}
ES6 (Modern JavaScript) Coding Interview Questions (Programs with Code)
60 questions
Hands-on ES6 (Modern JavaScript) programs that are asked in coding rounds and machine tests. Read the code, then try writing it yourself without looking.
41
How interviewers ask it“Can you reverse a string in modern JavaScript? Then walk me through the edge cases you would test.”
Quick answerFizzBuzz prints numbers from 1 to n, but for multiples of 3 print "Fizz", for multiples of 5 print "Buzz", and for multiples of both print "FizzBuzz".
Logic: Check divisibility by 3 and 5
Order: Check 15 first, then 3, then 5
Output: Print each result
Use Cases: Common interview question
JavaScript
// FizzBuzzfunctionfizzBuzz(n) {
for (let i = 1; i <= n; i++) {
if (i % 15 === 0) console.log("FizzBuzz");
elseif (i % 3 === 0) console.log("Fizz");
elseif (i % 5 === 0) console.log("Buzz");
elseconsole.log(i);
}
}
fizzBuzz(15);
Quick answerMerge sort is a divide-and-conquer algorithm that divides the array into halves, recursively sorts them, and merges the results. O(n log n) time.
Algorithm: Divide, recursively sort, merge
Merge Function: Merge two sorted arrays
Stable: Maintains relative order of equal elements
Time Complexity: O(n log n) guaranteed
JavaScript
// Merge sortfunctionmergeSort(arr) {
if (arr.length <= 1) return arr;
const mid = Math.floor(arr.length / 2);
const left = mergeSort(arr.slice(0, mid));
const right = mergeSort(arr.slice(mid));
returnmerge(left, right);
}
functionmerge(left, right) {
const result = [];
let i = 0, j = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) result.push(left[i++]);
else result.push(right[j++]);
}
return [...result, ...left.slice(i), ...right.slice(j)];
}
Quick answerThe once function ensures a function is called only once, regardless of how many times it's invoked. Subsequent calls return the cached result.
Method: Track if function has been called
Implementation: Use a closure with a flag
Use Cases: Initialization, setup operations
Thread Safety: Not needed in single-threaded JavaScript
JavaScript
// Once functionfunctiononce(fn) {
let called = false;
let result;
returnfunction(...args) {
if (!called) {
called = true;
result = fn(...args);
}
return result;
};
}
const initialize = once(() => {
console.log("Initialized");
return { id: 1, name: "App" };
});
initialize(); // Prints "Initialized"initialize(); // Returns cached result
Quick answerDebounce with leading edge executes the function immediately on the first call, then waits for the delay period before allowing another execution.
Method: Track last call time
Implementation: Immediate execution, then cooldown
Use Cases: Save actions, API calls
Difference: Leading vs trailing edge
JavaScript
// Debounce with leading edgefunctiondebounceLeading(func, delay) {
let timeoutId;
let lastCall = 0;
returnfunction(...args) {
const now = Date.now();
if (now - lastCall < delay) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
lastCall = Date.now();
func.apply(this, args);
}, delay);
} else {
lastCall = now;
func.apply(this, args);
}
};
}
Quick answerThe Observable pattern allows objects to subscribe to changes and get notified when the observable state changes. It's a popular pattern in reactive programming.
Quick answerThe Singleton pattern ensures that a class has only one instance and provides a global point of access to it. Useful for configuration, logging, and caching.
Implementation: Store instance in static property
Lazy Initialization: Create instance only when needed
Quick answerThe Factory pattern provides a way to create objects without specifying the exact class. It encapsulates object creation logic and provides flexibility.
Quick answerThe Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. It allows the algorithm to vary independently.
Quick answerThe Observer pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified automatically.
Quick answerThe Command pattern encapsulates a request as an object, thereby allowing for parameterization of clients with different requests, queuing, logging, and undo operations.
Quick answerThe Memento pattern captures and externalizes an object's internal state so that the object can be restored to that state later without violating encapsulation.
Quick answerThe Mediator pattern defines an object that encapsulates how a set of objects interact. It promotes loose coupling by keeping objects from referring to each other explicitly.
Quick answerThe Chain of Responsibility pattern passes a request along a chain of handlers until one of them handles it. Each handler decides whether to process the request or pass it on.
Quick answerThe Proxy pattern provides a surrogate or placeholder for another object to control access to it. It can add behavior like caching, logging, or access control.
Quick answerThe Flyweight pattern minimizes memory usage by sharing as much data as possible with similar objects. It's useful for large numbers of similar objects.
Quick answerThe Bridge pattern decouples an abstraction from its implementation so that the two can vary independently. It's useful for separating interface from implementation.
Quick answerThe Adapter pattern converts the interface of a class into another interface that clients expect. It allows incompatible interfaces to work together.
Quick answerThe Composite pattern composes objects into tree structures to represent part-whole hierarchies. It lets clients treat individual objects and compositions uniformly.
Quick answerThe Visitor pattern lets you add further operations to objects without having to modify them. It separates an algorithm from the object structure.
Visitor: Defines operations
Element: Accepts visitors
Benefits: Adding new operations without modifying elements
Quick answerThe Iterator pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
Iterator: Traverses collection
Aggregate: Creates iterator
Benefits: Uniform traversal, multiple iterators
Use Cases: Collection traversal, custom data structures
Quick answerThe Template Method pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. It lets subclasses redefine certain steps without changing the algorithm's structure.
Quick answerThe Prototype pattern creates new objects by cloning an existing object, rather than instantiating new ones. It's useful when creating objects is expensive.
ES6 (ECMAScript 2015) is a major JavaScript update that introduced modern language features such as let, const, arrow functions, classes, modules, promises, template literals, destructuring, and more.
What is the difference between var, let, and const?
var is function-scoped, while let and const are block-scoped. const cannot be reassigned after initialization.
What are arrow functions?
Arrow functions provide a shorter syntax for writing functions and inherit the surrounding lexical this value.
What is destructuring in ES6?
Destructuring allows extracting values from arrays and objects into individual variables using concise syntax.
What is the spread operator?
The spread operator (...) expands arrays, objects, or iterable elements into individual values.
What are JavaScript Promises?
Promises represent the eventual completion or failure of an asynchronous operation and its resulting value.
What is async/await?
async/await simplifies asynchronous programming by allowing asynchronous code to be written in a synchronous style using Promises.
What are ES6 modules?
ES6 modules allow JavaScript code to be organized into reusable files using import and export statements.
Why is ES6 important?
ES6 introduced modern JavaScript features that improve code readability, maintainability, modularity, and support for large-scale application development.
AK
Written and reviewed by Abhishek Kumar
Founder, InterviewPitch · 10+ years in IT. Questions are collected from real interview rounds and refreshed regularly. Spotted an error? Tell us.