{"id":39702770,"url":"https://github.com/codewithdhruba01/javascript-interview-questions","last_synced_at":"2026-01-18T10:29:05.396Z","repository":{"id":322047558,"uuid":"1088001932","full_name":"codewithdhruba01/javascript-interview-questions","owner":"codewithdhruba01","description":"A complete collection of JavaScript interview questions and answers,","archived":false,"fork":false,"pushed_at":"2025-12-13T10:22:29.000Z","size":130,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-12-15T00:50:11.581Z","etag":null,"topics":["interview-preparation","javascript"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/codewithdhruba01.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-11-02T04:55:47.000Z","updated_at":"2025-12-13T10:22:28.000Z","dependencies_parsed_at":null,"dependency_job_id":"730a05b5-908f-47ce-be52-c07b7b5499b3","html_url":"https://github.com/codewithdhruba01/javascript-interview-questions","commit_stats":null,"previous_names":["codewithdhruba01/javascript-interview-questions"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/codewithdhruba01/javascript-interview-questions","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codewithdhruba01%2Fjavascript-interview-questions","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codewithdhruba01%2Fjavascript-interview-questions/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codewithdhruba01%2Fjavascript-interview-questions/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codewithdhruba01%2Fjavascript-interview-questions/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/codewithdhruba01","download_url":"https://codeload.github.com/codewithdhruba01/javascript-interview-questions/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codewithdhruba01%2Fjavascript-interview-questions/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28534411,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-18T10:13:46.436Z","status":"ssl_error","status_checked_at":"2026-01-18T10:13:11.045Z","response_time":98,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["interview-preparation","javascript"],"created_at":"2026-01-18T10:29:05.304Z","updated_at":"2026-01-18T10:29:05.368Z","avatar_url":"https://github.com/codewithdhruba01.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# JavaScript Interview Questions\nA complete collection of **JavaScript interview questions and answers**, explained with code examples and easy-to-understand concepts.  \nPerfect for developers preparing for interviews or revising JavaScript fundamentals.\n\n---\n\n\u003e Prepare for real interviews with 100+ curated JavaScript problems, runnable in your browser. Every question is selected and reviewed by experienced ex-FAANG interviewers so you practise what actually shows up in interviews — not filler content. We promise: no AI-generated fluff and no fake reviews — just high-quality problems, thoughtful explanations, and honest feedback to level up your interview game.\n\n## 📋 Table of Contents\n\n| No. | Questions |\n|-----|------------|\n| 1 | [What is JavaScript?](#1-what-is-javascript) |\n| 2 | [What are the different data types in JavaScript?](#2-what-are-the-different-data-types-in-javascript) |\n| 3 | [How do you declare variables in JavaScript?](#3-how-do-you-declare-variables-in-javascript) |\n| 4 | [What is the difference between `let`, `const`, and `var`?](#4-what-is-the-difference-between-let-const-and-var) |\n| 5 | [What is the `typeof` operator used for?](#5-what-is-the-typeof-operator-used-for) |\n| 6 | [What is NaN in JavaScript?](#6-what-is-nan-in-javascript) |\n| 7 | [What is a callback function?](#7-what-is-a-callback-function) |\n| 8 | [What is event delegation in JavaScript?](#8-what-is-event-delegation-in-javascript) |\n| 9 | [Explain the concept of prototypal inheritance in JavaScript.](#9-explain-the-concept-of-prototypal-inheritance-in-javascript) |\n| 10 | [What is the `this` keyword in JavaScript?](#10-what-is-the-this-keyword-in-javascript) |\n| 11 | [What are JavaScript promises?](#11-what-are-javascript-promises) |\n| 12 | [Explain the difference between `null` and `undefined` in JavaScript.](#12-explain-the-difference-between-null-and-undefined-in-javascript) |\n| 13 | [What is the event loop in JavaScript?](#13-what-is-the-event-loop-in-javascript) |\n| 14 | [Explain the concept of event-driven programming in JavaScript.](#14-explain-the-concept-of-event-driven-programming-in-javascript) |\n| 15 | [What is the difference between synchronous and asynchronous JavaScript?](#15-what-is-the-difference-between-synchronous-and-asynchronous-javascript) |\n| 16 | [How do you handle errors in JavaScript?](#16-how-do-you-handle-errors-in-javascript) |\n| 17 | [What are JavaScript modules and how do they improve code organization?](#17-what-are-javascript-modules-and-how-do-they-improve-code-organization) |\n| 18 | [What are generators in JavaScript?](#18-what-are-generators-in-javascript) |\n| 19 | [What are arrow functions in JavaScript?](#19-what-are-arrow-functions-in-javascript) |\n| 20 | [Explain the concept of currying in JavaScript.](#20-explain-the-concept-of-currying-in-javascript) |\n| 21 | [What is memoization and how is it useful in JavaScript?](#21-what-is-memoization-and-how-is-it-useful-in-javascript) |\n| 22 | [What is a prototype chain?](#22-what-is-a-prototype-chain) |\n| 23 | [What is a first-class function?](#23-what-is-a-first-class-function) |\n| 24 | [What is a higher-order function?](#24-what-is-a-higher-order-function) |\n| 25 | [What are lambda expressions or arrow functions?](#25-what-are-lambda-expressions-or-arrow-functions) |\n| 26 | [What is the difference between let and var?](#26-what-is-the-difference-between-let-and-var) |\n| 27 | [How do you decode or encode a URL in JavaScript?](#27-how-do-you-decode-or-encode-a-url-in-javascript) |\n| 28 | [What is memoization](#28-what-is-memoization) |\n| 29 | [What is Hoisting](#29-what-is-hoisting) |\n| 30 | [Explain the JavaScript event loop and how microtasks differ from macrotasks.](#30-what-is-the-javascript-event-loop) |\n| 31 | [What is the DOM in JavaScript? ](#31-what-is-the-dom-in-javascript) |\n| 32 | [How do you select an element by its ID in JavaScript?](#32-how-do-you-select-an-element-by-its-id-in-javascript) |\n| 33 | [What are arrow functions in JavaScript?](#33-what-are-arrow-functions-in-javascript) |\n| 34 | [What is a pure function ?](#34-what-is-a-pure-function-in-javascript) |\n| 35 | [What are classes in ES6](#35-what-are-classes-in-es6) |\n| 36 | [What are modules?](#36-what-are-modules) |\n| 37 | [What is scope in javascript?](#37-what-is-scope-in-javascript) |\n| 38 | [Why do you need modules?](#38-why-do-you-need-modules) |\n| 39 | [How do you manipulate DOM using a service worker](#39-how-do-you-manipulate-dom-using-a-service-worker)\n| 40 | [What is a post message?](#40-what-is-a-post-message)\n| 41 | [What is a Cookie?](#41-what-is-a-cookie)\n| 42 | [What is a promise?](#42-what-is-a-promise)\n| 43 | [Why do we need a Promise in JavaScript](#43-why-do-we-need-a-promise-in-javascript)\n| 44 | [What are Closures](#44-what-are-closures)\n| 45 | [What is IndexedDB](#45-what-is-indexedDB)\n| 46 | [What is Collation?](#46-what-is-collation)\n| 47 | [Why do you need web storage](#47-why-do-you-need-web-storage)\n| 48 | [How do you delete a cookie](#48-how-do-you-delete-a-cookie)\n| 49 | [What is promise.all](#49-what-is-promise.all)\n| 50 | [What is undefined property](#50-what-is-undefined-property)\n\n---\n\n## 📋 Repository Structure\n\nThis repository is organized into comprehensive topic-based folders. Each folder contains detailed interview questions with code examples and explanations.\n\n### 📁 [Core JavaScript](./core-javascript/) - Fundamental JavaScript concepts\n- Data types, variables, operators\n- Functions, scope, closures\n- Objects, arrays, prototypes\n- Error handling, modules\n\n### 📁 [ES6+ Features](./es6-plus/) - Modern JavaScript (ES6 and beyond)\n- Arrow functions, template literals, destructuring\n- Classes, modules, promises\n- Async/await, generators, proxies\n- Maps, sets, symbols, iterators\n\n### 📁 [Arrays \u0026 Objects](./arrays-objects/) - Array and object manipulation\n- Array methods (map, filter, reduce, etc.)\n- Object methods and manipulation\n- Advanced patterns and techniques\n- Performance considerations\n\n### 📁 [DOM \u0026 Browser APIs](./dom-browser-apis/) - Browser interaction\n- DOM manipulation and traversal\n- Event handling and delegation\n- Browser APIs (localStorage, geolocation, etc.)\n- Web APIs (Fetch, WebSockets, Service Workers)\n\n### 📁 [Asynchronous Programming](./async-programming/) - Async patterns\n- Callbacks, promises, async/await\n- Event loop, microtasks/macrotasks\n- Generators, async iterators\n- Error handling in async code\n\n### 📁 [Node.js](./node-js/) - Server-side JavaScript\n- Node.js fundamentals and architecture\n- File system operations, streams\n- HTTP servers, Express.js, middleware\n- Database integration, authentication, security\n\n### 📁 [Build Tools \u0026 Development](./build-tools/) - Development workflow\n- Package managers (npm, yarn, pnpm)\n- Bundlers (Webpack, Rollup, Vite)\n- Task runners (Gulp, Grunt)\n- Development tools (ESLint, Prettier, Husky)\n\n### 📁 [Testing](./testing/) - Testing methodologies\n- Jest testing framework\n- React Testing Library\n- Unit, integration, and E2E testing\n- Test coverage and best practices\n\n### 📁 [Frameworks](./frameworks/) - Popular JavaScript frameworks\n- **React**: Components, hooks, state management, performance\n- **Vue.js**: Vue instance, templates, Vuex, Composition API\n- **Angular**: Components, services, dependency injection, CLI\n\n### 📁 [Performance](./performance/) - Optimization techniques\n- Performance metrics and monitoring\n- JavaScript optimization\n- DOM and rendering performance\n- Network optimization\n\n### 📁 [Design Patterns](./design-patterns/) - Software design patterns\n- Creational patterns (Singleton, Factory, Prototype)\n- Structural patterns (Adapter, Decorator, Proxy)\n- Behavioral patterns (Observer, Strategy, Command)\n- Modern JavaScript patterns\n\n## 🚀 Quick Start\n\n1. **Clone the repository**\n   ```bash\n   git clone https://github.com/codewithdhruba01/javascript-interview-questions.git\n   cd javascript-interview-questions\n   ```\n\n2. **Install dependencies**\n   ```bash\n   npm install\n   ```\n\n3. **Start development server**\n   ```bash\n   npm run serve\n   ```\n\n4. **Run tests**\n   ```bash\n   npm test\n   ```\n\n## 📖 How to Use\n\n- **Browse by Topic**: Choose a folder based on your area of interest\n- **Practice Questions**: Each topic contains 15-30+ interview questions\n- **Code Examples**: All questions include runnable code examples\n- **Progressive Learning**: Start with fundamentals, then advance to complex topics\n\n## 🎯 Interview Preparation Tips\n\n1. **Focus on Fundamentals**: Master core JavaScript before frameworks\n2. **Practice Coding**: Implement concepts, don't just read\n3. **Understand Trade-offs**: Know when to use different approaches\n4. **Stay Updated**: Keep learning new JavaScript features\n5. **System Design**: Practice architectural questions\n\n## 🤝 Contributing\n\nContributions are welcome! Please read our contributing guidelines and submit pull requests for:\n- New interview questions\n- Code examples improvements\n- Topic expansions\n- Bug fixes\n\n## 📄 Legacy Questions (Original 50 Questions)\n\nFor backward compatibility, the original 50 questions are still available below:\n\n---\n\n### 1. What is JavaScript?\n\nJavaScript is a high-level, interpreted programming language used to make web pages dynamic and interactive.  \nIt runs in browsers and on servers (with Node.js).\n\n**Features:**\n- Dynamic typing  \n- Prototype-based object orientation  \n- Event-driven and asynchronous  \n- Lightweight and flexible  \n\n**Example:**\n```javascript\nconsole.log(\"Hello, JavaScript!\");\n````\n\n[🔝 Back to Top](#-table-of-contents)\n\n---\n\n### 2. What are the different data types in JavaScript?\n\nJavaScript supports **primitive** and **non-primitive** data types.\n\n| Type      | Example                 |\n| --------- | ----------------------- |\n| String    | `\"Hello\"`               |\n| Number    | `42`                    |\n| Boolean   | `true`                  |\n| Undefined | `let a;`                |\n| Null      | `let b = null;`         |\n| Symbol    | `Symbol(\"id\")`          |\n| BigInt    | `12345678901234567890n` |\n| Object    | `{ name: \"John\" }`      |\n\n**Example:**\n\n```javascript\nlet name = \"John\";\nlet age = 30;\nlet isLogged = true;\nlet user = { name, age };\nconsole.log(typeof user); // \"object\"\n```\n\n[🔝 Back to Top](#-table-of-contents)\n\n---\n\n### 3. How do you declare variables in JavaScript?\n\nYou can declare variables using `var`, `let`, or `const`.\n\n```javascript\nvar city = \"Delhi\";   // function scoped\nlet age = 25;         // block scoped\nconst country = \"India\"; // constant, cannot be reassigned\n```\n\n[🔝 Back to Top](#-table-of-contents)\n\n---\n\n### 4. What is the difference between `let`, `const`, and `var`?\n\n| Feature    | var       | let                    | const                  |\n| ---------- | --------- | ---------------------- | ---------------------- |\n| Scope      | Function  | Block                  | Block                  |\n| Re-declare | Allowed |  Not allowed          |  Not allowed          |\n| Re-assign  | Allowed |  Allowed              |  Not allowed          |\n| Hoisting   | Yes     |  Yes (uninitialized) |  Yes (uninitialized) |\n\n**Example:**\n\n```javascript\nfunction example() {\n  console.log(a); // undefined\n  var a = 10;\n  let b = 20;\n  const c = 30;\n  console.log(a, b, c);\n}\nexample();\n```\n\n[🔝 Back to Top](#-table-of-contents)\n\n---\n\n### 5. What is the `typeof` operator used for?\n\nIt returns the **data type** of a variable.\n\n```javascript\ntypeof 123;         // \"number\"\ntypeof \"Hello\";     // \"string\"\ntypeof true;        // \"boolean\"\ntypeof undefined;   // \"undefined\"\ntypeof null;        // \"object\"\ntypeof {};          // \"object\"\ntypeof Symbol();    // \"symbol\"\n```\n\n[🔝 Back to Top](#-table-of-contents)\n\n---\n\n### 6. What is NaN in JavaScript?\n\n`NaN` stands for **Not-a-Number** and indicates invalid number results.\n\n```javascript\nconsole.log(0 / 0);        // NaN\nconsole.log(parseInt(\"A\")); // NaN\nconsole.log(typeof NaN);   // \"number\"\n```\n\n[🔝 Back to Top](#-table-of-contents)\n\n---\n\n### 7. What is a callback function?\n\nA **callback function** is a function passed as an argument to another function, to be executed later.\n\n**Example:**\n\n```javascript\nfunction greet(name, callback) {\n  console.log(\"Hi \" + name);\n  callback();\n}\n\nfunction bye() {\n  console.log(\"Goodbye!\");\n}\n\ngreet(\"John\", bye);\n```\n\n[🔝 Back to Top](#-table-of-contents)\n\n---\n\n### 8. What is event delegation in JavaScript?\n\nEvent delegation allows you to handle events at a **parent level** instead of adding listeners to individual child elements.\n\n**Example:**\n\n```javascript\ndocument.getElementById(\"list\").addEventListener(\"click\", function(e) {\n  if (e.target.tagName === \"LI\") {\n    console.log(\"You clicked on:\", e.target.textContent);\n  }\n});\n```\n\nThis approach improves **performance** and **maintainability**.\n\n[🔝 Back to Top](#-table-of-contents)\n\n---\n\n### 9. Explain the concept of prototypal inheritance in JavaScript.\n\nJavaScript objects can inherit properties and methods from other objects using the **prototype chain**.\n\n**Example:**\n\n```javascript\nfunction Person(name) {\n  this.name = name;\n}\nPerson.prototype.greet = function() {\n  console.log(\"Hello, I'm \" + this.name);\n};\nconst user = new Person(\"Alice\");\nuser.greet(); // Hello, I'm Alice\n```\n\n[🔝 Back to Top](#-table-of-contents)\n\n---\n\n### 10. What is the `this` keyword in JavaScript?\n\n`this` refers to the **object that owns the current execution context**.\n\n| Context               | Value of `this`                       |\n| --------------------- | ------------------------------------- |\n| Global                | `window` (browser)                    |\n| Inside a function     | `undefined` (in strict mode)          |\n| Inside object method  | That object                           |\n| Inside arrow function | Lexical `this` (inherits from parent) |\n\n**Example:**\n\n```javascript\nconst user = {\n  name: \"John\",\n  show() {\n    console.log(this.name);\n  },\n};\nuser.show(); // John\n```\n\n[🔝 Back to Top](#-table-of-contents)\n\n---\n\n### 11. What are JavaScript promises?\n\nA **Promise** represents a value that may be available now, later, or never.\nIt helps handle **asynchronous operations**.\n\n**States:**\n\n* Pending\n* Fulfilled\n* Rejected\n\n**Example:**\n\n```javascript\nconst promise = new Promise((resolve, reject) =\u003e {\n  setTimeout(() =\u003e resolve(\"Done!\"), 1000);\n});\n\npromise.then(result =\u003e console.log(result)); // Done!\n```\n\n[🔝 Back to Top](#-table-of-contents)\n\n---\n\n### 12. Explain the difference between `null` and `undefined` in JavaScript.\n\n| Feature | `null`                       | `undefined`                        |\n| ------- | ---------------------------- | ---------------------------------- |\n| Meaning | Intentional absence of value | Variable declared but not assigned |\n| Type    | Object                       | Undefined                          |\n| Example | `let a = null;`              | `let b;`                           |\n\n**Example:**\n\n```javascript\nlet a = null;\nlet b;\nconsole.log(a, typeof a); // null \"object\"\nconsole.log(b, typeof b); // undefined \"undefined\"\n```\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 13. What is the event loop in JavaScript?\n\nThe **event loop** handles asynchronous code execution by monitoring the **call stack** and **callback queue**.\n\n**Flow:**\n\n1. JS executes synchronous code (call stack)\n2. Async callbacks go to task queue\n3. Event loop moves them to stack when free\n\n**Example:**\n\n```javascript\nconsole.log(\"Start\");\nsetTimeout(() =\u003e console.log(\"Async Task\"), 0);\nconsole.log(\"End\");\n// Output: Start → End → Async Task\n```\n\n[🔼 Back to Top](#-table-of-contents)\n\n\n### 14. Explain the concept of event-driven programming in JavaScript.\n\nEvent-driven programming is a paradigm where the flow of the program is determined by events — such as user actions (clicks, keypresses), messages from other programs, or sensor outputs.\n\n**Example:**\n\n```javascript\ndocument.getElementById(\"btn\").addEventListener(\"click\", () =\u003e {\n  console.log(\"Button was clicked!\");\n});\n```\n\nHere, the function only executes **when** the click event happens.\n\n**Key Points:**\n\n* JavaScript is event-driven.\n* It uses **event listeners** and **callbacks**.\n* Allows asynchronous, interactive behavior on webpages.\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 15. What is the difference between synchronous and asynchronous JavaScript?\n\n| Feature   | Synchronous              | Asynchronous                      |\n| --------- | ------------------------ | --------------------------------- |\n| Execution | Code runs line-by-line   | Code can skip ahead while waiting |\n| Blocking  | Blocks further execution | Non-blocking                      |\n| Example   | Loops, calculations      | API calls, file I/O               |\n\n**Example:**\n\n```javascript\nconsole.log(\"Start\");\n\nsetTimeout(() =\u003e console.log(\"Async Task\"), 2000);\n\nconsole.log(\"End\");\n```\n\n**Output:**\n\n```\nStart\nEnd\nAsync Task\n```\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 16. How do you handle errors in JavaScript?\n\nYou can use **try...catch...finally** blocks or **Promise `.catch()`** for async code.\n\n**Example:**\n\n```javascript\ntry {\n  let result = riskyOperation();\n} catch (error) {\n  console.error(\"Something went wrong:\", error);\n} finally {\n  console.log(\"Operation completed\");\n}\n```\n\n**Also:**\n\n```javascript\nfetch(\"https://api.example.com\")\n  .then(res =\u003e res.json())\n  .catch(err =\u003e console.error(\"Error fetching:\", err));\n```\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 17. What are JavaScript modules and how do they improve code organization?\n\nModules allow splitting JavaScript code into separate files to improve maintainability.\n\n**Example:**\n\n```javascript\n// math.js\nexport function add(a, b) {\n  return a + b;\n}\n\n// main.js\nimport { add } from './math.js';\nconsole.log(add(2, 3)); // 5\n```\n\n **Benefits:**\n\n* Code reusability\n* Clear organization\n* Avoids global scope pollution\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 18. What are generators in JavaScript?\n\nGenerators are special functions that can pause and resume their execution using the `yield` keyword.\n\n**Example:**\n\n```javascript\nfunction* count() {\n  yield 1;\n  yield 2;\n  yield 3;\n}\n\nconst counter = count();\nconsole.log(counter.next().value); // 1\n```\n\n\u003e **Use Case:** Useful for lazy evaluation and asynchronous iteration.\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 19. What are arrow functions in JavaScript?\n\nArrow functions are a shorter syntax for writing functions introduced in ES6.\n\n**Example:**\n\n```javascript\nconst add = (a, b) =\u003e a + b;\nconsole.log(add(5, 10)); // 15\n```\n\n **Advantages:**\n\n* Concise syntax\n* Lexically binds `this`\n* Great for callbacks and inline functions\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 20. Explain the concept of currying in JavaScript.\n\nCurrying transforms a function with multiple arguments into a sequence of functions that take one argument each.\n\n**Example:**\n\n```javascript\nfunction curry(a) {\n  return function(b) {\n    return function(c) {\n      return a + b + c;\n    };\n  };\n}\nconsole.log(curry(2)(3)(4)); // 9\n```\n\n **Benefits:**\n\n* Reusability\n* Function composition\n* Delayed execution\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 21. What is memoization and how is it useful in JavaScript?\n\nMemoization is an optimization technique to cache results of expensive function calls.\n\n**Example:**\n\n```javascript\nfunction memoize(fn) {\n  const cache = {};\n  return function(x) {\n    if (x in cache) return cache[x];\n    return (cache[x] = fn(x));\n  };\n}\n\nconst square = memoize(x =\u003e x * x);\nconsole.log(square(4)); // Computed\nconsole.log(square(4)); // Cached\n```\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 22. What is a prototype chain?\n\nThe prototype chain is the mechanism through which objects inherit properties and methods from other objects.\n\n**Example:**\n\n```javascript\nfunction Person(name) {\n  this.name = name;\n}\nPerson.prototype.greet = function() {\n  return `Hello ${this.name}`;\n};\n\nconst user = new Person(\"John\");\nconsole.log(user.greet()); // Hello John\n```\n\n **Inheritance works via** `__proto__` links between objects.\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 23. What is a first-class function?\n\nFunctions in JavaScript are treated like variables — they can be passed as arguments, returned, and assigned.\n\n**Example:**\n\n```javascript\nfunction greet(name) {\n  return `Hello ${name}`;\n}\n\nfunction logGreeting(fn) {\n  console.log(fn(\"Alice\"));\n}\n\nlogGreeting(greet);\n```\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 24. What is a higher-order function?\n\nA higher-order function takes one or more functions as arguments or returns a function.\n\n**Example:**\n\n```javascript\nfunction multiplier(factor) {\n  return function(num) {\n    return num * factor;\n  };\n}\n\nconst double = multiplier(2);\nconsole.log(double(5)); // 10\n```\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 25. What are lambda expressions or arrow functions?\n\nArrow functions (`=\u003e`) are a type of lambda expression — a compact way to define anonymous functions.\n\n**Example:**\n\n```javascript\nconst greet = name =\u003e `Hello, ${name}!`;\nconsole.log(greet(\"John\"));\n```\n\n**Difference:** Arrow functions do not have their own `this` or `arguments` binding.\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 26. What is the difference between `let` and `var`?\n\nYou can list out the differences in a **tabular format**.\n\n| var                                         | let                         |\n| ------------------------------------------- | --------------------------- |\n| Available since the beginning of JavaScript | Introduced in ES6           |\n| Function scoped                             | Block scoped                |\n| Hoisted and initialized as undefined        | Hoisted but not initialized |\n| Can be re-declared                          | Cannot be re-declared       |\n\n**Example:**\n\n```javascript\nfunction userDetails(username) {\n  if (username) {\n    console.log(salary); // undefined due to hoisting\n    // console.log(age); // ReferenceError: Cannot access 'age' before initialization\n    let age = 30;\n    var salary = 10000;\n  }\n  console.log(salary); // 10000 (function scope)\n  // console.log(age); // Error: age is not defined (block scope)\n}\nuserDetails(\"John\");\n```\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 27. How do you decode or encode a URL in JavaScript?\n\n`encodeURI()` function is used to encode a URL. This function requires a URL string as a parameter and returns that encoded string.\n`decodeURI()` function is used to decode a URL. This function requires an encoded URL string as a parameter and returns that decoded string.\n\n\u003e **Note:** If you want to encode characters such as `/ ? : @ \u0026 = + $ #`, then you need to use `encodeURIComponent()` instead of `encodeURI()`.\n\n```javascript\nlet uri = \"employeeDetails?name=john\u0026occupation=manager\";\nlet encoded_uri = encodeURI(uri);\nlet decoded_uri = decodeURI(encoded_uri);\n\nconsole.log(\"Encoded URI:\", encoded_uri);\nconsole.log(\"Decoded URI:\", decoded_uri);\n```\n\n[🔼 Back to Top](#-table-of-contents)\n\n\n---\n\n### 28. What is memoization\n\nMemoization is a functional programming technique that attempts to increase a function’s performance by caching its previously computed results.\nEach time a memoized function is called, its parameters are used to index the cache.\nIf the data is already present, it returns the cached result without executing the entire function again.\nOtherwise, the function is executed and the new result is added to the cache.\n\nLet’s take an example of an adding function with memoization:\n\n```javascript\nconst memoizeAddition = () =\u003e {\n  let cache = {};\n  return (value) =\u003e {\n    if (value in cache) {\n      console.log(\"Fetching from cache\");\n      return cache[value]; // Here, cache.value cannot be used as property name starts with a number\n    } else {\n      console.log(\"Calculating result\");\n      let result = value + 20;\n      cache[value] = result;\n      return result;\n    }\n  };\n};\n\n// returned function from memoizeAddition\nconst addition = memoizeAddition();\nconsole.log(addition(20)); // output: 40 calculated\nconsole.log(addition(20)); // output: 40 cached\n```\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 29. What is Hoisting\n\nHoisting is a JavaScript mechanism where variables, function declarations, and classes are moved to the top of their scope before code execution.\nRemember that JavaScript only hoists **declarations**, not **initializations**.\n\nLet’s take a simple example of variable hoisting:\n\n```javascript\nconsole.log(message); // output: undefined\nvar message = \"The variable has been hoisted\";\n```\n\nThe above code looks like this to the interpreter:\n\n```javascript\nvar message;\nconsole.log(message);\nmessage = \"The variable has been hoisted\";\n```\n\nIn the same fashion, function declarations are hoisted too:\n\n```javascript\nmessage(\"Good morning\"); // Good morning\n\nfunction message(name) {\n  console.log(name);\n}\n```\n\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 30. What is the JavaScript Event Loop\n\nJavaScript is **single-threaded**, meaning it executes one piece of code at a time on a single main thread.\nTo handle asynchronous operations (like `setTimeout`, `fetch`, or `Promises`), JavaScript uses the **event loop**.\n\nThe **event loop** continuously checks:\n\n1. If the **call stack** (where JS executes functions) is empty.\n2. If the **task queues** have any pending callbacks to run.\n3. It then **takes the next task** from the queue and pushes it onto the call stack.\n\n### The Two Types of Task Queues\n\nThere are **two major queues** where async callbacks are placed:\n\n#### 1. **Macrotasks (a.k.a. Tasks)**\n\nThese are large, independent units of work.\nExamples:\n\n* `setTimeout()`\n* `setInterval()`\n* `setImmediate()` (Node.js)\n* `I/O events`\n* `requestAnimationFrame()`\n\n\u003eAfter each macrotask, the event loop checks for microtasks before moving to the next one.\n\n#### 2. **Microtasks**\n\nMicrotasks are smaller, higher-priority tasks meant to run **immediately after the current execution context**, before any new macrotask starts.\n\nExamples:\n\n* `Promise.then()`, `Promise.catch()`, `Promise.finally()`\n* `queueMicrotask()`\n* `MutationObserver`\n\n\u003eAll queued microtasks run **right after the current script or macrotask finishes**, and before the next macrotask starts.\n\n### Example\n\n```javascript\nconsole.log(\"Start\");\n\nsetTimeout(() =\u003e {\n  console.log(\"Macrotask\");\n}, 0);\n\nPromise.resolve().then(() =\u003e {\n  console.log(\"Microtask\");\n});\n\nconsole.log(\"End\");\n```\n\n**Output:**\n\n```\nStart\nEnd\nMicrotask\nMacrotask\n```\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 31. What is the DOM in JavaScript\nThe DOM (Document Object Model) is a representation of the HTML structure as \nobjects, allowing JavaScript to interact with and manipulate the content and layout.\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 32. How do you select an element by its ID in JavaScript\nUse `document.getElementById('id')` to select an element by its ID. \n\n* **How do you add a class to an HTML element using JavaScript?** \u003c/br\u003e\n-\u003e Use `element.classList.add('class-name')` to add a class to an element.\n  \n* **How do you remove an element from the DOM in JavaScript?** \u003c/br\u003e\n-\u003e Use `element.remove()` to remove an element from the DOM.\n\n* **How do you change the text content of an element in JavaScript?** \u003c/br\u003e\n-\u003e Use `element.textContent = 'New text'` to change the text of an element.\n  \n* **What is a for loop in JavaScript?** \u003c/br\u003e\n-\u003e A for loop is used to execute a block of code a certain number of times. Example: for \n`(let i = 0; i \u003c 5; i++)`  `{ console.log(i); }`.\n\n* **What is an if-else statement in JavaScript?** \u003c/br\u003e\n-\u003e An `if-else` statement executes a block of code if a condition is true, otherwise it runs \nthe code in the `else` block.\n\n* **What is the purpose of the switch statement in JavaScript?** \u003c/br\u003e\n-\u003e A `switch` statement allows you to execute different blocks of code based on the value \nof a variable.\n\n* **What is a while loop in JavaScript?** \u003c/br\u003e\n-\u003e A `while` loop repeatedly executes a block of code as long as a specified condition is \ntrue.\n\n* **How do you exit a loop in JavaScript?** \u003c/br\u003e\n-\u003e Use the `break` statement to exit a loop prematurely.\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 33. What are arrow functions in JavaScript\nArrow functions are a shorthand syntax for writing functions in JavaScript. Example: \n``const add = (a, b) =\u003e a + b;``.\n\n* **What is destructuring in JavaScript?** \u003c/br\u003e\n-\u003e Destructuring allows you to extract values from arrays or objects into variables. \nExample: `const [a, b] = [1, 2];`.\n\n* **What is template literals in JavaScript?** \u003c/br\u003e\n-\u003e Template literals are string literals that allow embedded expressions, using backticks (``) \nand ${} for placeholders.\n\n* **What are default parameters in JavaScript?** \u003c/br\u003e\n-\u003e Default parameters allow you to initialize function parameters with default values if no \nvalue is passed. \n\n* **What is the spread operator in JavaScript?** \u003c/br\u003e\n-\u003e The `spread` operator (...) allows an iterable to expand in places where multiple \narguments are expected.\n\n* **What is the rest parameter in JavaScript?** \u003c/br\u003e\n-\u003e The `rest` parameter (...args) allows you to pass an indefinite number of arguments \nto a function.\n\n* **What are promises in JavaScript?** \u003c/br\u003e\n-\u003e Promises represent asynchronous operations that either resolve or reject. Example: \n`new Promise((resolve, reject) =\u003e {})`.\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 34. What is a Pure Function in JavaScript\n\nA **pure function** is a function whose output depends *only* on its input arguments and produces **no side effects**.\nThis means:\n\n* Given the **same inputs**, it will always return the **same output**.\n* It does **not modify any external variables, objects, or state**.\n\nTo understand this better, let’s compare pure and impure functions.\n\n## **Example: Pure Function vs. Impure Function**\n\n### **Impure Function**\n\n```js\nlet numbers = [];\n\nconst impureAdd = (num) =\u003e {\n  return numbers.push(num);\n};\n```\n\n### **Pure Function**\n\n```js\nconst pureAdd = (num) =\u003e (arr) =\u003e {\n  return arr.concat([num]);\n};\n```\n\n### **Usage**\n\n```js\nconsole.log(impureAdd(5));  // Output: 1\nconsole.log(numbers);       // Output: [5]\n\nconsole.log(pureAdd(10)(numbers)); // Output: [5, 10]\nconsole.log(numbers);              // Still [5]\n```\n\n## **Explanation**\n\n### **Why impureAdd is impure?**\n\n* It modifies the **external array** `numbers`.\n* Each call changes the program's overall state.\n* The returned value depends on how many times the function was called earlier.\n\nBecause it alters something outside itself, it is **not a pure function**.\n\n### **Why pureAdd is pure?**\n\n* It never changes the original array.\n* Instead, it **creates and returns a new array** with the added value.\n* Same input → same output, with no side effects.\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 35. What are classes in ES6\n\nIn ES6, JavaScript classes are mainly **syntactic sugar** over JavaScript’s prototype-based inheritance. Before ES6, inheritance was done using function constructors and prototypes, like this:\n\n```js\nfunction Bike(model, color) {\n  this.model = model;\n  this.color = color;\n}\n\nBike.prototype.getDetails = function () {\n  return this.model + \" bike has \" + this.color + \" color\";\n};\n```\n\nWith ES6, the same structure can be written more cleanly using the `class` syntax:\n\n```js\nclass Bike {\n  constructor(model, color) {\n    this.model = model;\n    this.color = color;\n  }\n\n  getDetails() {\n    return this.model + \" bike has \" + this.color + \" color\";\n  }\n}\n```\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 36. What are modules\nModules refer to small units of independent, reusable code and also act as the foundation of many JavaScript design patterns. Most of the JavaScript modules export an object literal, a function, or a constructor\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 37. What is scope in javascript\nScope is the accessibility of variables, functions, and objects in some particular part of your code during runtime. In other words, scope determines the visibility of variables and other resources in areas of your code.\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 38. Why do you need modules\n\nWe need modules in JavaScript because they help:\n\n1. **Break code into smaller parts** (easy to manage).\n2. **Increase reusability** (use the same code multiple times).\n3. **Prevent global scope pollution** (avoid variable conflicts).\n4. **Make maintenance easier** (useful in large projects).\n5. **Keep code clean, organized, and secure.**\n\n**Conclusion:**\nModules make JavaScript code **organized, reusable, safe, and easier to maintain**.\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 39. How do you manipulate DOM using a service worker\nService worker can't access the DOM directly. But it can communicate with the pages it controls by responding to messages sent via the `postMessage` interface, and those pages can manipulate the DOM.\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 40. What is a post message\n**`postMessage` is a method that allows secure cross-origin communication between different Window objects — such as between a parent page and a popup it opened, or between a webpage and an embedded iframe. Normally, scripts running on different pages cannot access each other unless they follow the same-origin policy, which requires the pages to share the same protocol, host, and port. The `postMessage` API provides a safe way to bypass this restriction and exchange data across different origins.**\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 41. **What is a Cookie**\n\nA **cookie in JavaScript** is a **small piece of data** stored in the **browser**.\nIt is used to **remember the user**, **store login sessions**, **preferences**, or **track activity**.\n\n**In simple words:**\n\n\u003e *Cookie = small data stored in the browser*\n\n\u003e *Example: remembering username, saving theme, storing cart items, or tracking sessions.*\n\n### **JavaScript Example**\n\n#### **1. Set a Cookie**\n\n```js\ndocument.cookie = \"username=John; expires=Fri, 31 Dec 2025 23:59:59 GMT; path=/\";\n```\n\n#### **2. Get All Cookies**\n\n```js\nconsole.log(document.cookie);\n```\n\n#### **3. Delete a Cookie**\n\n```js\ndocument.cookie = \"username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/\";\n```\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 42. What is a promise?\nA Promise is a JavaScript object that represents the eventual result of an asynchronous operation—whether it succeeds or fails.\nIt serves as a placeholder for a value that isn’t available yet but will be provided at some point in the future once the operation completes.\n\n**In simple words:**\n\n\u003e *Promise = an object that guarantees you will get the result in the future*\n\n\u003e It handles the result of async tasks (success or error).\n\n### **3 States of a Promise**\n\n1. **Pending** → The result is not available yet\n2. **Fulfilled** → The operation completed successfully\n3. **Rejected** → The operation failed (error)\n\n### **Simple Example**\n\n```js\nlet myPromise = new Promise((resolve, reject) =\u003e {\n  let success = true;\n\n  if (success) {\n    resolve(\"Operation Successful!\");\n  } else {\n    reject(\"Something went wrong!\");\n  }\n});\n\nmyPromise\n  .then(result =\u003e console.log(result)) // Success case\n  .catch(error =\u003e console.log(error)); // Error case\n```\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n### 43. **Why do we need a Promise in JavaScript**\n\nWe need **Promises** to handle **asynchronous operations** in a clean and manageable way.\nJavaScript runs tasks one by one, so when something takes time—like fetching data from a server—Promises help us handle the result **without blocking** the rest of the code.\n\n\n### **Reasons we need Promises**\n\n**1. To handle asynchronous tasks easily**\n\nExample: fetching data from an API, reading files, waiting for timers.\n\n**2. To avoid “callback hell”**\n\nPromises provide `.then()` and `.catch()` instead of deeply nested callback functions.\n\n**3. To write cleaner and more readable code**\n\nPromises, especially with `async/await`, make asynchronous code look like synchronous code.\n\n**4. Better error handling**\n\n`.catch()` handles all errors in one place, making debugging easier.\n\n **5. Promises chain smoothly**\n\nYou can run async operations step-by-step using `.then()` chaining.\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n## 44. What are Closures\nA closure is a function that remembers and can access variables from its outer (lexical) scope, even after the outer function has finished executing.\nIt is created when an inner function uses variables of its enclosing function.\n\nThe closure has access to **three scope chains**:\n\ni. **Its own scope** – variables defined inside its curly braces\nii. **Outer function’s scope** – variables of the enclosing function\niii. **Global scope** – globally declared variables\n\n---\n\n### **Example of Closure Concept**\n\n```javascript\nfunction Welcome(name) {\n  var greetingInfo = function (message) {\n    console.log(message + \" \" + name);\n  };\n  return greetingInfo;\n}\n\nvar myFunction = Welcome(\"John\");\n\nmyFunction(\"Welcome\");   // Output: Welcome John\nmyFunction(\"Hello Mr.\"); // Output: Hello Mr. John\n```\n\n---\n\n### **Explanation**\n\nIn the above code:\n\n* `Welcome()` is the **outer function**\n* `greetingInfo()` is the **inner function**\n* The inner function uses the variable `name` from the outer function\n\nEven after the `Welcome()` function has finished execution,\nthe inner function **still remembers and has access to `name`**.\n\nThis behavior of remembering variables from the outer scope is called a **closure**.\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n## 45. What is IndexedDB\n\nIndexedDB is a low-level API for client-side storage of larger amounts of structured data, including files/blobs. This API uses indexes to enable high-performance searches of this data.\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n## 46. What is Collation\nCollation determines how strings are compared, sorted, and matched. It controls whether text comparison is case-sensitive or case-insensitive and how characters are ordered based on language rules.\n\n**Example:**\nIn a case-insensitive collation, “Apple” and “apple” are treated as the same, while in case-sensitive collation they are considered different.\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n## 47. Why do you need web storage\nWeb Storage allows web applications to store data locally in the user’s browser, such as user preferences, login state, or theme settings. It improves performance by reducing server requests and provides a better user experience.\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n## 48. How do you delete a cookie\nTo delete a cookie, we re-set the same cookie with the same name and path, but with an expiration date in the past, which tells the browser to remove it.\n\n**Example:**\n\n```javascript\ndocument.cookie = \"username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;\";\n```\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n## 49. What is promise.all\n`Promise.all()` takes an array of promises and returns a single promise. It resolves with an array of results when all promises succeed, but if any promise rejects, it immediately rejects with that error.\n\n**Example:**\n\n```javascript\nPromise.all([\n  fetch('/api/user'),\n  fetch('/api/posts'),\n  fetch('/api/comments')\n])\n.then(results =\u003e {\n  console.log(\"All promises resolved\", results);\n})\n.catch(error =\u003e {\n  console.error(\"One promise failed\", error);\n});\n```\n\n[🔼 Back to Top](#-table-of-contents)\n\n---\n\n## 50. What is undefined property\nIn JavaScript, when we try to access an object property that is not defined or a variable that has been declared but not initialized, JavaScript returns undefined.\n\n**Example:**\n\n```javascript\nlet user = { name: \"Dhrub\" };\n\nconsole.log(user.age); // undefined (property does not exist)\n```\n\n**Important Points:**\n\n* undefined is a primitive data type\n* It means absence of a value\n* Different from null (null is intentionally assigned)\n\n[🔼 Back to Top](#-table-of-contents)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcodewithdhruba01%2Fjavascript-interview-questions","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcodewithdhruba01%2Fjavascript-interview-questions","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcodewithdhruba01%2Fjavascript-interview-questions/lists"}