JavaScript Notes
HubYour First JavaScript Program — Hello World & Beyond Complete Guide 2026History of JavaScript — Complete Timeline from 1995 to 2026How JavaScript Runs — Complete Guide to Execution, Call Stack & Event LoopJavaScript Engine Explained — V8, JIT Compilation & How Code Gets FastJavaScript Use Cases — 15 Things You Can Build with JavaScript (2026)JavaScript vs Other Languages — Complete Comparison Guide 2026What is JavaScript? Complete BeginnerWhy Learn JavaScript in 2026? Career, Salary, Scope & Benefits GuideJavaScript Break Statement Tutorial – Complete Guide with ExamplesJavaScript Break and Continue Statements – Complete Guide with ExamplesJavaScript Continue Statement Tutorial – Skip Iterations with ExamplesJavaScript Do While Loop Tutorial – Execute at Least Once with ExamplesJavaScript Do-While Loop Tutorial – Complete Guide with ExamplesJavaScript For Loop Tutorial – Complete Guide with ExamplesJavaScript If Statement Tutorial – Conditional Logic with ExamplesJavaScript If Else Statement Tutorial – Complete Guide with ExamplesJavaScript If Statement Tutorial – Complete Guide with ExamplesJavaScript Nested If Statement Tutorial – Multi-Level Conditions with ExamplesNested Loops in JavaScriptJavaScript Control Flow Practice Programs – 20+ Exercises with SolutionsJavaScript Switch Statement Tutorial – Case Matching with ExamplesSwitch Statement in JavaScriptJavaScript While Loop Tutorial – Complete Guide with ExamplesJavaScript Arrow Functions Tutorial – Syntax, Use Cases & this BindingJavaScript Callback Functions Explained – Synchronous & AsynchronousJavaScript Closures Explained – Lexical Scope, Private State & MemoryJavaScript Function Declaration Tutorial – Hoisting, Syntax & ScopeJavaScript Function Expression Tutorial – Anonymous, Named & AssignedJavaScript Higher Order Functions Tutorial – map, filter, reduce & Custom HOFsJavaScript IIFE Explained – Immediately Invoked Function ExpressionJavaScript Functions Practice Programs – 20+ Exercises with SolutionsJavaScript Recursion Tutorial – Call Stack, Base Case & Recursive PatternsJavaScript Array Basics - Complete BeginnerJavaScript Array Methods - Complete Reference Guide with ExamplesJavaScript Array Programs - 20+ Practice Problems with SolutionsJavaScript Arrays Basics - Complete Guide with Examples & DiagramsJavaScript Array filter() Method - Complete Tutorial with ExamplesJavaScript filter() Method — Complete Guide with Examples 2026JavaScript Array find() Method - Complete Tutorial with ExamplesJavaScript find() & findIndex() — Complete Guide 2026JavaScript Array map() Method - Complete Tutorial with ExamplesJavaScript map() Method — Transform Arrays Complete Guide 2026JavaScript map() vs forEach() - Key Differences with ExamplesJavaScript Array push() and pop() - Complete Tutorial with ExamplesJavaScript Array reduce() Method - Complete Tutorial with ExamplesJavaScript reduce() Method — Complete Deep Dive with Examples 2026JavaScript Array shift() and unshift() - Complete Tutorial with ExamplesJavaScript Array sort() Method - Complete Tutorial with ExamplesJavaScript splice() vs slice() - Complete Tutorial with ExamplesJavaScript Object Destructuring - Complete Guide with ExamplesJavaScript Objects - Complete Guide to Object Basics with ExamplesJavaScript Object Methods - Built-in Methods & Custom Methods Complete GuideJavaScript Object Programs - Practice Problems with SolutionsJavaScript Object Properties - Keys, Values, Descriptors & Dynamic PropertiesJavaScript Rest Operator (...) - Parameters, Destructuring & Complete GuideJavaScript Spread Operator (...) - Complete Guide with ExamplesJavaScript this Keyword - Complete Guide with Binding Rules & ExamplesJavaScript String Basics - Complete Guide to Strings with ExamplesJavaScript String Methods - Complete Reference with Examples & OutputJavaScript String Programs - Practice Problems with SolutionsJavaScript String Replacing - replace(), replaceAll() & Regex Patterns GuideJavaScript String Searching Methods - includes, indexOf, startsWith, match GuideJavaScript Template Literals (ES6) - Complete Guide with Tagged TemplatesJavaScript DOM Changing Content - textContent, innerHTML, setAttribute Complete GuideJavaScript DOM Changing Styles - CSS Manipulation, classList & getComputedStyleJavaScript DOM Creating Elements - createElement, appendChild, DocumentFragment GuideJavaScript DOM Introduction - Complete Guide to Document Object ModelJavaScript DOM Traversal - Navigate Parent, Child & Sibling NodesJavaScript DOM Forms - Form Handling, Validation & FormData Complete GuideJavaScript localStorage - Complete Guide to Web Storage APIlocalStorage vs sessionStorage - JavaScript Web Storage Comparison GuideJavaScript DOM Removing Elements - remove(), removeChild() Complete GuideJavaScript DOM Selecting Elements - querySelector, getElementById Complete GuideJavaScript sessionStorage - Complete Guide to Session-Based Web StorageJavaScript Click Event - addEventListener, Event Handler Complete GuideEvent Bubbling in JavaScript – Complete Guide with Examples (2026)Event Capturing in JavaScript – Complete Guide to Capture Phase (2026)Event Delegation in JavaScript – Complete Guide with Examples (2026)JavaScript Event Object – Complete Guide with Examples (2026)JavaScript Form Events – Complete Guide with Examples (2026)JavaScript Keyboard Events – Complete Guide to keydown, keyup & Key Properties (2026)JavaScript Mouse Events – Complete Guide with Examples (2026)JavaScript Async Await - Complete Guide with Examples & Error HandlingJavaScript Call Stack - Complete Guide with Visual Diagrams & ExamplesJavaScript Callback Queue (Task Queue) - Complete Guide with DiagramsJavaScript Callbacks - Complete Guide with Callback Hell & PatternsJavaScript Event Loop - Complete Guide with Visual Diagrams & ExamplesJavaScript Fetch API - Complete Guide with Examples, Error Handling & Async/AwaitJSON in JavaScript - Complete Guide: Parse, Stringify, Fetch & Error HandlingJavaScript Promise.all, Promise.race, Promise.any, Promise.allSettled — Complete Guide 2026JavaScript Promises - Complete Guide with Chaining, Error Handling & Event LoopSynchronous vs Asynchronous JavaScript — Complete Explanation 2026JavaScript Web APIs - Complete Guide: setTimeout, fetch, DOM Events & MoreClosures in JavaScript — Complete Guide with Examples 2026Hoisting in JavaScript — Complete Guide with Examples 2026Prototype in JavaScript — Complete Guide with Examples 2026Scope in JavaScript — Complete Guide with Examples 2026Browser Object Model (BOM) in JavaScript — Complete GuideCanvas API in JavaScript — Complete Drawing & Animation GuideDrag and Drop API in JavaScript — Complete TutorialGeolocation API in JavaScript — Get User Location TutorialHistory API in JavaScript — SPA Routing & pushState GuideNotification API in JavaScript — Push Notifications TutorialService Workers in JavaScript — Offline, Caching & PWA GuideWeb Storage API in JavaScript — localStorage & sessionStorage GuideWeb Workers in JavaScript — Multithreading & Background Tasks GuideJavaScript Interview — Behavioral Questions and Soft Skills Guide 2026Common JavaScript Interview Mistakes — What to Avoid 2026JavaScript Interview Tips — Strategy and Preparation Guide 2026JavaScript Mock Interview — Practice Questions with Solutions 2026JavaScript System Design — Frontend Architecture Interview Guide 2026JavaScript apply() Method - Complete Guide with ExamplesJavaScript bind() Method - Complete Guide with ExamplesJavaScript call() Method - Complete Guide with ExamplesJavaScript call() vs apply() vs bind() - Complete Comparison GuideJavaScript Currying - Complete Guide with ExamplesJavaScript Debounce - Complete Guide with Timeline DiagramsJavaScript Execution Context - Complete Guide with Stack DiagramsJavaScript Garbage Collection - Memory Lifecycle & Mark-and-Sweep GuideJavaScript Generators - Complete Guide with yield and IterationJavaScript Hoisting - Complete Guide with var, let, const & FunctionsJavaScript Iterators - Complete Guide with Iterator ProtocolJavaScript Lexical Scope - Complete Guide with Scope Chain DiagramsJavaScript Memory Management - Complete Guide with Lifecycle DiagramsJavaScript Modules - Complete Guide with import export ExamplesJavaScript Scope - Complete Guide with var, let, const & Scope ChainJavaScript Symbols - Complete Guide with Well-Known SymbolsJavaScript Throttle - Complete Guide with Timeline DiagramsJavaScript Comments Complete Guide – Single Line, Multi-line & JSDoc with ExamplesJavaScript Data Types Complete Guide – Primitives, Objects & typeof with ExamplesJavaScript Input and Output Complete Guide – console.log, prompt, alert & DOM with ExamplesJavaScript Keywords Complete Guide – Reserved Words List with Examples for BeginnersJavaScript null vs undefined – Complete Guide with Differences, Examples & Interview Q&AJavaScript Operators Complete Guide – Arithmetic, Comparison, Logical & More with ExamplesJavaScript Strict Mode Complete Guide – JavaScript Type Conversion Complete Guide – Explicit & Implicit Coercion with ExamplesJavaScript var vs let vs const – Complete Guide with Scope, Hoisting & Best PracticesJavaScript Variables Complete Guide – Declaration, Naming Rules & Memory Model for BeginnersDeque (Double-Ended Queue) in JavaScript — Complete GuideLinked List in JavaScript — Nodes, Pointers & Operations GuideJavaScript Map — Key-Value Data Structure Complete GuideJavaScript Numbers — IEEE 754, Precision, and Number Methods GuidePriority Queue in JavaScript — Min Heap Implementation GuideQueue Data Structure in JavaScript — FIFO, Enqueue & Dequeue ExplainedJavaScript Set — Unique Values Data Structure GuideSorting Algorithms in JavaScript — Bubble, Merge, Quick Sort GuideStack Data Structure in JavaScript — LIFO, Push, Pop ExplainedJavaScript Typed Arrays — ArrayBuffer, Int32Array, Float64Array GuideJavaScript WeakMap — Weak References, Memory Management GuideJavaScript WeakSet — Complete Guide with Examples 2026Applications of JavaScript — Where JS is Used in 2026 Complete GuideJavaScript Backend Frameworks — Node.js, Express, NestJS Complete Guide 2026JavaScript Frontend Libraries — React, Vue, Angular, Svelte Complete Overview 2026JavaScript Full-Stack Frameworks — Next.js, Remix, Astro Complete Guide 2026JavaScript Career Paths & Jobs — Salary, Roles & Roadmap 2026JavaScript Libraries vs Frameworks — Difference & Examples Complete Guide 2026JavaScript Custom Errors – Extend Error Class, Custom Error Types & instanceofJavaScript Debugging – console Methods, DevTools, Breakpoints & Error Stack TracesJavaScript throw Statement – Throw Errors, Custom Messages & Error TypesJavaScript Try Catch Finally – Error Handling Complete GuideTop 30 JavaScript Closure Interview Questions & Answers 2026Top 30 JavaScript Coding Interview Questions 2026 (With Solutions)Top 25 JavaScript Event Loop Interview Questions & Answers 2026Top 50 JavaScript Interview Questions & Answers 2026Top 30 JavaScript Promise Interview Questions & Answers 202650 Tricky JavaScript Output Questions 2026 (With Answers)Build a JavaScript Calculator - Step by Step Project TutorialBuild a JavaScript Image Carousel - Step by Step Project TutorialBuild a JavaScript Counter Application - Step by Step Project TutorialBuild a JavaScript Digital Clock - Step by Step Project TutorialBuild a Dynamic Resume Builder in JavaScript - Step by Step TutorialBuild a JavaScript Email Validator - Step by Step Project TutorialBuild a JavaScript Employee Database Management App - Step by Step TutorialBuild a JavaScript Expense Tracker - Step by Step Project TutorialBuild a GitHub Profile Search App in JavaScript - Step by Step TutorialBuild a JavaScript Image Slider - Step by Step Project TutorialBuild a JavaScript Multi-Step Progress Bar - Step by Step TutorialBuild JavaScript Nested Chat Comments - Step by Step Project TutorialBuild a JavaScript Notes App - Step by Step Project TutorialBuild a JavaScript OTP Input Field - Step by Step Project TutorialBuild a JavaScript Palindrome Checker - Step by Step Project TutorialBuild a JavaScript Price Range Slider - Step by Step Project TutorialBuild a JavaScript Prime Number Checker - Step by Step Project TutorialBuild a JavaScript QR Code Generator - Step by Step Project TutorialBuild a JavaScript QR Code Scanner - Step by Step Project TutorialBuild a JavaScript Quiz App - Step by Step Project TutorialBuild a JavaScript Random Number Generator - Step by Step TutorialBuild a JavaScript Random Password Generator - Step by Step TutorialJavaScript Image Resize & Compress — Canvas API Project 2026JavaScript Responsive Admin Dashboard — DOM & CSS Project 2026JavaScript Show/Hide Password Toggle — Beginner DOM Project 2026JavaScript Sortable Filterable Table — DOM & Array Methods Project 2026JavaScript Stopwatch Project — setInterval & DOM Tutorial 2026JavaScript Student Grade Calculator — Arrays & Logic Project 2026JavaScript Task Scheduler Project — CRUD & localStorage Tutorial 2026JavaScript Tic-Tac-Toe Game — DOM Manipulation Project Tutorial 2026JavaScript Toast Notification Project — Custom Alerts Tutorial 2026Build a Todo App in JavaScript - Step by Step Project TutorialJavaScript Unicode Character Value Finder — charCodeAt & fromCharCode Project 2026JavaScript Weather App Project — Fetch API & DOM Complete Tutorial 2026JavaScript Cheat Sheet 2026 — Complete Quick ReferenceImportant JavaScript Concepts Every Developer Must Know in 2026JavaScript One Shot Notes 2026 — Complete JS in One PageJavaScript Quick Revision Notes — Interview Prep in 30 Minutes 2026Abstraction in JavaScript OOP – Hide Complexity, Expose SimplicityJavaScript Classes Tutorial – ES6 Class Syntax, Inheritance & MoreJavaScript Constructor Functions – new Keyword, Prototype & OOP PatternsEncapsulation in JavaScript – Private Fields, Getters, Setters & Data ProtectionJavaScript Inheritance – extends, super, and Prototype-Based InheritanceObject-Oriented Programming in JavaScript – OOP Concepts Complete GuideJavaScript OOP Projects – Build Real-World Apps with Classes & OOPPolymorphism in JavaScript – Method Overriding, Duck Typing & Many FormsJavaScript Prototype Chain – How Property Lookup Works in JavaScriptJavaScript Prototypes – Prototype-Based Inheritance, Object.create & prototype PropertyJavaScript Advanced Practice Problems — 15+ Interview-Level Challenges 2026JavaScript Assignments — 10 Project-Based Learning Tasks 2026JavaScript Beginner Practice Problems — 20+ Coding Exercises 2026JavaScript Coding Challenges — 25 Interview-Style Problems 2026JavaScript Intermediate Practice Problems — 20+ Coding Challenges 2026JavaScript MCQs — 50 Multiple Choice Questions with Answers 2026JavaScript Regex Character Classes – [abc], [^abc], Ranges & ShortcutsJavaScript Regex Email Validation – Pattern, Edge Cases & Best PracticesJavaScript Regex Flags – g, i, m, s, u, y Flags Explained with ExamplesJavaScript Regex Groups – Capturing, Non-Capturing & Named GroupsJavaScript Number Validation with Regex — Complete Patterns & Examples 2026JavaScript Password Validation with Regex — Strength Checker & Patterns 2026JavaScript Regex Quantifiers – *, +, ?, {n,m}, Greedy vs Lazy MatchingJavaScript Regex Basics – Regular Expressions Tutorial for BeginnersJavaScript Regex Projects — 10 Practical Mini-Projects with Code 2026JavaScript URL Validation with Regex — Complete Patterns & Examples 2026JavaScript Username Validation with Regex — Patterns & Form Examples 2026JavaScript TutorialJavaScript Lazy Loading — Images, Modules & Components Complete Guide 2026JavaScript Performance Optimization — Speed Up Your Code Complete Guide 2026JavaScript Unit Testing with Jest — Complete Guide for Beginners 2026
Top 30 JavaScript coding interview questions with step-by-step solutions. Covers arrays, strings, objects, recursion, algorithms, and problem-solving patterns for 2026 interviews.
These coding questions test problem-solving ability, not just JavaScript knowledge. They appear in real interviews at product companies, startups, and big tech.
Section 1: Array Problems
Q1: Flatten a Nested Array
Example
// Implement: flattenArray([[1, [2, [3, [4]]]], 5]) → [1, 2, 3, 4, 5]
function flattenArray(arr) {
return arr.reduce((acc, item) => {
if (Array.isArray(item)) {
return acc.concat(flattenArray(item));
}
return acc.concat(item);
}, []);
}
console.log(flattenArray([1, [2, [3, [4]]]]));
console.log(flattenArray([[1, 2], [3, [4, 5]]]));
Output
[1, 2, 3, 4] [1, 2, 3, 4, 5]
Alternative using built-in:
Example
[1, [2, [3]]].flat(Infinity); // Native ES2019+
Q2: Remove Duplicates from Array
Example
function unique(arr) {
return [...new Set(arr)];
}
// Using filter:
function uniqueFilter(arr) {
return arr.filter((item, index) => arr.indexOf(item) === index);
}
console.log(unique([1, 2, 2, 3, 3, 4, 1]));
console.log(unique(["a", "b", "a", "c"]));
Output
[1, 2, 3, 4] ["a", "b", "c"]
Q3: Chunk Array
Example
function chunk(arr, size) {
const result = [];
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
}
console.log(chunk([1, 2, 3, 4, 5], 2));
console.log(chunk([1, 2, 3, 4, 5], 3));
Output
[[1, 2], [3, 4], [5]] [[1, 2, 3], [4, 5]]
Q4: Two Sum
Example
function twoSum(nums, target) {
const map = new Map();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (map.has(complement)) {
return [map.get(complement), i];
}
map.set(nums[i], i);
}
return null;
}
console.log(twoSum([2, 7, 11, 15], 9));
console.log(twoSum([3, 2, 4], 6));
Output
[0, 1] [1, 2]
Time: O(n) | Space: O(n)
Q5: Group By Key
Example
function groupBy(arr, key) {
return arr.reduce((groups, item) => {
const group = item[key];
groups[group] = groups[group] || [];
groups[group].push(item);
return groups;
}, {});
}
const people = [
{ name: "Alice", city: "Delhi" },
{ name: "Bob", city: "Mumbai" },
{ name: "Carol", city: "Delhi" }
];
console.log(groupBy(people, "city"));
Output
{
Delhi: [{ name: "Alice", city: "Delhi" }, { name: "Carol", city: "Delhi" }],
Mumbai: [{ name: "Bob", city: "Mumbai" }]
}Section 2: String Problems
Q6: Check Palindrome
Example
function isPalindrome(str) {
const clean = str.toLowerCase().replace(/[^a-z0-9]/g, "");
return clean === clean.split("").reverse().join("");
}
console.log(isPalindrome("racecar")); // true
console.log(isPalindrome("A man a plan a canal Panama")); // true
console.log(isPalindrome("hello")); // false
Output
true true false
Q7: Check Anagram
Example
function isAnagram(s, t) {
if (s.length !== t.length) return false;
const count = {};
for (const char of s) count[char] = (count[char] || 0) + 1;
for (const char of t) {
if (!count[char]) return false;
count[char]--;
}
return true;
}
console.log(isAnagram("listen", "silent")); // true
console.log(isAnagram("hello", "world")); // false
Output
true false
Q8: Count Character Frequency
Example
function charFrequency(str) {
return str.split("").reduce((acc, char) => {
acc[char] = (acc[char] || 0) + 1;
return acc;
}, {});
}
console.log(charFrequency("javascript"));
Output
{ j: 1, a: 2, v: 1, s: 1, c: 1, r: 1, i: 1, p: 1, t: 1 }Q9: Capitalize Words
Example
function titleCase(str) {
return str
.split(" ")
.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join(" ");
}
console.log(titleCase("hello world from javascript"));
Output
Hello World From Javascript
Q10: Find Longest Word
Example
function longestWord(sentence) {
return sentence
.split(" ")
.reduce((longest, word) =>
word.length > longest.length ? word : longest, "");
}
console.log(longestWord("The quick brown fox jumped"));
Output
jumped
Section 3: Object Problems
Q11: Deep Clone an Object
Example
function deepClone(obj) {
if (obj === null || typeof obj !== "object") return obj;
if (obj instanceof Date) return new Date(obj.getTime());
if (Array.isArray(obj)) return obj.map(item => deepClone(item));
const clone = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
clone[key] = deepClone(obj[key]);
}
}
return clone;
}
const original = { a: 1, b: { c: 2, d: [3, 4] } };
const cloned = deepClone(original);
cloned.b.c = 99;
console.log(original.b.c); // 2 (untouched)
console.log(cloned.b.c); // 99
Output
2 99
Q12: Flatten a Nested Object
Example
function flattenObject(obj, prefix = "") {
return Object.keys(obj).reduce((acc, key) => {
const fullKey = prefix ? `${prefix}.${key}` : key;
if (typeof obj[key] === "object" && obj[key] !== null && !Array.isArray(obj[key])) {
Object.assign(acc, flattenObject(obj[key], fullKey));
} else {
acc[fullKey] = obj[key];
}
return acc;
}, {});
}
const nested = { a: { b: { c: 1 }, d: 2 }, e: 3 };
console.log(flattenObject(nested));
Output
{ "a.b.c": 1, "a.d": 2, e: 3 }Q13: Object to Query String
Example
function toQueryString(params) {
return Object.entries(params)
.map(([key, val]) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`)
.join("&");
}
console.log(toQueryString({ name: "Alice", age: 25, city: "New Delhi" }));
Output
name=Alice&age=25&city=New%20Delhi
Section 4: Function Problems
Q14: Custom map()
Example
Array.prototype.myMap = function (callback) {
const result = [];
for (let i = 0; i < this.length; i++) {
result.push(callback(this[i], i, this));
}
return result;
};
console.log([1, 2, 3].myMap(x => x * 2));
console.log([1, 2, 3].myMap((x, i) => `${i}:${x}`));
Output
[2, 4, 6] ["0:1", "1:2", "2:3"]
Q15: Custom filter()
Example
Array.prototype.myFilter = function (callback) {
const result = [];
for (let i = 0; i < this.length; i++) {
if (callback(this[i], i, this)) {
result.push(this[i]);
}
}
return result;
};
console.log([1, 2, 3, 4, 5].myFilter(x => x % 2 === 0));
Output
[2, 4]
Q16: Custom reduce()
Example
Array.prototype.myReduce = function (callback, initialValue) {
let acc = initialValue !== undefined ? initialValue : this[0];
const start = initialValue !== undefined ? 0 : 1;
for (let i = start; i < this.length; i++) {
acc = callback(acc, this[i], i, this);
}
return acc;
};
console.log([1, 2, 3, 4].myReduce((acc, val) => acc + val, 0));
console.log([1, 2, 3, 4].myReduce((acc, val) => acc * val));
Output
10 24
Q17: Debounce Function
Example
function debounce(fn, delay) {
let timer = null;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
timer = null;
}, delay);
};
}
const handleInput = debounce((val) => console.log("Search:", val), 300);
// Only calls search after 300ms of inactivity
Q18: Throttle Function
Example
function throttle(fn, limit) {
let lastRun = 0;
return function (...args) {
const now = Date.now();
if (now - lastRun >= limit) {
lastRun = now;
return fn.apply(this, args);
}
};
}
const handleScroll = throttle(() => console.log("Scrolled!"), 100);
// At most once per 100ms
Q19: Function Composition
Example
const compose = (...fns) => (x) => fns.reduceRight((acc, fn) => fn(acc), x);
const pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x);
const double = x => x * 2;
const addOne = x => x + 1;
const square = x => x * x;
const transform = compose(square, addOne, double);
console.log(transform(3)); // square(addOne(double(3))) = square(7) = 49
const pipeline = pipe(double, addOne, square);
console.log(pipeline(3)); // square(addOne(double(3))) = same
Output
49 49
Q20: Curry Function
Example
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
}
return function (...more) {
return curried.apply(this, args.concat(more));
};
};
}
const add = (a, b, c) => a + b + c;
const curriedAdd = curry(add);
console.log(curriedAdd(1)(2)(3));
console.log(curriedAdd(1, 2)(3));
console.log(curriedAdd(1)(2, 3));
Output
6 6 6
Section 5: Recursion Problems
Q21: Fibonacci (Recursive + Memoized)
Example
// Recursive (exponential)
function fib(n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
// Memoized (O(n))
function fibMemo(n, memo = {}) {
if (n in memo) return memo[n];
if (n <= 1) return n;
memo[n] = fibMemo(n - 1, memo) + fibMemo(n - 2, memo);
return memo[n];
}
console.log(fib(10));
console.log(fibMemo(50));
Output
55 12586269025
Q22: Deep Equal
Example
function deepEqual(a, b) {
if (a === b) return true;
if (typeof a !== "object" || typeof b !== "object") return false;
if (a === null || b === null) return false;
const keysA = Object.keys(a);
const keysB = Object.keys(b);
if (keysA.length !== keysB.length) return false;
return keysA.every(key => deepEqual(a[key], b[key]));
}
console.log(deepEqual({ a: 1, b: { c: 2 } }, { a: 1, b: { c: 2 } }));
console.log(deepEqual({ a: 1 }, { a: 2 }));
Output
true false
Q23: Power Function
js example
function power(base, exp) {
if (exp === 0) return 1;
if (exp % 2 === 0) {
const half = power(base, exp / 2);
return half * half;
}
return base * power(base, exp - 1);
}
console.log(power(2, 10)); // 1024
console.log(power(3, 4)); // 81Output
1024 81
Section 6: Design Pattern Problems
Q24: Implement EventEmitter
Example
class EventEmitter {
constructor() {
this.events = {};
}
on(event, listener) {
this.events[event] = this.events[event] || [];
this.events[event].push(listener);
return this;
}
emit(event, ...args) {
(this.events[event] || []).forEach(fn => fn(...args));
return this;
}
off(event, listener) {
this.events[event] = (this.events[event] || []).filter(fn => fn !== listener);
return this;
}
once(event, listener) {
const wrapper = (...args) => {
listener(...args);
this.off(event, wrapper);
};
return this.on(event, wrapper);
}
}
const emitter = new EventEmitter();
emitter.on("data", d => console.log("Received:", d));
emitter.emit("data", "Hello!");
emitter.emit("data", "World!");
Output
Received: Hello! Received: World!
Q25: LRU Cache
js example
class LRUCache {
constructor(capacity) {
this.capacity = capacity;
this.cache = new Map();
}
get(key) {
if (!this.cache.has(key)) return -1;
const val = this.cache.get(key);
this.cache.delete(key);
this.cache.set(key, val); // Move to end (most recent)
return val;
}
put(key, val) {
if (this.cache.has(key)) this.cache.delete(key);
this.cache.set(key, val);
if (this.cache.size > this.capacity) {
this.cache.delete(this.cache.keys().next().value); // Remove oldest
}
}
}
const cache = new LRUCache(3);
cache.put(1, "A");
cache.put(2, "B");
cache.put(3, "C");
console.log(cache.get(1)); // A (1 is now most recent)
cache.put(4, "D"); // evicts 2 (least recently used)
console.log(cache.get(2)); // -1 (evicted)
console.log(cache.get(3)); // COutput
A -1 C
Common Traps 🪤
| Mistake | Fix | ||
|---|---|---|---|
Using == instead of === | Always use strict equality | ||
| Mutating input array | Use [...arr] or arr.slice() to copy | ||
| Off-by-one in loops | Test with small arrays manually | ||
| Not handling empty input | Add guard `if (!arr | !arr.length) return` | |
| Forgetting to return in reduce | Always verify your accumulator logic |
Time Complexity Quick Reference
| Solution | Time | Space |
|---|---|---|
| Two Sum (hash map) | O(n) | O(n) |
| Flatten (recursive) | O(n) | O(d) — d=depth |
| Deep Clone | O(n) | O(n) |
| Debounce/Throttle | O(1) | O(1) |
| Fibonacci (memo) | O(n) | O(n) |
| LRU Cache get/put | O(1) | O(n) |
Continue the lesson path
Study next in this module
01InterviewTop 30 JavaScript Closure Interview Questions & Answers 2026Master closure interview questions with detailed answers, code examples, outputs, common traps, and tips. Covers IIFE, loop problem, data privacy, currying, memoization.02InterviewTop 25 JavaScript Event Loop Interview Questions & Answers 2026Master JavaScript event loop interview questions with call stack, microtasks, macrotasks, Promise order, async/await execution, and real output prediction examples.03InterviewTop 50 JavaScript Interview Questions & Answers 2026Complete JavaScript interview guide 2026. Covers 50 most asked questions on closures, hoisting, promises, prototypes, async/await, event loop, DOM, and ES6+ features.04InterviewTop 30 JavaScript Promise Interview Questions & Answers 2026Master JavaScript Promise interview questions with detailed answers. Covers Promise states, chaining, Promise.all/race/allSettled/any, async/await, error handling, and output questions.