JavaScript Interview Questions 26-30 (Delegation, Optimization, Modules, Fetch, CORS)
Welcome to the final part of our Core JavaScript interview series. You have journeyed from basic data types to complex asynchronous logic. Now, we focus on optimization, architecture, and networking.
These questions test your ability to write efficient code (handling events and function calls smartly), structure your applications (modules), and communicate with the outside world (fetching data and security). These are daily tasks for a Full Stack developer. Let's finish strong!
26. What is event delegation?
Event delegation is a pattern where we attach a single event listener to a parent element to handle events for all its children (even ones that haven't been created yet). It works because of event bubbling (events bubbling up from the target to the parent).
Analogy: Imagine an office building with 100 employees. Instead of giving a letter to every single employee individually (100 listeners), you give all the mail to one receptionist at the front desk (1 listener). The receptionist checks the name on the envelope (the event target) and handles it accordingly.
Why use it?
- Memory efficiency: Fewer listeners mean less memory usage.
- Dynamic content: It works for elements added to the DOM later via JavaScript.
// HTML Structure:
// <ul id="todo-list">
// <li class="item">Task 1</li>
// <li class="item">Task 2</li>
// </ul>
const list = document.getElementById('todo-list');
// Delegate the event: Listen on the <ul>, not the <li>s
list.addEventListener('click', (event) => {
// Check if the actual thing clicked was a list item
if (event.target && event.target.matches('li.item')) {
console.log("Clicked on: " + event.target.textContent);
}
});
// Even if we add a new item now, the listener above still works!
const newItem = document.createElement('li');
newItem.className = 'item';
newItem.textContent = 'Task 3 (Dynamic)';
list.appendChild(newItem);
Sample Output (on click):
Clicked on: Task 1
Clicked on: Task 3 (Dynamic)
27. What are debouncing and throttling?
These are techniques to control how often a function is executed. They are essential for performance when handling events that fire rapidly, like window resizing, scrolling, or typing in a search bar.
- Debouncing: Ensures a function is not called until a certain amount of time has passed since the last time it was called. "Wait for the silence."
- Throttling: Ensures a function is called at most once in a specified time period. "Run at a steady pace."
Analogy:
Debounce (Elevator): The elevator door stays open. It waits. If someone walks in, it resets the timer. It only closes and moves when no one has walked in for 5 seconds.
Throttle (Machine Gun): You can pull the trigger as fast as you want, but the gun will only fire bullets at a fixed rate (e.g., once every 0.1 seconds).
// 1. Debounce Example (Good for Search Bars)
function debounce(func, delay) {
let timer;
return (...args) => {
clearTimeout(timer); // Reset the timer if called again
timer = setTimeout(() => func(...args), delay);
};
}
const search = debounce((query) => {
console.log("Searching API for:", query);
}, 1000);
// User types fast: "a", "ap", "app"
search("a");
search("ap");
search("app");
// Only the last one runs after 1 second of silence.
// 2. Throttle Example (Good for Scroll Events)
function throttle(func, limit) {
let inThrottle;
return (...args) => {
if (!inThrottle) {
func(...args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
const logScroll = throttle(() => {
console.log("Scroll event logged!");
}, 2000);
// Even if the user scrolls 100 times a second,
// 'logScroll' only runs once every 2 seconds.
Sample Output:
// (After 1 second)
Searching API for: app
// (If scrolling continuously)
Scroll event logged!
// ... waits 2 seconds ...
Scroll event logged!
28. What are JavaScript modules (ES6 modules)?
Modules allow us to split our code into separate files, making it more maintainable, reusable, and organized. Before ES6, everything was in a global scope (often leading to naming conflicts). ES6 modules introduced the import and export syntax.
- Strict Mode: Modules always run in strict mode automatically.
- File-based scope: Variables in a module are not global unless explicitly exported.
// --- mathUtils.js ---
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
// --- main.js ---
// We import specific functionalities
import { add, PI } from './mathUtils.js';
console.log("PI is:", PI);
console.log("Sum is:", add(2, 5));
// Note: To run this in a browser, your <script> tag needs type="module"
29. What are fetch API and XMLHttpRequest (XHR)?
Both are used to make network requests (like getting data from a server) without reloading the page.
| Feature | XMLHttpRequest (XHR) | Fetch API |
|---|---|---|
| Age | Old way (Legacy) | Modern Standard |
| Handling | Callback-based (messy) | Promise-based (cleaner) |
| JSON | Must parse manually | Built-in .json() method |
Fetch is the standard for modern development, though XHR is still the engine behind libraries like Axios (for backward compatibility).
// The Modern Way: Fetch
fetch('https://api.example.com/data')
.then(response => {
// Fetch doesn't reject on HTTP error (like 404), so we check 'ok'
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then(data => console.log("Data:", data))
.catch(error => console.error("Error:", error));
30. What is CORS and how does it work?
CORS stands for Cross-Origin Resource Sharing. It is a security feature implemented by browsers. By default, browsers block web pages from making requests to a different domain (origin) than the one that served the web page. This prevents malicious sites from reading your data on other sites.
Analogy: Imagine you are at a club (Origin A). You want to order a drink from the bar next door (Origin B). The bouncer (Browser) stops you. The only way the bouncer lets the drink through is if the bar next door explicitly puts a sticker on the cup saying, "This drink is allowed to be consumed at Club A."
How it works technically:When you make a request to a different domain, the browser adds anOrigin header. The server must reply with a specific header: Access-Control-Allow-Origin.
- Request (Browser): "Hey api.com, I am calling from mywebsite.com. Can I have data?"
- Response (Server): "Yes, I have a header
Access-Control-Allow-Origin: *(or specifically mywebsite.com). Here is your data." - Result: Browser accepts the data. If the header is missing, the Browser throws a CORS error.
Tip: CORS errors are browser errors, not server errors. The server often sends the data fine, but the browser hides it from your JavaScript because the security pass (header) was missing.
You have completed the 30-question JavaScript challenge! You now possess a robust understanding of the language, from variable declaration to how it handles network security. These concepts—delegation, async logic, modules, and the DOM—form the backbone of every modern framework like React, Vue, or Angular. Be proud of your progress and keep coding!