JavaScript interview questions
36 questions, easy to hard. Read one, then answer it out loud: an AI interviewer follows up, hints when you're stuck and grades your answer.
JavaScript interviews probe the parts of the language that trip people up: scope and hoisting, equality, closures, the this keyword, promises and the event loop.
Fundamentals
A teammate asks why the style guide says to use const by default, let when a value changes, and never var. Explain the differences between the three, and what goes wrong in a for loop that uses var to create click handlers that each log their own loop number.
What a strong answer covers
- How the three keywords differ in where a variable can be seen.
- What const really protects, and what it leaves changeable.
- What happens when a variable is used before the line that declares it.
- Why a loop's handlers can all end up reporting the same number, and how the keyword choice changes that.
Common mistake: Assuming const makes a value fully unchangeable, when it only fixes which value the name points to.
- Double or Triple Equals
- easy
- Pro
A form check compares the user's input to zero with double equals, and it passes when the input is an empty string. Explain why, how double equals and triple equals differ, and how you'd compare values safely, including objects and the value NaN.
What a strong answer covers
- Why loose comparison can treat values of different types as equal.
- Which comparison to reach for by default, and why.
- How objects and arrays are compared, as opposed to numbers and strings.
- The one value that never equals itself, and the reliable way to test for it.
Common mistake: Expecting two objects with identical contents to compare as equal.
- Truthy and Falsy
- easy
- Pro
A function sets a default page size by writing the argument or twenty, but when a caller passes zero the page size becomes twenty anyway. Explain which values JavaScript treats as falsy, why this bug happens, and how you'd fix it.
What a strong answer covers
- The short list of values a condition treats as false.
- Why a common shortcut for defaults swallows legitimate values like zero.
- A fallback that only kicks in when a value is genuinely missing.
- The cases where default parameters do and don't apply.
Common mistake: Thinking an empty array or empty object counts as false in a condition.
- Null and Undefined
- easy
- Pro
A junior developer asks why JavaScript has both null and undefined, and which one they should use for a user's middle name when it isn't known. Explain where each comes from, how they compare, and how you'd check for either safely.
What a strong answer covers
- Where each of the two empty values comes from.
- Why a team should pick a convention for 'deliberately empty' and stick to it.
- How the two behave under loose and strict comparison, including a well-known quirk.
- Reading possibly missing data without the program crashing.
Common mistake: Treating the two as interchangeable everywhere, then getting caught out by strict comparisons.
- Primitives and References
- easy
- Pro
A function receives a settings object, changes one of its fields, and suddenly settings elsewhere in the app have changed too. But when the same function changes a number it was passed, nothing outside changes. Explain why, and how you'd avoid the surprise.
What a strong answer covers
- How simple values and objects behave differently when handed to a function.
- Why changing a field differs from giving a parameter a new value.
- Ways a function can make its change without touching the caller's data.
- How deep the usual quick copy actually goes.
Common mistake: Saying JavaScript passes objects 'by reference' and so expecting a reassigned parameter to change the caller's variable.
- Destructuring and Spread
- easy
- Pro
You're reviewing code that reads five fields from an options object one line at a time, and builds a new array by looping over two others and pushing each item. Explain how destructuring and the spread and rest syntax would make this shorter, and what to watch out for.
What a strong answer covers
- Pulling several values out of an object or array in one go, with renaming and defaults.
- Combining or extending arrays and objects without loops.
- Gathering 'everything else' into one variable.
- The situations where these shortcuts throw errors or share data unexpectedly.
Common mistake: Forgetting that order matters when spreading objects, so a later property silently overwrites an earlier one.
- Map, Filter and Reduce
- easy
- Pro
You have an array of orders, each with a status and a total. You need the totals of the paid orders, and then their sum. Explain how you'd do this with map, filter and reduce instead of a for loop, and when a plain loop might still be better.
What a strong answer covers
- What each of the three methods does and what it returns.
- Chaining them so each step has one clear job.
- Why the starting value of a reduce matters, especially for empty input.
- When an ordinary loop is the better tool.
Common mistake: Leaving out reduce's starting value, so an empty array throws instead of giving zero.
- Explain Closures
- medium
- Pro
You need a function called makeCounter. Each call to it returns a new counter function, and each time you call a counter it returns the next number, starting at one. Two counters must count independently, and nothing outside should be able to change a counter's number. Explain how you'd build it and why it works.
What a strong answer covers
- Where the counter's number lives so it survives between calls.
- How an inner function keeps access to variables after its outer function has finished.
- Why each counter keeps its own count.
- How this pattern keeps data private, and where else it shows up.
Common mistake: Keeping the count in a variable outside the factory, so every counter shares one number.
- What This Refers To
- medium
- Pro
A class has a method that reads this dot name. Calling it directly works, but passing the method to a button's click handler or to a timer means this no longer refers to the object. Explain how JavaScript decides what this means, and give two ways to fix the bug.
What a strong answer covers
- How JavaScript decides what this means for an ordinary function.
- Why handing a method to someone else to call later loses its object.
- More than one way to keep the method tied to its instance.
- How arrow functions treat this differently.
Common mistake: Believing this is fixed by where a method is written, rather than by how it is called.
- Shallow and Deep Copies
- medium
- Pro
You copy a user object with the spread syntax before editing their address, but the original user's address changes too. Explain why, and compare the ways you could make a full copy, including their limits.
What a strong answer covers
- How far a spread or similar copy actually reaches into nested data.
- Copying just the parts you are about to change.
- Built-in options for a full deep copy, and what each one loses or rejects.
- Weighing a deep copy against a more targeted update.
Common mistake: Using a JSON round-trip as a universal deep copy and silently losing dates, undefined values or functions.
- Floating-Point Surprises
- medium
- Pro
A checkout adds ten pence and twenty pence and the test expecting thirty pence fails, because the result is a tiny bit more than point three. Explain why JavaScript numbers behave like this, and how you'd handle money safely.
What a strong answer covers
- How JavaScript stores numbers, and why some decimals can't be held exactly.
- Why comparing decimal results for exact equality is fragile.
- A safe way to represent amounts of money.
- Number limits beyond decimals, and how to display currency properly.
Common mistake: Fixing the symptom by rounding at random places instead of changing how money is represented.
Objects and Prototypes
- Read and Update Properties
- easy
- Pro
You're building a settings screen where the field to update arrives as a name in a variable, and some settings objects are missing whole sections. Explain the ways to read and change an object's properties, and how to read nested values without crashing.
What a strong answer covers
- The two ways to read and write a property, and when each is needed.
- What happens when the data you expect is missing.
- Reading deeply nested values safely, with sensible defaults.
- Checking that a property exists, and removing one.
Common mistake: Treating a property that holds undefined as the same as one that doesn't exist at all.
- Loop Over an Object
- easy
- Pro
You have an object mapping product names to stock counts and you need to list every product with its count, and the total stock. Explain the ways to loop over an object, and which you'd choose.
What a strong answer covers
- The built-in helpers for getting an object's keys, values or both.
- Why the loop that works on arrays doesn't work on a plain object.
- The catch with the older loop that visits keys.
- Working out the total, and what type the keys always are.
Common mistake: Using for-of directly on a plain object and getting an error that it isn't iterable.
- Classes in JavaScript
- easy
- Pro
Someone coming from Java asks how classes work in JavaScript. Explain how you'd write a bank account class with an owner, a balance and a deposit method, and then a savings account that adds interest.
What a strong answer covers
- Writing a class with a constructor, fields and methods.
- Extending it, and the rule for setting up the parent first.
- Overriding behaviour while still reusing the parent's version.
- How JavaScript classes relate to prototypes, and how privacy works.
Common mistake: Touching this in a subclass constructor before calling super, which throws an error.
- How Prototypes Work
- medium
- Pro
You create an array and call its map method, but when you log the array's own properties, map isn't there. Explain where map comes from, how JavaScript looks up properties through the prototype chain, and how classes relate to this.
What a strong answer covers
- How JavaScript looks up a property an object doesn't have itself.
- Where shared methods such as map actually live.
- How classes fit on top of the same mechanism.
- What happens when an object defines a property with the same name as its prototype.
Common mistake: Adding custom methods to built-in prototypes, which can clash with libraries and future versions of the language.
- Private Fields and Accessors
- medium
- Pro
A shopping cart class exposes its items array, and other code keeps pushing to it directly, skipping the cart's validation. Explain how you'd protect the cart's data, using private fields, getters and setters.
What a strong answer covers
- Making internal data impossible to reach from outside the class.
- Routing every change through methods that check it.
- Using getters and setters where they genuinely help.
- Not handing out a live reference to the internal data.
Common mistake: Making the field private but returning the internal array from a getter, so callers can still change it.
- Map, Set or Object
- medium
- Pro
You're tracking which users are online, counting visits per page, and attaching extra data to DOM elements without leaking memory. Explain when you'd use a plain object, a Map, a Set or a WeakMap for each, and why.
What a strong answer covers
- Which structure fits a collection of unique values.
- Why a Map often beats a plain object for counting by key.
- Attaching data to objects without keeping them alive forever.
- Where plain objects are still the natural choice.
Common mistake: Using a normal Map keyed by DOM elements and leaking memory when the elements are removed.
- Immutable Updates
- medium
- Pro
A state update in your app changes a nested field on an existing object, and the screen doesn't refresh. A colleague suggests Object.freeze. Explain what immutability means here, what freeze does and doesn't do, and how you'd update nested data without mutation.
What a strong answer covers
- Why changing an object in place can go unnoticed by a UI.
- What freezing an object guarantees, and its limits.
- Updating one nested value by building new objects only along that path.
- Built-in methods and libraries that make non-mutating updates easier.
Common mistake: Deep-copying the whole state on every change, which is slow and makes every part look changed.
- Composition over Inheritance
- hard
- Pro
A game has a class hierarchy: Character, then Flying Character and Swimming Character, and now designers want a duck that both flies and swims. Explain why the inheritance tree struggles with this, and how you'd redesign it using composition.
What a strong answer covers
- Why a single inheritance tree struggles with combinations of abilities.
- Building characters out of small, reusable behaviours instead.
- What that flexibility buys in testing and change.
- The costs of composition, and when shallow inheritance is still fine.
Common mistake: Fixing it with a deeper hierarchy or by copying code into a new subclass for each combination.
DOM and Events
- Find and Change Elements
- easy
- Pro
Without any framework, you need to find a page's error message box, put a message in it, and make it visible. Explain how you'd select the element, change its text and styles, and why you'd be careful about using innerHTML.
What a strong answer covers
- Locating an element on the page, and what to do if it isn't there.
- Setting the text safely.
- Showing and hiding things in a way that keeps styling in CSS.
- Why inserting raw HTML from a string carries a security risk.
Common mistake: Using innerHTML to show a message that contains user input.
- Listen for Events
- easy
- Pro
You need a button that counts how many times it has been clicked, without a framework. Explain how you'd attach the click handler, what the event object gives you, and how you'd remove the handler later.
What a strong answer covers
- Attaching a handler to an element.
- Useful information and controls on the event object.
- Removing a handler again, and the catch involved.
- Why inline handler attributes are usually avoided.
Common mistake: Trying to remove a listener by passing a new anonymous function that merely looks like the original.
- Bubbling and Delegation
- medium
- Pro
A to-do list adds a click listener to every delete button. New items added later don't respond, and with thousands of items the page is sluggish. Explain event bubbling, and how event delegation solves both problems.
What a strong answer covers
- How an event travels from the clicked element up through its ancestors.
- Handling many children's clicks with one listener on a parent.
- Why this covers items added later and scales to large lists.
- Subtleties such as which element is which, and events that don't travel upward.
Common mistake: Reaching for stopPropagation as a fix, which can break other code that relies on the event bubbling.
- Handle a Form Submit
- medium
- Pro
A sign-up form posts its data with JavaScript, but every time you press the button the whole page reloads and the request is lost. Explain why, and how you'd handle the submission properly, including pressing Enter and showing validation errors.
What a strong answer covers
- Why submitting a form reloads the page, and how to stop that.
- Which event to listen for so every way of submitting is covered.
- Reading the form's values and using the browser's built-in validation.
- Showing errors accessibly and handling a slow or failed request.
Common mistake: Listening for the button's click instead of the form's submit, so pressing Enter slips through.
- Defer and Async Scripts
- medium
- Pro
A script in the page's head can't find the elements it needs, and the page also appears blank for a moment while it downloads. Explain how script tags block the HTML parser, and how the defer and async attributes and module scripts change that.
What a strong answer covers
- How a plain script tag holds up the HTML parser.
- What each loading attribute changes about downloading and running.
- Which option suits scripts that depend on each other versus ones that stand alone.
- How module scripts behave by default, and the event marking a parsed document.
Common mistake: Using async for scripts that depend on each other, then being surprised when they run in the wrong order.
- Store Data in the Browser
- medium
- Pro
Your app needs to remember a user's theme choice, keep an unsent message draft per tab, and save thousands of offline records. Explain the browser's storage options, which fits each case, and what should never be stored there.
What a strong answer covers
- The browser's main storage options and how long each keeps data.
- Matching each of the three needs to the right store.
- Limits such as data format, size and whether access is blocking.
- What must never be kept in browser storage, and why.
Common mistake: Storing an authentication token in localStorage, where any injected script can read it.
- Prevent Cross-Site Scripting
- hard
- Pro
A comments section builds its HTML by joining strings that include each comment's text, then sets it with innerHTML. A user posts a comment containing a script that steals other visitors' data. Explain how the attack works and how you'd defend against it.
What a strong answer covers
- How untrusted text turns into running code in other people's browsers.
- Rendering user content so it is always treated as text.
- Allowing some formatting safely when it's genuinely needed.
- Extra layers that limit the damage if something slips through.
Common mistake: Trying to block attacks by filtering out the word script, which misses the many other ways to run code.
- Build Infinite Scroll
- hard
- Pro
A feed should load more posts as the user nears the bottom. The current version listens to every scroll event, sometimes loads the same page twice, and gets slower the longer you scroll. Explain how you'd rebuild it.
What a strong answer covers
- A cheaper way to notice that the user is near the end than watching every scroll.
- Making sure each page loads exactly once, and knowing when to stop.
- Keeping a long session from slowing the page down.
- Errors, keyboard and screen-reader users, and returning to the same place.
Common mistake: Fixing duplicate loads with a delay or debounce instead of tracking whether a load is already in progress.
Asynchronous JavaScript
A page loads a user, then that user's orders, then the first order's details. Each step needs the result of the one before. Explain how you'd write this with nested callbacks, with promises, and with async and await, and why the later styles are easier to read and to handle errors in.
What a strong answer covers
- How a sequence of dependent steps looks in each of the three styles.
- Why nesting makes code and error handling harder to follow.
- How promises and async functions let errors be handled in one place.
- What an async function gives back, and whether waiting freezes the page.
Common mistake: Thinking await blocks the whole browser while it waits.
- The Forgotten Await
- easy
- Pro
A function loads a user and checks if they are an admin, but every user is treated as an admin, and logging the result shows a pending promise. Explain what went wrong, and how you'd find bugs like this sooner.
What a strong answer covers
- What an async function actually hands back to its caller.
- Why a condition on that result passes every time.
- How to get at the real value.
- Tooling that catches this class of bug before it ships.
Common mistake: Fixing the one call site but leaving no lint or type check to catch the next one.
- Handle Async Errors
- easy
- Pro
A page fetches data with async and await, and when the network fails the page just stays on a loading spinner while the console shows an unhandled promise rejection. Explain how errors travel through promises, and how you'd handle them so the user sees a helpful message.
What a strong answer covers
- How a failed request surfaces in code that uses await.
- What happens to a failure that nothing handles.
- Making sure the loading state ends however the request turns out.
- Choosing where errors should be caught and what the user sees.
Common mistake: Wrapping every single call in its own try and catch that swallows the error, so failures vanish silently.
- Predict the Event Loop
- medium
- Pro
A script does four things in this order: it logs A; it schedules a timeout with zero delay that logs B; it creates an already-resolved promise whose then callback logs C; and it logs D. Say in what order the letters are printed, and explain why using the call stack, the task queue and the microtask queue.
What a strong answer covers
- The order the four logs appear in.
- Why plain synchronous code always finishes before any callback.
- How promise callbacks and timer callbacks are queued differently.
- Why a zero-millisecond delay doesn't mean 'run immediately'.
Common mistake: Assuming a zero-delay timer runs before a resolved promise's callback because it was scheduled first.
- Check the Fetch Response
- medium
- Pro
An app calls fetch to load a profile. When the server returns a four hundred and four or a five hundred page, the app doesn't show an error: instead it crashes later trying to read the JSON. Explain how fetch reports errors, and how you'd write a safe wrapper.
What a strong answer covers
- Which kinds of failure make fetch reject, and which don't.
- Checking the response before trusting its body.
- Coping with error pages that aren't the format you expected.
- Giving callers one predictable result shape, and stopping requests that hang.
Common mistake: Assuming a catch on fetch will handle a 404 or 500 response.
- Cancel a Stale Request
- medium
- Pro
A search box fetches results as the user types. Sometimes the results shown don't match the text in the box, because an older, slower request finished after a newer one. Explain why this happens and how you'd fix it.
What a strong answer covers
- Why responses can come back in a different order from the requests.
- Stopping an outdated request when a new one begins.
- Ignoring results that no longer match what the user typed.
- Sending fewer requests in the first place.
Common mistake: Showing whichever response arrives last, assuming it must belong to the latest search.
- Write a Debounce
- medium
- Pro
A resize handler recalculates a chart hundreds of times while the user drags the window. Explain how you'd write a debounce function that only runs the work once the user has stopped for a quarter of a second, and how it differs from throttling.
What a strong answer covers
- How the wrapper remembers and resets its timer between calls.
- Passing the right arguments through when the work finally runs.
- How debouncing differs from throttling, and when each suits.
- Refinements such as cancelling on cleanup or firing at the start.
Common mistake: Creating a fresh debounced function on every event, so each one has its own timer and nothing is ever debounced.
- Run Requests in Parallel
- hard
- Pro
A dashboard loads ten independent widgets. The current code awaits each request one after another, so the page takes the sum of all ten response times. Explain how you'd load them in parallel, what should happen when one request fails or hangs, and how you'd avoid overwhelming the server if there were a thousand requests instead of ten.
What a strong answer covers
- Starting independent requests together rather than one after another.
- Choosing between failing fast and collecting every result, error or not.
- Dealing with a request that never answers.
- Keeping a very large batch from flooding the server.
Common mistake: Awaiting each request inside a loop and expecting them to run in parallel.
- Retry with Backoff
- hard
- Pro
A payment status request sometimes fails because the server is briefly overloaded. Explain how you'd write a helper that retries failed requests, which failures it should retry, how long to wait between attempts, and how to avoid making the overload worse.
What a strong answer covers
- Telling temporary failures apart from ones that will never succeed.
- Spacing out attempts, and why some randomness helps.
- Knowing when to give up, and respecting what the server asks for.
- Why a repeated request mustn't cause a repeated payment.
Common mistake: Retrying immediately in a tight loop, which piles more load onto a server that is already struggling.
Questions about practising
- How should I prepare for javascript interview questions?
- Practise answering them out loud, not just reading them. Explaining an answer under follow-up questions is what interviews test. Work through the 36 questions here from easy to hard, and revisit the ones you struggle with.
- Can I practise javascript interview questions with an AI?
- Yes. Open any question and start a voice session: an AI interviewer asks it, follows up on your answer, gives hints when you're stuck and grades your answer with written feedback when the call ends.
- Are these javascript interview questions free?
- 1 of the 36 questions are free to practise. Sign in with Google, no card needed. Pro unlocks the rest, plus practice calls to your phone.