JavaScript
JavaScript
June 11, 2025 at 08:38 AM
🔥 *Scenario-Based JavaScript Interview Questions with Answers* 💻⚡ *1. Scenario: Asynchronous API Call Not Working* *Q:* An API call is not returning expected data. How would you debug it? *A:* Check if `await` is used correctly with `async`. Ensure correct headers and endpoint. Use `console.log` and the Network tab in DevTools to inspect requests. *2. Scenario: Page Freezes on Button Click* *Q:* A button click causes the page to freeze. What might be wrong? *A:* Likely a blocking loop or heavy computation on the main thread. Move heavy logic to Web Workers or use `setTimeout` to defer processing. *3. Scenario: Data Doesn’t Update After API Call* *Q:* You update state after an API call, but UI doesn’t refresh. Why? *A:* In React, ensure you're using `useState` correctly. State update must be immutable: `setData([...data, newItem])`. *4. Scenario: Event Listener Not Working* *Q:* Why isn’t a click event triggering on a dynamically added element? *A:* The element didn’t exist at initial render. Use event delegation: ```js document.body.addEventListener('click', function(e) { if (e.target.matches('.dynamic-btn')) { // Handle click } }); ``` *5. Scenario: LocalStorage Not Persisting* *Q:* Why is data missing from `localStorage` after page reload? *A:* Ensure `localStorage.setItem()` is called correctly. Remember it stores *strings*, so use `JSON.stringify()` for objects. Check browser privacy settings. *6. Scenario: NaN Displayed in Output* *Q:* A calculation shows `NaN` in output. What could be wrong? *A:* Likely performing math on `undefined` or a string. Use `typeof` to validate input types before calculations. *7. Scenario: Form Submission Reloads Page* *Q:* Why does your form refresh the page on submit? *A:* Default form behavior is to reload. Prevent it: ```js form.addEventListener('submit', (e) => { e.preventDefault(); }); ``` *8. Scenario: CORS Error in Fetch* *Q:* Your frontend can’t fetch data due to CORS. What’s the fix? *A:* Backend must allow CORS (set headers or use `cors` in Express). Dev workaround: proxy through a server or `http-proxy-middleware`. *9. Scenario: Unexpected `undefined` Value* *Q:* You keep getting `undefined` when accessing an object. *A:* Check if the key exists before access. Use optional chaining: `obj?.user?.name`. Also ensure async data is available before access. *10. Scenario: Debounce Search Input* *Q:* How do you reduce API calls while typing in a search box? *A:* Use debouncing: ```js function debounce(fn, delay) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => fn.apply(this, args), delay); }; } ``` *React ❤️ for more!*
❤️ 👍 🙏 😂 26

Comments