Skip to content

JavaScript Core Interview Questions for Web Development

25 JavaScript Core questions with answers for web development roles — 10 easy, 11 medium, 4 hard.

About JavaScript Core

JavaScript makes websites interactive. This topic covers scope, hoisting, closures, this, prototypes, the event loop, promises and async/await, and everyday array and object operations. Expect output-prediction questions, small coding tasks like debounce, and debugging scenarios about duplicate API calls, floating point and memory leaks.

Sheet progressStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

What is the difference between var, let and const?

Save to ▾
Show answer
var is function-scoped, is hoisted and initialised as undefined, and can be redeclared, which causes bugs in loops and blocks. let and const are block-scoped and sit in the temporal dead zone until their declaration line runs. let allows reassignment, while const does not, although objects declared with const can still have their properties changed. Modern code uses const by default and let only when the value must change.
02

What is hoisting in JavaScript?

Save to ▾
Show answer
Hoisting means declarations are processed before code runs, so they behave as if moved to the top of their scope. Function declarations are hoisted completely and can be called before they appear. var variables are hoisted but set to undefined until assignment. let, const and class are hoisted too, but accessing them before declaration throws a ReferenceError because of the temporal dead zone.
03

What is the difference between == and ===?

Save to ▾
Show answer
== compares values after type coercion, so 0 == '0' and null == undefined are both true, which can hide bugs. === is strict equality and returns true only when both type and value match, so 0 === '0' is false. Most style guides require === everywhere. One accepted exception is value == null, which conveniently checks for both null and undefined in one condition.
04

What are truthy and falsy values?

Save to ▾
Show answer
In a boolean context, JavaScript converts values to true or false. The falsy values are false, 0, -0, 0n, empty string, null, undefined and NaN; everything else is truthy, including '0', empty arrays and empty objects. This matters in conditions: if (items.length) works, but if (count) fails when count is legitimately 0. The nullish coalescing operator ?? helps by only falling back for null or undefined.
05

What is the difference between null and undefined?

Save to ▾
Show answer
undefined means a variable was declared but not assigned, a missing function argument, or a property that does not exist. null is an intentional empty value set by the developer, like clearing a selected user. typeof undefined is 'undefined', while typeof null is 'object', a long-standing quirk. APIs often return null for 'no data', and optional chaining like user?.address handles both safely.
06

What are the spread and rest operators?

Save to ▾
Show answer
Both use three dots but do opposite jobs. Spread expands an iterable or object into individual elements, for example [...a, ...b] to merge arrays or {...user, city: 'Pune'} to copy and update an object. Rest collects multiple values into one, for example function sum(...nums) gathers all arguments into an array, or const { id, ...others } = user separates one property from the rest.
07

Remove duplicates from an array of numbers and from an array of objects.

Save to ▾
Show answer
For primitives, a Set is simplest; for objects, use a Map keyed by id: const nums = [1, 2, 2, 3, 3]; const unique = [...new Set(nums)]; const users = [{ id: 1 }, { id: 2 }, { id: 1 }]; const uniqueUsers = [ ...new Map(users.map(u => [u.id, u])).values() ]; Both are O(n). A Set compares objects by reference, so it cannot remove two different objects with the same id.
08

Use map, filter and reduce to calculate the total price of in-stock items.

Save to ▾
Show answer
Chain the methods so each does one job: const cart = [ { name: 'Mouse', price: 499, qty: 2, inStock: true }, { name: 'Keyboard', price: 1299, qty: 1, inStock: false } ]; const total = cart .filter(item => item.inStock) .map(item => item.price * item.qty) .reduce((sum, value) => sum + value, 0); console.log(total); // 998 Always pass an initial value to reduce so empty arrays return 0 instead of throwing.
09

Your code throws 'Unexpected token < in JSON' after an API call. What does it mean?

Save to ▾
Show answer
It means response.json() received HTML instead of JSON, usually an error page, a login redirect, or a 404 page from the server. I would check the response status and body in the Network tab, verify the endpoint URL and method, and confirm the server sets Content-Type: application/json. In code I would check response.ok before parsing so users see a clear error instead of a crash.
10

How do you learn a new JavaScript concept you do not understand?

Save to ▾
Show answer
I start with MDN for the precise definition, then write tiny experiments in the browser console to see the behaviour myself. If it is still unclear, I watch a short explanation and try to explain it in my own words in notes. For example, I learned the event loop by predicting the output of mixed setTimeout and promise code, checking it, and repeating until my predictions were right.
11

Explain closures with an example.

Save to ▾
Show answer
A closure is a function that remembers variables from the scope where it was created, even after that outer function has finished. For example, function counter() { let count = 0; return () => ++count; } returns a function that keeps its own private count. Closures are used for data privacy, function factories, debounce helpers and event handlers. Their trade-off is that captured variables stay in memory as long as the function exists.
12

How is the value of this decided in JavaScript?

Save to ▾
Show answer
this depends on how a function is called, not where it is written. In a method call like user.greet(), this is user. In a plain function call it is undefined in strict mode. With new it is the new object, and call, apply or bind set it explicitly. Arrow functions do not have their own this; they take it from the surrounding scope, which is why they are handy inside callbacks.
13

What is the difference between Promises and async/await?

Save to ▾
Show answer
A Promise represents a value that will be available later, handled with then and catch chains. async/await is syntax built on promises: an async function always returns a promise, and await pauses that function until the promise settles, making code read top to bottom. Errors are handled with try and catch. For parallel work you still use Promise.all, because awaiting calls one by one runs them sequentially.
14

How do arrow functions differ from regular functions?

Save to ▾
Show answer
Arrow functions have shorter syntax, an implicit return for single expressions, and no own this, arguments or super; they inherit these from the outer scope. They cannot be used as constructors with new and do not have a prototype property. This makes them ideal for callbacks like array.map, but unsuitable for object methods that need this to refer to the object, or for event handlers that rely on this as the element.
15

What is the difference between a shallow copy and a deep copy?

Save to ▾
Show answer
A shallow copy, made with spread syntax or Object.assign, copies only top-level properties, so nested objects are still shared references. Changing copy.address.city also changes the original. A deep copy duplicates every nested level. Modern browsers and Node provide structuredClone(obj), which handles dates, maps and circular references. JSON.parse(JSON.stringify(obj)) also works but drops functions, undefined and converts dates to strings.
16

Write a debounce function and explain where it is used.

Save to ▾
Show answer
Debounce delays a function until calls stop for a given time: function debounce(fn, delay) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => fn.apply(this, args), delay); }; } const onSearch = debounce((e) => fetchResults(e.target.value), 300); input.addEventListener('input', onSearch); It is used for search boxes, window resize and autosave, so the API is called once after the user pauses typing.
17

Fetch data from an API with async/await and handle errors properly.

Save to ▾
Show answer
fetch only rejects on network failure, so check response.ok yourself: async function getCourses() { try { const res = await fetch('/api/courses'); if (!res.ok) throw new Error('HTTP ' + res.status); const data = await res.json(); renderCourses(data); } catch (err) { console.error(err); showMessage('Could not load courses. Please retry.'); } } A 404 or 500 response would otherwise be treated as success.
18

Write a function that groups an array of students by city.

Save to ▾
Show answer
Object.groupBy is available in modern browsers and Node 21+, with reduce as a fallback: const students = [ { name: 'Asha', city: 'Delhi' }, { name: 'Ravi', city: 'Pune' }, { name: 'Neha', city: 'Delhi' } ]; const byCity = Object.groupBy(students, s => s.city); const byCity2 = students.reduce((acc, s) => { (acc[s.city] ||= []).push(s); return acc; }, {}); Both return { Delhi: [...], Pune: [...] }.
19

An API is being called twice when the page loads. How do you debug it?

Save to ▾
Show answer
I would open the Network tab and check the Initiator column to see which code triggered each request. Common causes are the script being included twice, an event listener attached twice, a function called on both DOMContentLoaded and load, or a framework's development mode running effects twice. I would add a breakpoint or console.trace inside the fetch function, fix the root cause, and add a guard flag only if truly needed.
20

A cart total shows 0.30000000000000004 instead of 0.3. Why, and how do you fix it?

Save to ▾
Show answer
JavaScript numbers are IEEE 754 floating point, so decimals like 0.1 and 0.2 cannot be stored exactly. For money, I would store and calculate amounts in the smallest unit, such as paise as integers, and convert only for display using Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }). The server should always recalculate the final amount, because client-side totals cannot be trusted for payment.
21

Describe a bug you found in production and how you handled it.

Save to ▾
Show answer
Situation: after a release, users reported the checkout button did nothing on some phones. Task: I had to find and fix it quickly. Action: I reproduced it on an older Safari, found that a new array method was unsupported, rolled back the change, then added a polyfill and Babel targets for those browsers. Result: the fix shipped the same day, and we added real-device checks to our release checklist.
22

Explain the JavaScript event loop.

Save to ▾
Show answer
JavaScript runs on a single main thread with a call stack. Asynchronous work like timers, network requests and events is handled by browser APIs, and their callbacks are queued. After the stack is empty, the event loop first runs all microtasks, such as promise callbacks and queueMicrotask, then takes the next macrotask, such as a setTimeout callback. That is why a resolved promise logs before a setTimeout of 0.
23

Explain prototypal inheritance in JavaScript.

Save to ▾
Show answer
Every object has an internal link to another object called its prototype. When a property is not found on the object, JavaScript looks up the prototype chain until it reaches Object.prototype and then null. Class syntax is a cleaner layer over this model: class Admin extends User sets Admin.prototype to inherit from User.prototype. Methods defined on the prototype are shared across instances, which saves memory.
24

What are iterators and generators in JavaScript?

Save to ▾
Show answer
An iterator is an object with a next() method returning { value, done }, and any object with a Symbol.iterator method can be used in for...of loops and spread syntax. A generator function, written function*, creates iterators easily: each yield pauses execution and returns a value, resuming on the next call. Generators are useful for lazy sequences, such as paginated API results, without building huge arrays in memory.
25

A dashboard page becomes slower the longer it stays open. What could cause it?

Save to ▾
Show answer
This points to a memory leak. Typical causes are setInterval timers never cleared, event listeners added repeatedly on re-render, detached DOM nodes still referenced in arrays, and growing caches. I would take heap snapshots in the DevTools Memory tab a few minutes apart and compare retained objects. Fixes include clearInterval on cleanup, removeEventListener or AbortController for listeners, and limiting cached data size.

Frequently asked questions

How important is JavaScript Core in Web Development interviews?

JavaScript makes websites interactive. This topic covers scope, hoisting, closures, this, prototypes, the event loop, promises and async/await, and everyday array and object operations. Expect output-prediction questions, small coding tasks like debounce, and debugging scenarios about duplicate API calls, floating point and memory leaks.

How should I use the JavaScript Core sheet?

Go top to bottom — easy to hard. Answer before opening each answer, tick what you solved and save misses to Last-Minute Revision.