├── setInterval_using_setTimeout.js ├── array_equality.js ├── lru-cache.js ├── custom_promise.js ├── fetch_polyfill.js ├── critical_css.md ├── custom_logger.js ├── recursive_file_path.js ├── accordion.html ├── deep_clone.js ├── snake-ladder-game.js ├── drag-and-drop.html ├── auto-suggestions-input-box.html └── js_interview_questions.md /setInterval_using_setTimeout.js: -------------------------------------------------------------------------------- 1 | function customSetInterval(callback, delay) { 2 | let timerId; 3 | 4 | function repeat() { 5 | timerId = setTimeout(() => { 6 | callback(); 7 | repeat(); // recursively call again 8 | }, delay); 9 | } 10 | 11 | repeat(); 12 | 13 | // return a function to stop the interval 14 | return () => clearTimeout(timerId); 15 | } 16 | 17 | // Example usage 18 | const stop = customSetInterval(() => { 19 | console.log('Tick 🕒'); 20 | }, 1000); 21 | 22 | // Stop after 5 seconds 23 | setTimeout(() => { 24 | stop(); 25 | console.log('Stopped 🚫'); 26 | }, 5000); 27 | -------------------------------------------------------------------------------- /array_equality.js: -------------------------------------------------------------------------------- 1 | let arr = [1, 2, 3]; 2 | 3 | console.log(arr == arr); 4 | // true ✅ Same reference in memory. 5 | 6 | console.log([1, 2, 3] == [1, 2, 3]); 7 | // false ❌ Different arrays → different references, even if contents match. 8 | 9 | console.log(arr === [1, 2, 3]); 10 | // false ❌ Strict equality, still different references. 11 | 12 | console.log(arr.toString() == [1, 2, 3].toString()); 13 | // true ✅ Both convert to "1,2,3" (string comparison). 14 | 15 | console.log(arr == "1,2,3"); 16 | // true ✅ Array gets coerced → "1,2,3", then compared to string. 17 | 18 | console.log([arr] == "1,2,3"); 19 | // true ✅ [arr] → ["1,2,3"] → "1,2,3", matches string. 20 | -------------------------------------------------------------------------------- /lru-cache.js: -------------------------------------------------------------------------------- 1 | class LRUCache { 2 | constructor(capacity) { 3 | this.capacity = capacity; 4 | this.cache = new Map(); 5 | } 6 | 7 | get(key) { 8 | if (!this.cache.has(key)) return -1; 9 | 10 | const value = this.cache.get(key); 11 | this.cache.delete(key); 12 | this.cache.set(key, value); // Move the accessed item to the end 13 | return value; 14 | } 15 | 16 | put(key, value) { 17 | if (this.cache.has(key)) { 18 | this.cache.delete(key); // Remove the key to update its position 19 | } 20 | 21 | this.cache.set(key, value); 22 | 23 | if (this.cache.size > this.capacity) { 24 | const lruKey = this.cache.keys().next().value; // Get the least recently used key 25 | this.cache.delete(lruKey); 26 | } 27 | } 28 | } 29 | 30 | // Example Usage 31 | const cache = new LRUCache(3); 32 | cache.put(1, "A"); 33 | cache.put(2, "B"); 34 | cache.put(3, "C"); 35 | console.log(cache.get(1)); // "A" 36 | cache 37 | -------------------------------------------------------------------------------- /custom_promise.js: -------------------------------------------------------------------------------- 1 | function customPromiseAll(promises) { 2 | return new Promise((resolve, reject) => { 3 | let results = []; 4 | let completed = 0; 5 | 6 | if (promises.length === 0) resolve([]); 7 | 8 | promises.forEach((promise, index) => { 9 | Promise.resolve(promise) 10 | .then((value) => { 11 | results[index] = value; 12 | completed++; 13 | if (completed === promises.length) { 14 | resolve(results); 15 | } 16 | }) 17 | .catch(reject); // Rejects immediately if any promise fails 18 | }); 19 | }); 20 | } 21 | 22 | // Test Cases 23 | const p1 = Promise.resolve(10); 24 | const p2 = Promise.resolve(20); 25 | const p3 = new Promise((_, reject) => setTimeout(reject, 100, 'Error')); 26 | 27 | customPromiseAll([p1, p2]) 28 | .then(console.log) // Output: [10, 20] 29 | .catch(console.error); 30 | 31 | customPromiseAll([p1, p2, p3]) 32 | .then(console.log) 33 | .catch(console.error); // Output: "Error" 34 | -------------------------------------------------------------------------------- /fetch_polyfill.js: -------------------------------------------------------------------------------- 1 | // Only define fetch if it doesn't exist 2 | if (!window.fetch) { 3 | // Polyfill fetch using XMLHttpRequest 4 | window.fetch = function (url, options = {}) { 5 | // Return a Promise like native fetch 6 | return new Promise((resolve, reject) => { 7 | const xhr = new XMLHttpRequest() // Create XHR object 8 | xhr.open(options.method || 'GET', url) // Set method or default to GET 9 | 10 | // Set headers if provided 11 | for (const key in options.headers || {}) { 12 | xhr.setRequestHeader(key, options.headers[key]) 13 | } 14 | 15 | // Resolve Promise on success 16 | xhr.onload = () => { 17 | resolve({ 18 | text: () => Promise.resolve(xhr.responseText), // text() method 19 | status: xhr.status, // HTTP status code 20 | }) 21 | } 22 | 23 | // Reject Promise on network error 24 | xhr.onerror = () => reject(new TypeError('Network request failed')) 25 | 26 | // Send request body if provided 27 | xhr.send(options.body) 28 | }) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /critical_css.md: -------------------------------------------------------------------------------- 1 | # ⚡ Critical CSS – Complete Guide for Developers 2 | 3 | ## 🔹 What is Critical CSS? 4 | When someone opens your website, the browser needs CSS before it can show anything. 5 | If your CSS file is big, the browser waits until it downloads everything → user sees a blank screen 😐. 6 | 7 | **Critical CSS** = the *small chunk of CSS* needed to style the first part of your page (above-the-fold, the area visible without scrolling). 8 | 9 | 👉 Put this CSS inside `` → content shows up instantly. 10 | 👉 Load the rest of the CSS later in the background. 11 | 12 | --- 13 | 14 | ## 🔹 Why use Critical CSS? 15 | - 🚀 Faster load → users see something quickly. 16 | - 📈 Better SEO → Google ranks fast sites higher. 17 | - 🎨 Better UX → avoids “unstyled flash.” 18 | - 📲 Great for mobile users → especially on slow networks. 19 | 20 | --- 21 | 22 | ## 🔹 How it Works 23 | 1. Extract CSS for the top of the page. 24 | 2. Inline it in `` using ` 39 | 40 | 41 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /custom_logger.js: -------------------------------------------------------------------------------- 1 | const Logger = (() => { 2 | const styles = { 3 | log: 'color: #00bcd4; font-weight: bold', 4 | info: 'color: #4caf50; font-weight: bold', 5 | warn: 'color: #ff9800; font-weight: bold', 6 | error: 'color: #f44336; font-weight: bold', 7 | success: 'color: #8bc34a; font-weight: bold', 8 | timestamp: 'color: gray; font-style: italic', 9 | }; 10 | 11 | let debugMode = true; 12 | 13 | const formatTime = () => 14 | new Date().toLocaleTimeString('en-IN', { hour12: false }); 15 | 16 | const log = (type, label, ...args) => { 17 | if (!debugMode) return; 18 | const time = formatTime(); 19 | const style = styles[type] || styles.log; 20 | console.log( 21 | `%c[${type.toUpperCase()}]%c [${label}] %c@${time}`, 22 | style, 23 | 'color: #3f51b5; font-weight: bold', 24 | styles.timestamp, 25 | ...args 26 | ); 27 | }; 28 | 29 | return { 30 | enable: () => (debugMode = true), 31 | disable: () => (debugMode = false), 32 | log: (...args) => log('log', 'General', ...args), 33 | info: (label, ...args) => log('info', label, ...args), 34 | warn: (label, ...args) => log('warn', label, ...args), 35 | error: (label, ...args) => log('error', label, ...args), 36 | success: (label, ...args) => log('success', label, ...args), 37 | }; 38 | })(); 39 | 40 | 41 | Logger.log('Just a simple message'); 42 | Logger.info('AuthModule', 'User logged in'); 43 | Logger.warn('API', 'Slow response time'); 44 | Logger.error('Database', 'Connection failed!'); 45 | Logger.success('Build', 'Deployed successfully 🚀'); 46 | 47 | // Turn off logging 48 | Logger.disable(); 49 | Logger.log('This won’t show'); 50 | 51 | // Turn it back on 52 | Logger.enable(); 53 | Logger.log('Back again!'); 54 | -------------------------------------------------------------------------------- /recursive_file_path.js: -------------------------------------------------------------------------------- 1 | function getFilePaths(folder, path = "") { 2 | let filePaths = []; // Initialize an array to store file paths 3 | 4 | for (let key in folder) { // Iterate over each key in the folder object 5 | let newPath = path ? `${path}/${key}` : key; // Construct the file path 6 | 7 | if (folder[key] === "file") { 8 | // If the value is "file", it means it's a file, so add the path to the result 9 | filePaths.push(newPath); 10 | } else if (typeof folder[key] === "object" && Object.keys(folder[key]).length > 0) { 11 | // If the value is an object and it's not empty, recurse into it 12 | filePaths.push(...getFilePaths(folder[key], newPath)); 13 | } 14 | // If the object is empty, it's an empty folder, so we skip it 15 | } 16 | 17 | return filePaths; // Return the accumulated file paths 18 | } 19 | 20 | // Complex folder structure example 21 | const complexFolderStructure = { 22 | src: { 23 | components: { 24 | Button: { 25 | "index.js": "file", 26 | "style.css": "file", 27 | tests: { 28 | "button.test.js": "file" 29 | } 30 | }, 31 | Header: { 32 | "header.js": "file", 33 | "header.css": "file", 34 | assets: { 35 | images: { 36 | "logo.png": "file", 37 | "banner.jpg": "file" 38 | } 39 | } 40 | } 41 | }, 42 | utils: { 43 | "helpers.js": "file", 44 | "constants.js": "file", 45 | deepUtils: { 46 | moreUtils: { 47 | "deepHelper.js": "file" 48 | } 49 | } 50 | }, 51 | emptyFolder: {} // This is an empty folder and will be skipped 52 | }, 53 | public: { 54 | "index.html": "file", 55 | assets: { 56 | images: { 57 | "favicon.ico": "file", 58 | backgrounds: { 59 | "background1.png": "file", 60 | "background2.png": "file" 61 | } 62 | } 63 | } 64 | } 65 | }; 66 | 67 | // Get file paths from the nested structure 68 | const result = getFilePaths(complexFolderStructure); 69 | console.log(result); // Output all file paths 70 | -------------------------------------------------------------------------------- /accordion.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Accordion in JS 6 | 39 | 40 | 41 | 42 |
43 |
44 | 45 |
46 |

This is content for section 1.

47 |
48 |
49 |
50 | 51 |
52 |

This is content for section 2.

53 |
54 |
55 |
56 | 57 |
58 |

This is content for section 3.

59 |
60 |
61 |
62 | 63 | 80 | 81 | 82 | 83 | -------------------------------------------------------------------------------- /deep_clone.js: -------------------------------------------------------------------------------- 1 | function deepClone(obj, hash = new WeakMap()) { 2 | if (obj === null || typeof obj !== "object") { 3 | return obj; // Return primitives and functions as they are 4 | } 5 | 6 | if (hash.has(obj)) { 7 | return hash.get(obj); // Handle circular references 8 | } 9 | 10 | let clone; 11 | 12 | if (Array.isArray(obj)) { 13 | clone = []; 14 | } else if (obj instanceof Date) { 15 | clone = new Date(obj); 16 | } else if (obj instanceof RegExp) { 17 | clone = new RegExp(obj); 18 | } else if (obj instanceof Map) { 19 | clone = new Map([...obj].map(([key, value]) => [deepClone(key, hash), deepClone(value, hash)])); 20 | } else if (obj instanceof Set) { 21 | clone = new Set([...obj].map(value => deepClone(value, hash))); 22 | } else if (ArrayBuffer.isView(obj)) { 23 | clone = new obj.constructor(obj); 24 | } else if (obj instanceof ArrayBuffer) { 25 | clone = obj.slice(0); 26 | } else if (typeof obj === "symbol") { 27 | clone = Symbol(obj.description); 28 | } else { 29 | clone = {}; 30 | } 31 | 32 | hash.set(obj, clone); // Store reference in WeakMap 33 | 34 | for (let key of Object.keys(obj)) { 35 | clone[key] = deepClone(obj[key], hash); 36 | } 37 | 38 | return clone; 39 | } 40 | const obj = { 41 | name: "Alice", 42 | details: { age: 25, hobbies: ["reading", "coding"] }, 43 | date: new Date(), 44 | regex: /test/i, 45 | map: new Map([["key1", "value1"], ["key2", { nested: "object" }]]), 46 | set: new Set([1, 2, 3, { a: 4 }]), 47 | buffer: new ArrayBuffer(8), 48 | typedArray: new Uint8Array([1, 2, 3]), 49 | symbol: Symbol("test"), 50 | }; 51 | 52 | const clonedObj = deepClone(obj); 53 | 54 | // Modify clone 55 | clonedObj.details.age = 30; 56 | clonedObj.map.set("key1", "modified"); 57 | clonedObj.set.add(100); 58 | 59 | // Check if original remains unchanged 60 | console.log(obj.details.age); // 25 (original remains unchanged) 61 | console.log(clonedObj.details.age); // 30 (modified copy) 62 | console.log(obj.date === clonedObj.date); // false (deep cloned) 63 | console.log(obj.regex === clonedObj.regex); // false (deep cloned) 64 | console.log(obj.map === clonedObj.map); // false (deep cloned) 65 | console.log(obj.set === clonedObj.set); // false (deep cloned) 66 | console.log(obj.buffer === clonedObj.buffer); // false (deep cloned) 67 | console.log(obj.typedArray === clonedObj.typedArray); // false (deep cloned) 68 | console.log(obj.symbol === clonedObj.symbol); // false (deep cloned, new Symbol) 69 | -------------------------------------------------------------------------------- /snake-ladder-game.js: -------------------------------------------------------------------------------- 1 | class SnakeLadderGame { 2 | constructor(boardSize = 100) { 3 | this.boardSize = boardSize; 4 | this.snakes = new Map(); 5 | this.ladders = new Map(); 6 | this.players = new Map(); 7 | this.turnQueue = []; 8 | } 9 | 10 | addSnake(start, end) { 11 | if (start <= end) throw new Error("Invalid snake position!"); 12 | this.snakes.set(start, end); 13 | } 14 | 15 | addLadder(start, end) { 16 | if (start >= end) throw new Error("Invalid ladder position!"); 17 | this.ladders.set(start, end); 18 | } 19 | 20 | addPlayer(name) { 21 | if (this.players.has(name)) throw new Error("Player already exists!"); 22 | this.players.set(name, 1); 23 | this.turnQueue.push(name); 24 | } 25 | 26 | rollDice() { 27 | return Math.floor(Math.random() * 6) + 1; 28 | } 29 | 30 | movePlayer(player) { 31 | if (!this.players.has(player)) return; 32 | 33 | let diceValue = this.rollDice(); 34 | let newPosition = this.players.get(player) + diceValue; 35 | 36 | if (newPosition > this.boardSize) { 37 | console.log(`${player} rolled ${diceValue}, but stays at ${this.players.get(player)} (out of bounds)`); 38 | return; 39 | } 40 | 41 | if (this.snakes.has(newPosition)) { 42 | console.log(`${player} encountered a 🐍 Snake! Moving from ${newPosition} to ${this.snakes.get(newPosition)}`); 43 | newPosition = this.snakes.get(newPosition); 44 | } else if (this.ladders.has(newPosition)) { 45 | console.log(`${player} found a 🪜 Ladder! Moving from ${newPosition} to ${this.ladders.get(newPosition)}`); 46 | newPosition = this.ladders.get(newPosition); 47 | } 48 | 49 | this.players.set(player, newPosition); 50 | console.log(`${player} rolled ${diceValue} and moved to ${newPosition}`); 51 | 52 | if (newPosition === this.boardSize) { 53 | console.log(`🎉 ${player} wins the game! 🎉`); 54 | this.players.delete(player); 55 | this.turnQueue = this.turnQueue.filter(p => p !== player); 56 | } 57 | } 58 | 59 | playGame() { 60 | while (this.turnQueue.length > 0) { 61 | let currentPlayer = this.turnQueue[0]; 62 | this.movePlayer(currentPlayer); 63 | this.turnQueue.push(this.turnQueue.shift()); 64 | } 65 | console.log("🏁 Game Over!"); 66 | } 67 | } 68 | 69 | // Example Usage 70 | const game = new SnakeLadderGame(); 71 | game.addSnake(98, 40); 72 | game.addSnake(95, 13); 73 | game.addLadder(3, 50); 74 | game.addLadder(20, 80); 75 | 76 | game.addPlayer("Alice"); 77 | game.addPlayer("Bob"); 78 | 79 | game.playGame(); 80 | -------------------------------------------------------------------------------- /drag-and-drop.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Drag & Drop Task Board 7 | 45 | 46 | 47 | 48 |
49 |
50 |

Will Start

51 |
Task 1
52 |
Task 2
53 |
54 |
55 |

Ongoing

56 |
Task 3
57 |
Task 4
58 |
59 |
60 |

Completed

61 |
Task 5
62 |
63 |
64 | 65 | 97 | 98 | 99 | 100 | -------------------------------------------------------------------------------- /auto-suggestions-input-box.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Auto-Suggestions Input Box 7 | 49 | 50 | 51 | 52 |
53 | 54 |
55 |
56 | 57 | 124 | 125 | 126 | 127 | -------------------------------------------------------------------------------- /js_interview_questions.md: -------------------------------------------------------------------------------- 1 | 2 | # 🔥 100 Most Frequently Asked JavaScript Interview Questions 3 | 4 | A carefully curated list of 100 essential JavaScript interview questions for L1 & L2 frontend rounds. Ideal for those preparing for roles in JavaScript, React, Angular, Vue, or Node.js. 5 | 6 | --- 7 | 8 | ## 🧠 Core JavaScript Concepts 9 | 10 | 1. What is the difference between `==` and `===`? 11 | 2. What is a closure in JavaScript? 12 | 3. What is hoisting in JavaScript? 13 | 4. Difference between `let`, `var`, and `const`? 14 | 5. What is the Temporal Dead Zone? 15 | 6. Is JavaScript dynamically or statically typed? 16 | 7. What is the difference between `null` and `undefined`? 17 | 8. What is the type of `NaN`? 18 | 9. What is the event loop in JavaScript? 19 | 10. What is the call stack? 20 | 11. What is a lexical scope? 21 | 12. Explain pass by value vs pass by reference. 22 | 13. What is an Immediately Invoked Function Expression (IIFE)? 23 | 14. What are JavaScript data types? 24 | 15. Explain the `typeof` operator. 25 | 26 | ## ⚙️ Functions & Execution 27 | 28 | 16. Difference between `call()`, `apply()`, and `bind()`? 29 | 17. What is `this` keyword and how does it work? 30 | 18. Arrow functions vs regular functions? 31 | 19. What are pure functions? 32 | 20. What is a higher-order function? 33 | 21. What are callbacks? 34 | 22. What are first-class functions? 35 | 23. What is a function expression vs function declaration? 36 | 24. What are default parameters? 37 | 25. What is function currying? 38 | 39 | ## 📦 Objects, Arrays & Destructuring 40 | 41 | 26. What is object destructuring? 42 | 27. What is array destructuring? 43 | 28. What are the differences between `Object.keys()`, `Object.values()`, and `Object.entries()`? 44 | 29. How to clone an object in JavaScript? 45 | 30. What is the difference between shallow copy and deep copy? 46 | 31. What is `Object.freeze()` vs `Object.seal()`? 47 | 32. How to check if an object is empty? 48 | 33. How to merge two objects? 49 | 34. What is optional chaining (`?.`) in JavaScript? 50 | 35. What is the spread operator and how is it used? 51 | 52 | ## ⏳ Asynchronous JavaScript 53 | 54 | 36. What is a Promise? 55 | 37. What is async/await? 56 | 38. What is the difference between synchronous and asynchronous code? 57 | 39. What is the output of `async function`? 58 | 40. What is the difference between microtasks and macrotasks? 59 | 41. What is Promise.all, Promise.race, Promise.any, and Promise.allSettled? 60 | 42. What is callback hell? 61 | 43. How to handle errors in Promises? 62 | 44. What is the use of `finally` in Promises? 63 | 45. What is event delegation? 64 | 65 | ## 🔄 Arrays & Iteration 66 | 67 | 46. Difference between `map()`, `filter()`, `reduce()`, and `forEach()`? 68 | 47. Difference between `for...in` and `for...of`? 69 | 48. How does `find()` differ from `filter()`? 70 | 49. What does `reduce()` do? 71 | 50. What is the difference between `some()` and `every()`? 72 | 51. What are array-like objects? 73 | 52. How to convert NodeList to an array? 74 | 53. What is array destructuring? 75 | 54. How to flatten a nested array? 76 | 55. What is `.flatMap()`? 77 | 78 | ## 🌐 Browser APIs & Storage 79 | 80 | 56. What is CORS? 81 | 57. Difference between localStorage, sessionStorage, and cookies? 82 | 58. What is IndexedDB? 83 | 59. What is the Fetch API? 84 | 60. How to handle JSON in JavaScript? 85 | 61. What is event bubbling and capturing? 86 | 62. What is the difference between `addEventListener` and `onclick`? 87 | 63. What are custom events? 88 | 64. How to stop event propagation? 89 | 65. What is the History API? 90 | 91 | ## 📜 ES6+ Features 92 | 93 | 66. What are template literals? 94 | 67. What are arrow functions? 95 | 68. What are rest parameters? 96 | 69. What is object property shorthand? 97 | 70. What are modules in JavaScript? 98 | 71. What is the difference between `import` and `require()`? 99 | 72. What are generators? 100 | 73. What is a symbol in JavaScript? 101 | 74. What is `Set` and `Map`? 102 | 75. What is the difference between `forEach` and `map`? 103 | 104 | ## 🚀 Performance & Optimization 105 | 106 | 76. What is debouncing? 107 | 77. What is throttling? 108 | 78. How to optimize JavaScript performance? 109 | 79. What is lazy loading? 110 | 80. What is code splitting? 111 | 81. What is tree shaking? 112 | 82. How to minimize memory leaks? 113 | 83. What is reflow and repaint? 114 | 84. What is event loop blocking? 115 | 85. What is a memory leak in JavaScript? 116 | 117 | ## 🔐 Security & Patterns 118 | 119 | 86. What is XSS? 120 | 87. What is CSRF? 121 | 88. How to prevent common JavaScript security issues? 122 | 89. What are design patterns in JavaScript? 123 | 90. What is the Module pattern? 124 | 91. What is the Singleton pattern? 125 | 92. What is a polyfill? 126 | 93. What is transpilation? 127 | 94. What is Babel? 128 | 95. What is Webpack? 129 | 130 | ## 🧪 Miscellaneous 131 | 132 | 96. What is the difference between `==` and `===`? 133 | 97. What is `eval()` and why is it discouraged? 134 | 98. What is the output of: `3 + 2 + "7"`? 135 | 99. What are service workers? 136 | 100. What’s the difference between authentication and authorization? 137 | --------------------------------------------------------------------------------