Skip to content
Home/Resources/Software Development/JavaScript interview questions
Interview prep ยท Software Development

JavaScript Interview Questions and Answers for Freshers: 34 Model Answers With Tested Code

Younus FardeenBy Younus FardeenUpdated 1 Dec 202614 min read
Short answer

JavaScript interviews test data types and equality, hoisting and scope, closures, the this keyword, prototypes and classes, the event loop, promises and async/await, and everyday ES6 features. These 34 answers are short, and every snippet was run with Node 24.15.0 so the output quoted is real, including the exact order of the event loop example.

On this pageTypes, equality and coercion (Q1 to Q7)Scope, hoisting and closures (Q8 to Q15)`this`, prototypes and classes (Q16 to Q22)Event loop, promises and async/await (Q23 to Q30)Everyday ES6, arrays and coding tasks (Q31 to Q34)Revision planFrequently asked questions

For students and freshers preparing for frontend, full-stack and Node roles, where JavaScript fundamentals are asked before any framework. Every JavaScript block below was executed with node (v24.15.0) on 1 December 2026, and the output quoted is what it printed. Language behaviour is described as the MDN Web Docs and the ECMAScript specification define it. Output of code that touches the browser, such as the DOM, was not run here.

Trends India shows interview-question searches for Java, Python, SQL, React and Node peaking from January to March, and those pages rank among the hub's recurring winners. The Search Console export of 26 November 2026 has no direct row for this page, so the "most asked" picks below are our reading, not data. Once these basics are solid, go on to React interview questions and Node.js interview questions.

Types, equality and coercion (Q1 to Q7)

  • Q1. What are the data types in JavaScript? Seven primitives: string, number, bigint, boolean, null, symbol and the type of a variable that has no value yet (the first word printed in the output below). Everything else is an object, including arrays, functions and dates. Primitives are immutable and compared by value, objects by reference.
  • Q2. Why is typeof null an object? It is a long-standing bug in the language that was never fixed to avoid breaking existing code. Test for null with value === null. The snippet shows typeof null as object and typeof [] as object too, so use Array.isArray for arrays.
  • Q3. == versus ===? === compares without converting types. == converts first, so 1 == "1" is true while 1 === "1" is false. null == void 0 is true while null === void 0 is false, where void 0 is the "no value yet" value. Use === by default.
  • Q4. Why is 0.1 + 0.2 not 0.3? Numbers are 64-bit binary floating point, and 0.1 and 0.2 cannot be stored exactly, so the sum is 0.30000000000000004. Compare with a tolerance such as Number.EPSILON, or work in integers (paise, not rupees).
  • Q5. What are truthy and falsy values? Falsy values are false, 0, -0, 0n, "", null, void 0 (the "no value yet" value) and NaN. Everything else is truthy, including "0", [] and {}, a classic trap shown in the output.
  • Q6. How do I check for NaN? NaN === NaN is false. Use Number.isNaN(x) or Object.is(x, NaN). The global isNaN coerces first and gives surprising results.
  • Q7. What does [] + {} give? The string "[object Object]", because both operands are converted to strings. "5" + 2 is "52" (string join) but "5" - 2 is 3 (number). The plus operator prefers strings, minus always uses numbers.
console.log(typeof undeclared, typeof null, typeof [], typeof (() => 1), typeof 10n);
console.log(0.1 + 0.2, 0.1 + 0.2 === 0.3, Math.abs(0.3 - (0.1 + 0.2)) < Number.EPSILON);
console.log(1 == "1", 1 === "1", null == undefined, null === undefined, NaN === NaN, Object.is(NaN, NaN));
console.log([] + [], [] + {}, "5" - 2, "5" + 2, +"", +"abc");
console.log(Boolean(""), Boolean("0"), Boolean([]), Boolean(0), Boolean(null));

Output:

undefined object object function bigint
0.30000000000000004 false true
true false true false false true
 [object Object] 3 52 0 NaN
false true true false false

Scope, hoisting and closures (Q8 to Q15)

  • Q8. var, let and const: what is the difference? var is function-scoped and can be redeclared. let and const are block-scoped, and const cannot be reassigned, though the object it holds can still be changed. Prefer const, use let when you must reassign and avoid var.
  • Q9. What is hoisting? Declarations are processed before code runs. Function declarations are hoisted with their body, so you can call them early. var is hoisted and starts with the "no value yet" value. let and const are hoisted but stay unusable until their line, the temporal dead zone.
  • Q10. What does the hoisting snippet show? typeof hoistedVar printed the "no value yet" type name and the function runs before its definition. Reading letValue early throws ReferenceError. A function stored in a var has no value until its line runs, so calling it early throws TypeError.
console.log(typeof hoistedVar, hoistedFn());
var hoistedVar = 1;
function hoistedFn() { return "function hoisted"; }
try { console.log(letValue); } catch (e) { console.log(e.name + ": " + e.message); }
let letValue = 2;
try { console.log(typeof arrowFn); arrowFn(); } catch (e) { console.log(e.name + ": " + e.message); }
var arrowFn = () => 1;

Output:

undefined function hoisted
ReferenceError: Cannot access 'letValue' before initialization
undefined
TypeError: arrowFn is not a function
  • Q11. What is a closure? A function that remembers the variables of the scope where it was created, even after that scope has returned. In the snippet, counter() returns functions that share a private n, and nothing outside can touch it. Closures give private state, callbacks and function factories. See the MDN closures guide.
  • Q12. Why does a var loop with closures print 3, 3, 3? All three callbacks share the one function-scoped i, which is 3 when they run. With let, each iteration gets its own j, so the output is 0, 1, 2. This is the most asked closure question.
  • Q13. What is lexical scope? A function's variables are decided by where it is written, not where it is called. Inner functions can read outer variables, never the reverse.
  • Q14. What is an IIFE and why is it used? An immediately invoked function expression, (function () { ... })(). It created a private scope before modules and let existed. Today, ES modules and block scope cover most of the need.
  • Q15. What are currying and memoization? Currying turns f(a, b) into f(a)(b). Memoization caches results by arguments. The utility snippet later memoizes a square function and shows it computed 2 times for 3 calls.
function counter() {
  let n = 0;
  return { inc: () => ++n, get: () => n };
}
const c = counter();
c.inc(); c.inc();
console.log(c.get());
var fs = [];
for (var i = 0; i < 3; i++) fs.push(() => i);
console.log(fs.map(f => f()));
var gs = [];
for (let j = 0; j < 3; j++) gs.push(() => j);
console.log(gs.map(f => f()));

Output:

2
[ 3, 3, 3 ]
[ 0, 1, 2 ]

`this`, prototypes and classes (Q16 to Q22)

  • Q16. How is this decided? By how the function is called. As a method (obj.fn()), this is obj. With new, it is the new object. With call, apply or bind, it is what you pass. A plain call gives no this at all in strict mode or the global object in sloppy mode. Arrow functions have no this of their own and use the enclosing one. See MDN on this.
  • Q17. Why does a detached method lose this? Copying const lost = user.regular and calling lost() is a plain call, so this is no longer user, and the snippet printed the "no value yet" value. Fix it with bind, an arrow wrapper or by calling user.regular().
  • Q18. call, apply and bind: what is the difference? call(thisArg, a, b) and apply(thisArg, [a, b]) invoke the function now. bind(thisArg) returns a new function with this fixed. The snippet printed Ravi and Meera using bind and call.
  • Q19. When should I not use an arrow function? For object methods that need their own this (the arrow method printed the module's this, an object in a Node CommonJS file, not user), for constructors (arrows cannot be used with new) and when you need arguments.
const user = {
  name: "Asha",
  regular() { return this && this.name; },
  arrow: () => typeof this,
  delayed() { return [1].map(() => this.name)[0]; },
};
console.log(user.regular(), user.arrow(), user.delayed());
const lost = user.regular;
console.log(lost());
const bound = user.regular.bind({ name: "Ravi" });
console.log(bound(), user.regular.call({ name: "Meera" }));
function Person(n) { this.n = n; }
console.log(new Person("Kabir").n);

Output (lost() printed the "no value yet" value because a plain call in sloppy mode makes this the global object, which has no name):

Asha object Asha
undefined
Ravi Meera
Kabir
  • Q20. What is the prototype chain? Every object has an internal link to a prototype, and property lookup walks up that chain until it finds the name or reaches null. That is how a.speak() works in the snippet below: speak lives on Animal.prototype, not on a.
  • Q21. Are ES6 classes real classes? They are syntax over prototypes. class Cat extends Animal sets up the same prototype chain, and super.speak() calls the parent method. The output shows Tom makes a sound (meow).
  • Q22. Shallow copy versus deep copy? Spread ({...obj}) copies one level, so nested objects are still shared. After changing original.nested.b to 99, the shallow copy showed 99 and the structuredClone copy showed 2. JSON.parse(JSON.stringify(x)) also deep copies but drops functions, missing values and dates as dates.
function Animal(name) { this.name = name; }
Animal.prototype.speak = function () { return this.name + " makes a sound"; };
const a = new Animal("Dog");
console.log(a.speak(), Object.getPrototypeOf(a) === Animal.prototype);
class Cat extends Animal { speak() { return super.speak() + " (meow)"; } }
console.log(new Cat("Tom").speak());
const original = { a: 1, nested: { b: 2 } };
const shallow = { ...original }, deep = structuredClone(original);
original.nested.b = 99;
console.log(shallow.nested.b, deep.nested.b);
const arr = [1, 2, 3, 4];
console.log(arr.map(x => x * 2), arr.filter(x => x % 2), arr.reduce((s, x) => s + x, 0));
const { name = "none", ...rest } = { x: 1, y: 2 };
console.log(name, rest, [..."hi"]);
console.log(null ?? "d", 0 ?? "d", 0 || "d", undefined?.x);
console.log(Object.freeze([1]).concat(2), [10, 9, 1].sort(), [10, 9, 1].sort((x, y) => x - y));

Output:

Dog makes a sound true
Tom makes a sound (meow)
99 2
[ 2, 4, 6, 8 ] [ 1, 3 ] 10
none { x: 1, y: 2 } [ 'h', 'i' ]
d 0 d undefined
[ 1, 2 ] [ 1, 10, 9 ] [ 1, 9, 10 ]

Event loop, promises and async/await (Q23 to Q30)

  • Q23. Is JavaScript single-threaded? How does it handle async work? The language runs your code on one thread with one call stack. Timers, network and file work happen outside it in the browser or in Node, and finished callbacks are queued back. The event loop runs the next queued task only when the stack is empty. See the MDN event loop page.
  • Q24. What is the order: sync code, microtasks, timers? All synchronous code first, then every queued microtask (promise callbacks, queueMicrotask, code after await), then the next macrotask such as setTimeout. In the snippet, the setTimeout(..., 0) callback ran last, after the promise callbacks.
console.log("1 sync start");
setTimeout(() => console.log("5 timeout 0"), 0);
Promise.resolve().then(() => console.log("3 promise microtask"));
queueMicrotask(() => console.log("4 queueMicrotask"));
(async () => { console.log("2 inside async, before await"); await null; console.log("4b after await"); })();
console.log("2b sync end");

Output (the labels show the order you should predict):

1 sync start
2 inside async, before await
2b sync end
3 promise microtask
4 queueMicrotask
4b after await
5 timeout 0
  • Q25. What is a promise, and what are its states? An object for a value that arrives later. It is pending, then either fulfilled with a value or rejected with an error, and never changes again. then and catch register callbacks, and chaining returns new promises. Details are on MDN Promise.
  • Q26. Promise.all, allSettled, race and any? all waits for every promise and rejects on the first failure. allSettled waits for all and reports each status. race settles with the first to settle, success or failure. any fulfills with the first success. The snippet printed ['ok','slow'], ['fulfilled','rejected'], a rejected race and ok for any.
  • Q27. How does async/await relate to promises? An async function always returns a promise, and await pauses that function (not the thread) until a promise settles. Errors become try/catch. It is syntax over promises.
  • Q28. Why can sequential await be slow? Awaiting one call after another adds the delays, while Promise.all starts them together. In the snippet, two 30 ms waits took longer one after the other than together, and the check printed true. Use sequential await only when one call needs the previous result.
  • Q29. What is callback hell, and how do I avoid it? Deeply nested callbacks that are hard to read and handle errors in. Promises and async/await flatten them into straight-line code.
  • Q30. What happens to an unhandled rejection? In Node a promise rejection that nothing handles ends the process by default in current versions, and browsers log an error. Always end chains with catch or wrap await in try/catch.
const after = (ms, value, fail) => new Promise((res, rej) =>
  setTimeout(() => (fail ? rej(new Error(value)) : res(value)), ms));
(async () => {
  console.log(await Promise.all([after(20, "ok"), after(30, "slow")]));
  const settled = await Promise.allSettled([after(20, "ok"), after(10, "boom", true)]);
  console.log(settled.map(r => r.status));
  console.log(await Promise.race([after(20, "ok"), after(10, "boom", true)]).catch(e => "race rejected: " + e.message));
  console.log(await Promise.any([after(10, "boom", true), after(20, "ok")]));
  try { await Promise.all([after(20, "ok"), after(10, "boom", true)]); } catch (e) { console.log("all rejected:", e.message); }
  let t0 = Date.now();
  await after(30, "a"); await after(30, "b");
  const seq = Date.now() - t0;
  t0 = Date.now();
  await Promise.all([after(30, "a"), after(30, "b")]);
  console.log("parallel faster than sequential:", Date.now() - t0 < seq);
})();

Output:

[ 'ok', 'slow' ]
[ 'fulfilled', 'rejected' ]
race rejected: boom
ok
all rejected: boom
parallel faster than sequential: true

Everyday ES6, arrays and coding tasks (Q31 to Q34)

  • Q31. Which ES6 and later features are asked most? Arrow functions, let and const, template literals, destructuring, spread and rest, default parameters, modules, classes, optional chaining (?.) and nullish coalescing (??). The utility and prototype snippets use several. Note 0 ?? "d" is 0 while 0 || "d" is "d".
  • Q32. map, filter and reduce? map transforms each item into a new array, filter keeps items that pass a test and reduce folds an array into one value. In the snippet, [1,2,3,4] gave [2,4,6,8], [1,3] and 10. None of them change the original array.
  • Q33. Why does [10, 9, 1].sort() give [1, 10, 9]? The default sort compares items as strings. Pass a comparator, (x, y) => x - y, for numbers. sort also changes the array in place.
  • Q34. How do I write debounce, and when is it used? It delays a function until calls stop for a set time, used for search boxes and resize handlers. It keeps a timer in a closure. The snippet called it three times in a row and the function ran once (debounced calls: 1).
function debounce(fn, ms) {
  let t;
  return (...args) => { clearTimeout(t); t = setTimeout(() => fn(...args), ms); };
}
let calls = 0;
const d = debounce(() => calls++, 20);
d(); d(); d();
setTimeout(() => console.log("debounced calls:", calls), 60);
const memo = fn => { const m = new Map(); return n => m.has(n) ? m.get(n) : (m.set(n, fn(n)), m.get(n)); };
let runs = 0;
const sq = memo(n => (runs++, n * n));
sq(4); sq(4); sq(5);
console.log("computed", runs, "times");
console.log([1, [2, [3, [4]]]].flat(Infinity));
console.log([..."aabbc"].filter((c, i, s) => s.indexOf(c) === i).join(""));

Output:

computed 2 times
[ 1, 2, 3, 4 ]
abc
debounced calls: 1

Compare with TypeScript, which adds types on top of these rules, in TypeScript vs JavaScript difference. To print and inspect values while practising, see JavaScript print and console.log.

Revision plan

  1. Day 1: Q1 to Q7. Type the types snippet and predict each line before running it.
  2. Day 2: scope, hoisting and closures. Explain the var versus let loop out loud.
  3. Day 3: this, call, bind and prototypes. Write a class and its prototype version.
  4. Day 4: the event loop. Predict the order of five small snippets, then run them with node.
  5. Day 5: promises and async/await. Rewrite a nested callback as a chain, then as await. Practise with JavaScript practice projects.
  6. Day 6 and 7: React interview questions and Node.js interview questions.

Frequently asked questions

What are the most asked JavaScript interview questions?

No company publishes its question bank, so this is our reading. Expect closures (especially the var loop), the event loop order, promises and async/await, the this keyword, hoisting, == versus === and prototypes. Questions 9, 11, 12, 16, 24 and 26 above are the ones to master first.

How do I prepare JavaScript for a fresher interview?

Run every snippet yourself with Node or the browser console and predict the output first. Then rebuild three utilities from memory: debounce, memoize and a promise-based delay. Fundamentals matter more than framework knowledge at fresher level.

What is the difference between synchronous and asynchronous JavaScript?

Synchronous code runs line by line and blocks the next line until done. Asynchronous code starts work (a timer, a network call) and lets the program continue, running a callback or resuming an await later through the event loop.

Are closures and the event loop always asked?

They are among the most common JavaScript topics in fresher and junior rounds, often as a predict-the-output snippet. Practise the loop-with-var closure and the order of setTimeout, promise and sync code until you can explain each step.

Should I learn JavaScript or TypeScript first?

JavaScript first, because TypeScript is JavaScript plus types and interviews still test the base language. After that, the TypeScript vs JavaScript page in this hub shows what the types add and what stays the same.

Do I need DOM questions for a JavaScript interview?

For frontend roles, yes: event bubbling, delegation, querySelector and addEventListener. For Node or general roles, the core language topics on this page matter more. The DOM was not run in our snippets, so practise it in your browser console.

Learn this with mentors

Programmes for builders and engineers with admissions open: live classes, mentors and project work.

Continue learning

Interview prep

React interview questions

40 questions, model answers and six coding problems for React 19.3

11 min read
Interview prep

Node.js interview questions

36 answers with tested code, from the event loop to Express 5 and scaling

11 min read
Concept

TypeScript vs JavaScript

A runnable bug in JavaScript, the TypeScript fix, and when to skip it.

5 min read