HireHireInterview Quizzes › Web Developer

Web Developer Interview Questions

Think you're ready? These are the questions that actually decide Web Developer interviews. Warm up on Easy — then face the Hard round, where 95% of candidates crumble. 80 questions across 3 levels, instant score, completely free.

80Questions
3Difficulty levels
95%Fail the hard round
FreeInstant score
Easy
Warm-up · 20 Qs
Medium
Practical · 30 Qs
Hard
Brutal · 30 Qs
⚡ Take the Web Developer quiz — get your score →

The Web Developer interview questions

Below are the real questions, grouped by difficulty. Expand any one to reveal the correct answer and why — or take the timed quiz for a score you can share. Can you clear the Hard round?

Easy round 20 questions

In JavaScript, what does the expression 0 == '0' evaluate to, and why?
  • A. false, different types
  • B. true, == does type coercion ✓
  • C. true, both are objects
  • D. throws a TypeError
Correct answer: B. == coerces the string '0' to a number before comparing, so it equals 0.
You set width: 200px, padding: 20px, border: 5px on a div with the default box-sizing. What is its rendered width?
  • A. 200px
  • B. 225px
  • C. 245px
  • D. 250px ✓
Correct answer: D. With content-box, total width = 200 + 20*2 padding + 5*2 border = 250px.
Three CSS rules target the same element: an element selector, a class, and an inline style all set color. Which wins?
  • A. The element selector
  • B. The class selector
  • C. The inline style ✓
  • D. Whichever is defined last
Correct answer: C. Inline styles have higher specificity than element or class selectors.
A parent has display: flex and justify-content: center. What does this do to the children?
  • A. Centers them vertically
  • B. Centers them horizontally along the main axis ✓
  • C. Stacks them vertically
  • D. Spreads them to the edges
Correct answer: B. justify-content aligns items along the main (default horizontal) axis, and center groups them in the middle.
A server returns HTTP status 404 for a request. What does the client learn?
  • A. The server had an internal error
  • B. The requested resource was not found ✓
  • C. The request was unauthorized
  • D. The request succeeded
Correct answer: B. 404 means the resource does not exist at that URL; 5xx codes are server errors.
console.log(typeof null) prints what in JavaScript?
  • A. 'null'
  • B. 'object' ✓
  • C. 'undefined'
  • D. 'boolean'
Correct answer: B. typeof null returns 'object', a long-standing quirk in the language.
You want a click on a child button to NOT trigger the parent div's click handler. Which do you call in the child handler?
  • A. event.preventDefault()
  • B. event.stopPropagation() ✓
  • C. return true
  • D. event.reload()
Correct answer: B. stopPropagation halts the event from bubbling up to ancestor handlers.
In CSS, position: absolute on a child positions it relative to what?
  • A. The browser viewport always
  • B. The nearest positioned ancestor ✓
  • C. Its direct parent always
  • D. The document body only
Correct answer: B. An absolutely positioned element is placed relative to its nearest ancestor with a non-static position.
const arr = [1,2,3]; arr.push(4); What is arr.length now?
  • A. 3
  • B. 4 ✓
  • C. 5
  • D. It throws because arr is const
Correct answer: B. push mutates the array (allowed on a const reference), adding one element to make length 4.
Which request method is appropriate for submitting a form that creates a new user record?
  • A. GET
  • B. POST ✓
  • C. HEAD
  • D. OPTIONS
Correct answer: B. POST is used to send data that creates or changes server state; GET is for retrieval.
You use <div> for a page's main navigation instead of <nav>. What is the main downside?
  • A. It renders more slowly
  • B. It loses semantic meaning for accessibility and SEO ✓
  • C. It cannot be styled with CSS
  • D. It breaks in modern browsers
Correct answer: B. Semantic tags like <nav> convey meaning to screen readers and crawlers that a generic <div> does not.
A media query @media (max-width: 600px) applies its styles when?
  • A. The viewport is wider than 600px
  • B. The viewport is 600px or narrower ✓
  • C. Only on printers
  • D. Only at exactly 600px
Correct answer: B. max-width: 600px matches viewports up to and including 600px wide.
let x; console.log(x); What is logged?
  • A. null
  • B. undefined ✓
  • C. 0
  • D. ReferenceError
Correct answer: B. A declared but unassigned variable holds the value undefined.
You store a user's theme choice so it survives a page refresh but does not need to reach the server. Which is most suitable?
  • A. A cookie sent every request
  • B. localStorage ✓
  • C. A JavaScript variable
  • D. The URL query string
Correct answer: B. localStorage persists across refreshes and is client-only, unlike a plain variable that resets.
Two sibling elements have z-index: 1 and z-index: 5 and both are positioned. Which appears on top?
  • A. The z-index: 1 element
  • B. The z-index: 5 element ✓
  • C. Whichever is first in the HTML
  • D. They flicker unpredictably
Correct answer: B. Within the same stacking context, a higher z-index stacks above a lower one.
You add an async keyword to a function. What does calling it always return?
  • A. The raw return value
  • B. A Promise ✓
  • C. undefined
  • D. A callback
Correct answer: B. An async function always wraps its return value in a Promise.
In git, you have uncommitted local edits and run git pull, which needs to merge changes to the same lines. What can happen?
  • A. Your edits are silently deleted
  • B. A merge conflict you must resolve ✓
  • C. The remote branch is overwritten
  • D. Nothing, pull ignores local files
Correct answer: B. Overlapping changes produce a merge conflict that the developer must resolve manually.
CSS: setting margin: 0 auto on a block element with a fixed width does what?
  • A. Removes it from the layout
  • B. Centers it horizontally in its container ✓
  • C. Centers it vertically
  • D. Makes it full width
Correct answer: B. Auto left/right margins split remaining space equally, centering a fixed-width block horizontally.
You reference a variable defined with const before its declaration line runs. What happens?
  • A. It returns undefined
  • B. It throws a ReferenceError (temporal dead zone) ✓
  • C. It returns null
  • D. It hoists the value
Correct answer: B. const is hoisted but stays in the temporal dead zone until declared, so early access throws.
An <img> tag has no alt attribute. Besides accessibility, what else is affected?
  • A. The image will not load
  • B. Nothing is shown if the image fails and SEO loses context ✓
  • C. The page will not validate as HTML5
  • D. The image cannot be styled
Correct answer: B. alt text provides fallback content when the image fails and gives search engines context.

Medium round 30 questions

In CSS, an element has `padding: 20px` and `box-sizing: border-box` with `width: 200px`. What is the total rendered content-box width (ignoring borders)?
  • A. 240px
  • B. 200px
  • C. 160px ✓
  • D. 180px
Correct answer: C. With border-box, the declared 200px includes padding, so content width = 200 - 20 - 20 = 160px.
You want a click handler on a parent `<ul>` to respond to clicks on any of its `<li>` children, including ones added later. Which approach is best?
  • A. Attach a separate listener to each `<li>` on page load
  • B. Use event delegation: one listener on the `<ul>` and check `event.target` ✓
  • C. Poll the DOM every second and rebind listeners
  • D. Use inline `onclick` attributes on each `<li>`
Correct answer: B. Event delegation puts one listener on the parent and inspects event.target, so dynamically added children are handled automatically.
What does the CSS `gap` property control in a flex or grid container?
  • A. The outer margin around the entire container
  • B. The spacing between items (rows/columns) inside the container ✓
  • C. The padding inside each individual item
  • D. The border width of the container
Correct answer: B. `gap` sets the spacing between rows and columns of items within a flex or grid container.
Which HTTP status code should an API return when a request is understood but the client lacks permission to access the resource?
  • A. 401 Unauthorized
  • B. 403 Forbidden ✓
  • C. 404 Not Found
  • D. 500 Internal Server Error
Correct answer: B. 403 means the server understood the request but refuses to authorize it, whereas 401 specifically signals missing/invalid authentication.
In JavaScript, what will `console.log(0.1 + 0.2 === 0.3)` output and why?
  • A. `true`, because arithmetic is exact
  • B. `false`, due to floating-point representation error ✓
  • C. `true`, because JS rounds automatically
  • D. It throws a TypeError
Correct answer: B. IEEE 754 floating-point can't represent 0.1 and 0.2 exactly, so their sum is slightly off from 0.3 and the comparison is false.
You need to make several independent API calls and proceed only after all of them finish. Which is the most appropriate tool?
  • A. `Promise.all()` with an array of the fetch promises ✓
  • B. A `for` loop with `await` inside it
  • C. `Promise.race()`
  • D. `setTimeout()` chained callbacks
Correct answer: A. `Promise.all()` runs the promises concurrently and resolves once all complete, unlike a sequential awaited loop or race which resolves on the first.
In Git, you committed to your local branch but want to combine your last 3 unpushed commits into one before pushing. Which command is designed for this?
  • A. `git merge --squash HEAD~3`
  • B. `git rebase -i HEAD~3` ✓
  • C. `git reset --hard HEAD~3`
  • D. `git cherry-pick HEAD~3`
Correct answer: B. Interactive rebase lets you squash/fixup the last N commits into one; `reset --hard` would discard the changes entirely.
Which CSS media feature is used to apply styles only when the viewport is at most 768px wide?
  • A. `@media (min-width: 768px)`
  • B. `@media (max-width: 768px)` ✓
  • C. `@media screen and (width: 768px)`
  • D. `@media (device-width: 768px)`
Correct answer: B. `max-width: 768px` matches viewports up to and including 768px, the standard mobile-first breakpoint pattern.
A user reports your fetch call fails in the browser console with a CORS error. Where must the fix generally be applied?
  • A. Add a `<meta>` CORS tag in the HTML head
  • B. Set the appropriate `Access-Control-Allow-Origin` header on the server response ✓
  • C. Wrap the fetch in a try/catch block
  • D. Change the request from GET to POST
Correct answer: B. CORS is enforced by the browser based on server-sent response headers, so the server must send an allowing `Access-Control-Allow-Origin` header.
In React, what is the primary purpose of the `key` prop when rendering a list with `.map()`?
  • A. To style each list item uniquely
  • B. To help React identify which items changed, added, or removed for efficient reconciliation ✓
  • C. To store the item's data in local state
  • D. To set a unique HTML `id` attribute on each element
Correct answer: B. Keys give elements stable identity so React can reconcile the list efficiently and avoid re-rendering or misplacing items.
Given `console.log(typeof null)` in JavaScript, what is printed?
  • A. "null"
  • B. "object" ✓
  • C. "undefined"
  • D. "boolean"
Correct answer: B. Due to a longstanding language quirk, typeof null evaluates to the string "object".
Which CSS unit is relative to the root element's font size rather than the parent's?
  • A. em
  • B. rem ✓
  • C. %
  • D. px
Correct answer: B. rem is calculated relative to the root (html) element's font size, while em is relative to the parent.
In the CSS box model, what does `box-sizing: border-box` change?
  • A. Padding and border are included within the element's set width ✓
  • B. Margins collapse automatically
  • C. The element becomes a flex container
  • D. Width is measured from the margin edge
Correct answer: A. With border-box, the declared width includes padding and border, so the content box shrinks to accommodate them.
What is the output of `[1,2,3].map(x => x * 2)`?
  • A. [1,2,3]
  • B. [2,4,6] ✓
  • C. 6
  • D. [1,4,9]
Correct answer: B. map returns a new array applying the function to each element, doubling each to produce [2,4,6].
A CORS error appears when the browser calls an API on another origin. Where must the fix be applied?
  • A. In the browser's JavaScript fetch options only
  • B. On the server, by sending appropriate Access-Control-Allow-Origin headers ✓
  • C. By disabling HTTPS
  • D. In the HTML <meta> tag
Correct answer: B. CORS is enforced by the browser but authorized by the server, which must return the correct Access-Control-Allow-* headers.
In JavaScript, why can `const arr = [1,2]; arr.push(3);` succeed even though arr is const?
  • A. push bypasses const
  • B. const prevents reassignment of the binding, not mutation of the object it references ✓
  • C. Arrays are always mutable regardless of const
  • D. This actually throws an error
Correct answer: B. const only forbids rebinding the variable; the referenced array object itself can still be mutated.
Which approach best prevents stored XSS when displaying user-submitted comments?
  • A. Using HTTPS
  • B. Escaping/encoding output and avoiding innerHTML with raw input ✓
  • C. Minifying the JavaScript
  • D. Setting a long cache header
Correct answer: B. Encoding user content on output (or using textContent instead of innerHTML) neutralizes injected markup that causes XSS.
What does the CSS property `position: sticky` do?
  • A. Fixes an element to the viewport permanently
  • B. Removes the element from document flow entirely
  • C. Acts as relative until a scroll threshold, then sticks like fixed within its container ✓
  • D. Centers the element automatically
Correct answer: C. A sticky element scrolls normally until it reaches a specified offset, then sticks in place within its containing block.
In an async function, what does `await fetch(url)` resolve to?
  • A. The parsed JSON body
  • B. A Response object whose body must still be read (e.g., .json()) ✓
  • C. A string of the HTML
  • D. The HTTP status code only
Correct answer: B. fetch resolves to a Response object; you must call .json() or .text() to read and parse the body stream.
Which HTTP header, when set by the server, tells the browser to only connect over HTTPS for a period of time?
  • A. Content-Security-Policy
  • B. Strict-Transport-Security ✓
  • C. X-Frame-Options
  • D. Referrer-Policy
Correct answer: B. Strict-Transport-Security (HSTS) instructs browsers to use HTTPS exclusively for the specified max-age.
In JavaScript, what will 'console.log(typeof null)' output, reflecting a well-known language quirk?
  • A. 'null'
  • B. 'object' ✓
  • C. 'undefined'
  • D. 'number'
Correct answer: B. Due to a long-standing bug in JavaScript, typeof null returns 'object' rather than 'null'.
Which CSS layout method is best suited for building a one-dimensional row or column of items with flexible spacing?
  • A. CSS Grid
  • B. Flexbox ✓
  • C. Float
  • D. Table layout
Correct answer: B. Flexbox is designed for one-dimensional layouts (a single row or column), while Grid handles two dimensions.
What does the 'defer' attribute on a <script> tag do?
  • A. Downloads the script but executes it only after HTML parsing completes, in order ✓
  • B. Blocks HTML parsing until the script runs
  • C. Prevents the script from loading
  • D. Executes the script before the DOM exists
Correct answer: A. defer downloads scripts in parallel but runs them in order after the document is fully parsed.
In a Promise chain, where should you place logic that must run whether the promise resolves or rejects?
  • A. .then()
  • B. .catch()
  • C. .finally() ✓
  • D. .resolve()
Correct answer: C. .finally() runs regardless of whether the promise was fulfilled or rejected, ideal for cleanup.
Which HTTP status code indicates the requested resource was not found on the server?
  • A. 301
  • B. 403
  • C. 404 ✓
  • D. 500
Correct answer: C. 404 Not Found means the server could not locate the requested resource.
In CSS specificity, which selector wins when styling the same element: an inline style, an id selector, and a class selector?
  • A. The class selector
  • B. The id selector
  • C. The inline style ✓
  • D. They are combined equally
Correct answer: C. Inline styles have the highest specificity, beating id and class selectors (barring !important).
What is the result of the JavaScript expression '0.1 + 0.2 === 0.3'?
  • A. true
  • B. false ✓
  • C. It throws an error
  • D. undefined
Correct answer: B. Floating-point representation makes 0.1 + 0.2 equal 0.30000000000000004, so the strict comparison is false.
Which technique prevents Cross-Site Scripting (XSS) when inserting user-provided text into the DOM?
  • A. Using innerHTML directly
  • B. Escaping/encoding output or using textContent ✓
  • C. Disabling JavaScript
  • D. Using a longer variable name
Correct answer: B. Encoding output or assigning via textContent prevents malicious markup from being interpreted as executable HTML.
In the CSS flexbox model, what does 'justify-content: space-between' do to items in a row?
  • A. Centers all items with equal margins
  • B. Places first and last items at the edges with equal space between the rest ✓
  • C. Stacks items vertically
  • D. Gives every item identical width
Correct answer: B. space-between pins the first and last items to the container edges and distributes remaining space evenly between others.
Why is 'event delegation' used when handling clicks on many dynamically added list items?
  • A. It attaches a listener to each item individually
  • B. It attaches one listener to a parent and uses event bubbling to handle child clicks ✓
  • C. It disables event bubbling
  • D. It requires inline onclick attributes
Correct answer: B. Event delegation attaches a single listener to a parent and leverages bubbling, handling current and future children efficiently.

Hard round 30 questions

What does this log, in order? console.log('A'); setTimeout(() => console.log('B'), 0); Promise.resolve().then(() => { console.log('C'); setTimeout(() => console.log('D'), 0); }); queueMicrotask(() => console.log('E')); console.log('F');
  • A. A F C E B D ✓
  • B. A F C E D B
  • C. A C E F B D
  • D. A F E C B D
Correct answer: A. Sync runs first (A,F), then the microtask queue drains fully (C then E, since C was queued before E), and only then macrotasks in FIFO order (B, then D which was queued during the first microtask).
A senior sees this render slow. The list has 5,000 rows and a colleague immediately wraps every row in React.memo and adds useMemo everywhere. What is the correct first objection? function Row({ item }) { return <li>{item.label}</li>; } function List({ items }) { return <ul>{items.map(i => <Row key={i.id} item={i} />)}</ul>; }
  • A. React.memo will not help because Row has no props
  • B. Without profiling you don't know memo is the bottleneck; rendering 5,000 DOM nodes at once likely needs virtualization, not memoization ✓
  • C. useMemo on the map result fixes it since map allocates a new array each render
  • D. memo is useless in React 18 because the compiler auto-memoizes
Correct answer: B. The red flag is optimizing before measuring; a 5,000-node list is a DOM/layout cost that memoization can't fix, and the Profiler would point to virtualization instead.
This effect logs a stale count. Why, and what is the minimal correct fix? function Counter() { const [count, setCount] = useState(0); useEffect(() => { const id = setInterval(() => console.log(count), 1000); return () => clearInterval(id); }, []); return <button onClick={() => setCount(count + 1)}>{count}</button>; }
  • A. The interval closure captured count=0 from the first render; use a ref (or functional read) so the interval reads the latest value ✓
  • B. setInterval is unreliable in React; switch to setTimeout recursion
  • C. Add count to the dependency array is the only acceptable fix and has no downside
  • D. State updates are async so count is always one behind; add a useLayoutEffect
Correct answer: A. The empty-dep effect runs once and its closure permanently captures count=0; reading through a ref (updated each render) or adding count to deps both fix it, but only the ref avoids tearing down the interval every tick.
A CORS request from https://app.example.com sends cookies via fetch(url, { credentials: 'include' }). The server responds with Access-Control-Allow-Origin: * and Access-Control-Allow-Credentials: true. What happens?
  • A. It works; * matches every origin including the credentialed one
  • B. The browser blocks it: with credentials, the ACAO header must echo the specific origin, not the wildcard * ✓
  • C. It works only if SameSite=None is also set on the cookie
  • D. The preflight succeeds but the cookie is silently stripped from the actual request
Correct answer: B. The Fetch spec forbids the wildcard when credentials are included; the server must reflect the exact origin (and the browser rejects the response otherwise).
Predict the output: const obj = { val: 42, regular() { return (function () { return this?.val; })(); }, arrow() { return (() => this.val)(); } }; console.log(obj.regular(), obj.arrow());
  • A. 42 42
  • B. undefined 42 ✓
  • C. 42 undefined
  • D. undefined undefined
Correct answer: B. The inner regular function is called plain so its `this` is undefined (strict) giving undefined via optional chaining, while the arrow captures the method's `this` (obj) yielding 42.
Why did React's Fiber architecture replace the old stack reconciler? Pick the most fundamental reason.
  • A. Fiber uses less memory by reusing a single tree
  • B. Reconciliation was synchronous and uninterruptible; Fiber makes work a linked list of units that can be paused, prioritized, and resumed so high-priority updates aren't blocked ✓
  • C. Fiber removed the virtual DOM entirely in favor of direct DOM diffing
  • D. Fiber enables server components by moving rendering to the server
Correct answer: B. The stack reconciler recursed synchronously and couldn't be interrupted; Fiber restructures work into resumable units enabling priority scheduling and time-slicing.
A form input feels janky while filtering a huge list on each keystroke. You want the input to stay responsive and the list to update at lower priority without debouncing. Which is the idiomatic React 18 tool, and what's the caveat?
  • A. useMemo on the filtered list — it will skip recomputation
  • B. useDeferredValue on the filter text — the list renders with a lagging value, but the underlying filtering work must still be cheap enough or you also need virtualization ✓
  • C. useCallback on the onChange handler to prevent re-renders
  • D. useLayoutEffect to batch the updates synchronously
Correct answer: B. useDeferredValue lets the input update urgently while the list re-renders from a deferred value at lower priority, but it only reprioritizes—it doesn't make an expensive render cheap.
Storing a JWT in localStorage vs an httpOnly SameSite=Strict cookie: which statement is the accurate trade-off?
  • A. localStorage is safe because JS on your own origin is trusted
  • B. httpOnly cookies are immune to CSRF so no other defense is needed
  • C. localStorage is readable by any XSS-injected script (token exfiltration), while an httpOnly cookie is not JS-readable but reintroduces CSRF risk that SameSite/anti-CSRF tokens must address ✓
  • D. Both are equivalent since HTTPS encrypts the token in transit
Correct answer: C. localStorage tokens are exposed to XSS; httpOnly cookies block that read but are auto-sent by the browser, so CSRF protections become necessary.
Passing a value through React Context, this consumer re-renders on every provider render even when `user` is unchanged. What's the root cause? <AuthContext.Provider value={{ user, login, logout }}>
  • A. Context always re-renders all consumers regardless of value
  • B. The value object literal is a new reference each render, so all consumers re-render; memoize it with useMemo ✓
  • C. useContext doesn't support object values
  • D. You must wrap consumers in React.memo — context bypasses memo, so it can't be fixed
Correct answer: B. Context compares the value by reference; a fresh object literal each render invalidates all consumers, so the provider value should be memoized (splitting stable vs volatile values also helps).
Two rapid searches: request A (for 're') is slow, request B (for 'react') is fast and arrives first. Without care the UI shows A's results last. Which is the robust fix for this out-of-order async race?
  • A. Add a loading spinner so the user waits
  • B. Debounce the input to 300ms — this guarantees ordering
  • C. Track the latest request (e.g. an AbortController to cancel A, or an ignore flag / request id) so stale responses are discarded ✓
  • D. Wrap both in Promise.all so they resolve together
Correct answer: C. Cancelling superseded requests or tagging responses with a request id and dropping any that aren't the latest prevents a slow earlier response from clobbering fresh data; debouncing reduces but doesn't eliminate the race.
Given `for (var i=0;i<3;i++){ setTimeout(()=>console.log(i),0); }`, what is logged?
  • A. 0 1 2
  • B. 3 3 3 ✓
  • C. 0 0 0
  • D. undefined three times
Correct answer: B. var is function-scoped, so all three closures share one i, which is 3 by the time the timeouts run; let would print 0 1 2.
In the browser event loop, which queue is drained completely before the next task (macrotask) runs?
  • A. The animation frame queue
  • B. The microtask queue (e.g., resolved Promises) ✓
  • C. The render queue
  • D. The timer queue
Correct answer: B. After each macrotask, the engine fully drains the microtask queue (Promise callbacks, queueMicrotask) before the next macrotask.
What does `console.log(0.1 + 0.2 === 0.3)` output and why?
  • A. true, exact arithmetic
  • B. false, due to IEEE-754 floating-point representation ✓
  • C. true, JS rounds automatically
  • D. throws a TypeError
Correct answer: B. 0.1 and 0.2 cannot be represented exactly in binary floating point, so their sum is slightly more than 0.3, making the comparison false.
A large layout thrash happens when JS repeatedly reads offsetHeight then writes styles in a loop. The core cause is:
  • A. Garbage collection pauses
  • B. Forced synchronous reflow because reads flush pending style/layout writes ✓
  • C. Too many DOM nodes only
  • D. Slow network requests
Correct answer: B. Interleaving layout reads and writes forces the browser to recompute layout synchronously each iteration; batching reads then writes avoids the thrash.
Which statement about CSS specificity is correct for `#nav .item a:hover`?
  • A. Its specificity is (0,1,1,1)
  • B. Its specificity is (0,1,2,1) ✓
  • C. Inline styles always lose to it
  • D. !important lowers its specificity
Correct answer: B. One id (1), two of class/pseudo-class (.item and :hover), and one element (a) give specificity 0,1,2,1.
In HTTP/2, what problem from HTTP/1.1 does multiplexing primarily solve?
  • A. TLS handshake latency
  • B. Head-of-line blocking at the application layer by allowing concurrent streams over one connection ✓
  • C. DNS resolution time
  • D. Cookie size limits
Correct answer: B. HTTP/2 multiplexes many streams over a single connection, removing the HTTP/1.1 head-of-line blocking where responses had to return in order per connection.
A JWT stored in localStorage is criticized as less secure than an HttpOnly cookie mainly because:
  • A. It cannot be signed
  • B. It is readable by JavaScript, so an XSS flaw can exfiltrate it ✓
  • C. It expires immediately
  • D. It cannot be sent to the server
Correct answer: B. localStorage is accessible to any JS on the page, so an XSS vulnerability can steal the token, whereas HttpOnly cookies are shielded from script access.
Which describes the difference between debouncing and throttling an event handler?
  • A. They are identical techniques
  • B. Debounce fires once after activity stops; throttle fires at most once per interval during activity ✓
  • C. Throttle fires only after activity stops; debounce fires continuously
  • D. Both fire on every event
Correct answer: B. Debounce delays execution until events stop for a quiet period; throttle guarantees the handler runs at a fixed maximum rate while events continue.
In React, why can updating state inside render cause an infinite loop, while updating it in useEffect with a proper dependency array does not?
  • A. useEffect never re-runs
  • B. render must be pure and side-effect-free; each render setting state schedules another render, whereas useEffect runs after commit and gates on dependencies ✓
  • C. State updates in render are ignored
  • D. React batches render but not effects
Correct answer: B. Rendering should be pure; calling setState during render triggers an immediate re-render loop, while useEffect runs post-commit and only re-runs when its dependencies change.
The CSS `z-index` on a positioned element seems ignored because a parent creates a stacking context. Which property does NOT create a new stacking context?
  • A. opacity less than 1
  • B. transform other than none
  • C. position: static with no other triggers ✓
  • D. will-change: transform
Correct answer: C. position: static (with no opacity/transform/filter/etc.) does not establish a stacking context; the other properties each create one, trapping child z-index values.
In JavaScript, what does the following log: for(var i=0;i<3;i++){ setTimeout(()=>console.log(i),0) }?
  • A. 0 1 2
  • B. 3 3 3 ✓
  • C. 0 0 0
  • D. undefined undefined undefined
Correct answer: B. var is function-scoped so all callbacks share one i, which is 3 after the loop finishes before the timeouts fire.
A page's Largest Contentful Paint is poor because a large hero image loads late. Which HTML hint most directly prioritizes its fetch?
  • A. loading="lazy" on the image
  • B. <link rel="preload" as="image"> for the hero ✓
  • C. defer on all scripts
  • D. display:none until loaded
Correct answer: B. Preloading the LCP image tells the browser to fetch it with high priority early, improving LCP.
What is the primary reason CORS blocks a browser fetch to a different origin even though the server received the request?
  • A. The server was offline
  • B. The response lacked the required Access-Control-Allow-Origin header for that origin ✓
  • C. The URL used HTTPS
  • D. The request used GET
Correct answer: B. CORS is enforced by the browser; without a matching Access-Control-Allow-Origin header the response is blocked from JavaScript.
In the browser event loop, which queue is drained to completion BEFORE the next macrotask (e.g., setTimeout) runs?
  • A. The render queue
  • B. The microtask queue (Promises) ✓
  • C. The animation queue
  • D. The idle callback queue
Correct answer: B. After each macrotask the engine fully drains the microtask queue (Promise callbacks) before the next macrotask.
Why can two visually identical CSS rules with 'position: sticky' behave differently, where one never sticks?
  • A. sticky requires JavaScript
  • B. The sticky element's nearest scrolling ancestor has overflow:hidden/auto that clips or lacks scroll range ✓
  • C. sticky only works on <table>
  • D. sticky needs a fixed pixel height
Correct answer: B. position:sticky depends on a scrollable ancestor; if an ancestor sets overflow that removes the scroll context, sticking fails.
What security benefit does the 'SameSite=Strict' cookie attribute provide?
  • A. Encrypts the cookie value
  • B. Prevents the cookie from being sent on cross-site requests, mitigating CSRF ✓
  • C. Compresses the cookie
  • D. Makes the cookie readable by JavaScript
Correct answer: B. SameSite=Strict stops the browser from attaching the cookie to cross-site requests, defending against CSRF.
In React, why can calling a state setter inside render without a condition cause an infinite loop?
  • A. setState is asynchronous only in events
  • B. Each set triggers a re-render, which calls the setter again, repeating endlessly ✓
  • C. React caches renders forever
  • D. It mutates the virtual DOM directly
Correct answer: B. An unconditional setState during render schedules another render that runs the same setter, creating an infinite render loop.
A CSS animation on 'top'/'left' stutters while the same motion on 'transform: translate' is smooth. Why?
  • A. transform triggers layout on every frame
  • B. top/left trigger layout and paint each frame; transform is composited on the GPU ✓
  • C. translate uses fewer pixels
  • D. top/left are deprecated
Correct answer: B. Animating top/left forces layout+paint per frame, whereas transform runs on the compositor/GPU without reflow, staying smooth.
When does the JavaScript 'this' inside a regular function called as a plain function (not a method) refer to in strict mode?
  • A. The global object
  • B. undefined ✓
  • C. The calling function
  • D. The nearest object literal
Correct answer: B. In strict mode a plain function call binds this to undefined rather than the global object.
Why might a service worker serve stale content even after you deploy a new version of the site?
  • A. Service workers ignore new deploys forever
  • B. The cached assets are served from the cache-first strategy until the worker updates and activates ✓
  • C. HTTPS blocks updates
  • D. The browser deleted the manifest
Correct answer: B. A cache-first service worker keeps serving cached assets until a new worker is fetched, installed, and activated.

Prep for another role

Questions are original, written and independently verified for HireHire's role interview quizzes. They reflect the kind of knowledge Web Developer interviews test, not any specific company's questions. HireHire maps live tech & IT jobs across India, updated regularly. Last updated: August 2026.