≡ Menu

JavaScript Questions That Could Be Asked In an Interview

The field of JavaScript development is constantly evolving, and interviews often go beyond basic syntax to test a candidate’s understanding of core concepts.

Tricky JavaScript questions are a common part of this process, designed to evaluate how a developer thinks about the language’s nuances, particularly its asynchronous nature, lexical scoping, and the “this” keyword. 🤯

These questions aren’t just about getting the right answer; they’re about demonstrating a deep comprehension of fundamental principles like closures, hoisting, and the event loop .

A strong performance on these questions shows an interviewer that you can write predictable and bug-free code, and that you’re prepared to tackle the complex challenges of modern web development.

Here are a few tricky Javascript questions to get you warmed up:

Question 1:

What’s the output of the following code and why?

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1000);
}

Answer:

The output will be 3 printed three times after a one-second delay. This is because var is function-scoped, not block-scoped.

The setTimeout callback function creates a closure, which “remembers” the outer scope’s variable i. By the time the setTimeout callbacks execute, the for loop has already completed, and the value of i has been incremented to 3.

All three closures refer to the same i in the same memory location, which now holds the value 3.


Tricky Questions on Hoisting

 

Question 2:

What’s the output of the following code and why?

console.log(a);
var a = 5;

Answer:

The output will be undefined. In JavaScript, variable declarations are hoisted to the top of their scope, but initializations are not. So, the code is interpreted as:

var a;
console.log(a); // a is declared but not yet assigned a value, so it's undefined
a = 5;

Tricky Questions on the Event Loop

 

Question 3:

What’s the order of the console logs and why?

console.log('Start');

setTimeout(() => {
  console.log('Timeout');
}, 0);

Promise.resolve().then(() => {
  console.log('Promise');
});

console.log('End');

Answer:

The output will be: Start, End, Promise, Timeout.

This is a classic question about the event loop and the task queue vs. microtask queue.

  1. console.log('Start') is a synchronous operation and runs immediately.
  2. setTimeout is an asynchronous Web API. Its callback is placed in the task queue (also known as the macrotask queue). It will run after all other code in the current stack and all microtasks have finished.
  3. Promise.resolve().then(...) is also asynchronous, but its callback is placed in the microtask queue. The event loop prioritizes the microtask queue over the task queue.
  4. console.log('End') is a synchronous operation and runs immediately after Start.
  5. After the synchronous code completes, the event loop checks the microtask queue. It finds the Promise callback and executes it, logging 'Promise'.
  6. Finally, after the microtask queue is empty, the event loop checks the task queue, finds the setTimeout callback, and executes it, logging 'Timeout'.

Try solving all of the problems below.

Problems 26-55 are considered advanced or “senior-level” JavaScript interview questions.

  1. Reverse a String
  2. Check if a String is a Palindrome
  3. Remove Duplicates from a String
  4. Find the First Non-Repeating Character
  5. Count the Occurrences of Each Character
  6. Reverse Words in a Sentence
  7. Check if Two Strings are Anagrams
  8. Find the Longest Substring Without Repeating Characters
  9. Convert a String to an Integer (atoi Implementation)
  10. Compress a String (Run-Length Encoding)
  11. Find the Most Frequent Character
  12. Find All Substrings of a Given String
  13. Check if a String is a Rotation of Another String
  14. Remove All White Spaces from a String
  15. Check if a String is a Valid Shuffle of Two Strings
  16. Convert a String to Title Case
  17. Find the Longest Common Prefix
  18. Convert a String to a Character Array
  19. Replace Spaces with %20 (URL Encoding)
  20. Convert a Sentence into an Acronym
  21. Check if a String Contains Only Digits
  22. Find the Number of Words in a String
  23. Remove a Given Character from a String
  24. Find the Shortest Word in a String
  25. Find the Longest Palindromic Substring
  26. Build a custom Promise from scratch.
  27. Create your own Promise.all implementation.
  28. Design a Promise.any that resolves to the first fulfilled promise.
  29. Develop a Promise.race to resolve based on the fastest result.
  30. Implement Promise.allSettled to handle multiple results—fulfilled or rejected.
  31. Add a finally method for promises that always runs, regardless of outcome.
  32. Convert traditional callback-based functions into promises (promisify).
  33. Implement custom methods for Promise.resolve() and Promise.reject().
  34. Execute N async tasks in series—one after another.
  35. Handle N async tasks in parallel and collect results.
  36. Process N async tasks in race to pick the fastest one.
  37. Recreate setTimeout() from scratch.
  38. Rebuild setInterval() for periodic execution.
  39. Design a clearAllTimers function to cancel all timeouts and intervals.
  40. Add auto-retry logic for failed API calls with exponential backoff.
  41. Create a debounce function to limit how often a task is executed.
  42. Implement throttling to control the frequency of function calls.
  43. Group API calls in batches to reduce server load.
  44. Build a cache system to memoize identical API calls for better performance.
  45. Develop a promise chaining system to handle dependent tasks seamlessly.
  46. Write a timeout-safe promise to reject automatically if it takes too long.
  47. Implement a retry mechanism with a maximum attempt limit.
  48. Create a cancelable promise to terminate unwanted async tasks.
  49. Build an event emitter to handle custom events in an asynchronous flow.
  50. Simulate async polling to continuously check server updates.
  51. Design a rate limiter to handle high-frequency API requests.
  52. Implement a job scheduler that runs async tasks at specified intervals.
  53. Develop a parallel execution pool to limit concurrency in async tasks.
  54. Create a lazy loader for async data fetching.
  55. Build an async pipeline to process tasks in stages with dependencies.

Find the largest number in a Javascript array (one of my LinkedIn posts)

Bonus Questions (React):

Your React app is getting slower when rendering a large list. How will you optimize it?

How would you handle API call retries with exponential backoff in React?

You have a component with heavy computations. How do you prevent unnecessary recalculations?

A child component re-renders even when props don’t change — what’s your debugging approach?

How do you implement role-based authentication in a React app?

You need to share state across deeply nested components. What options do you have?

How do you handle memory leaks in React apps (like setInterval, subscriptions)?

What’s your strategy for error handling at the global React app level?

How would you design a theme switcher (dark/light mode) in React?

Your app needs offline support — how would you implement it?

Useful links below:

Let me & my team build you a money making website/blog for your business https://bit.ly/tnrwebsite_service

Get Bluehost hosting for as little as $1.99/month (save 75%)…https://bit.ly/3C1fZd2

Join my Patreon for one-on-one coaching and help with your coding…https://www.patreon.com/c/TyronneRatcliff

Buy me a coffee ☕️https://buymeacoffee.com/tyronneratcliff

{ 0 comments… add one }

Leave a Comment