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 page
Types, 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 questionsFor 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 nullan object? It is a long-standing bug in the language that was never fixed to avoid breaking existing code. Test for null withvalue === null. The snippet showstypeof nullasobjectandtypeof []asobjecttoo, so useArray.isArrayfor arrays. - Q3.
==versus===?===compares without converting types.==converts first, so1 == "1"is true while1 === "1"is false.null == void 0is true whilenull === void 0is false, wherevoid 0is the "no value yet" value. Use===by default. - Q4. Why is
0.1 + 0.2not 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 asNumber.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) andNaN. Everything else is truthy, including"0",[]and{}, a classic trap shown in the output. - Q6. How do I check for
NaN?NaN === NaNis false. UseNumber.isNaN(x)orObject.is(x, NaN). The globalisNaNcoerces first and gives surprising results. - Q7. What does
[] + {}give? The string"[object Object]", because both operands are converted to strings."5" + 2is"52"(string join) but"5" - 2is3(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,letandconst: what is the difference?varis function-scoped and can be redeclared.letandconstare block-scoped, andconstcannot be reassigned, though the object it holds can still be changed. Preferconst, useletwhen you must reassign and avoidvar. - Q9. What is hoisting? Declarations are processed before code runs. Function declarations are hoisted with their body, so you can call them early.
varis hoisted and starts with the "no value yet" value.letandconstare hoisted but stay unusable until their line, the temporal dead zone. - Q10. What does the hoisting snippet show?
typeof hoistedVarprinted the "no value yet" type name and the function runs before its definition. ReadingletValueearly throwsReferenceError. A function stored in avarhas no value until its line runs, so calling it early throwsTypeError.
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 privaten, and nothing outside can touch it. Closures give private state, callbacks and function factories. See the MDN closures guide. - Q12. Why does a
varloop with closures print 3, 3, 3? All three callbacks share the one function-scopedi, which is 3 when they run. Withlet, each iteration gets its ownj, 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 andletexisted. Today, ES modules and block scope cover most of the need. - Q15. What are currying and memoization? Currying turns
f(a, b)intof(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
thisdecided? By how the function is called. As a method (obj.fn()),thisisobj. Withnew, it is the new object. Withcall,applyorbind, it is what you pass. A plain call gives nothisat all in strict mode or the global object in sloppy mode. Arrow functions have nothisof their own and use the enclosing one. See MDN onthis. - Q17. Why does a detached method lose
this? Copyingconst lost = user.regularand callinglost()is a plain call, sothisis no longeruser, and the snippet printed the "no value yet" value. Fix it withbind, an arrow wrapper or by callinguser.regular(). - Q18.
call,applyandbind: what is the difference?call(thisArg, a, b)andapply(thisArg, [a, b])invoke the function now.bind(thisArg)returns a new function withthisfixed. The snippet printedRaviandMeerausingbindandcall. - Q19. When should I not use an arrow function? For object methods that need their own
this(thearrowmethod printed the module'sthis, an object in a Node CommonJS file, notuser), for constructors (arrows cannot be used withnew) and when you needarguments.
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 howa.speak()works in the snippet below:speaklives onAnimal.prototype, not ona. - Q21. Are ES6 classes real classes? They are syntax over prototypes.
class Cat extends Animalsets up the same prototype chain, andsuper.speak()calls the parent method. The output showsTom makes a sound (meow). - Q22. Shallow copy versus deep copy? Spread (
{...obj}) copies one level, so nested objects are still shared. After changingoriginal.nested.bto 99, the shallow copy showed 99 and thestructuredClonecopy 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 afterawait), then the next macrotask such assetTimeout. In the snippet, thesetTimeout(..., 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.
thenandcatchregister callbacks, and chaining returns new promises. Details are on MDN Promise. - Q26.
Promise.all,allSettled,raceandany?allwaits for every promise and rejects on the first failure.allSettledwaits for all and reports each status.racesettles with the first to settle, success or failure.anyfulfills with the first success. The snippet printed['ok','slow'],['fulfilled','rejected'], a rejected race andokforany. - Q27. How does
async/awaitrelate to promises? Anasyncfunction always returns a promise, andawaitpauses that function (not the thread) until a promise settles. Errors becometry/catch. It is syntax over promises. - Q28. Why can sequential
awaitbe slow? Awaiting one call after another adds the delays, whilePromise.allstarts them together. In the snippet, two 30 ms waits took longer one after the other than together, and the check printedtrue. Use sequentialawaitonly 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/awaitflatten 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
catchor wrapawaitintry/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,
letandconst, template literals, destructuring, spread and rest, default parameters, modules, classes, optional chaining (?.) and nullish coalescing (??). The utility and prototype snippets use several. Note0 ?? "d"is0while0 || "d"is"d". - Q32.
map,filterandreduce?maptransforms each item into a new array,filterkeeps items that pass a test andreducefolds an array into one value. In the snippet,[1,2,3,4]gave[2,4,6,8],[1,3]and10. 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.sortalso 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
- Day 1: Q1 to Q7. Type the types snippet and predict each line before running it.
- Day 2: scope, hoisting and closures. Explain the
varversusletloop out loud. - Day 3:
this,call,bindand prototypes. Write a class and its prototype version. - Day 4: the event loop. Predict the order of five small snippets, then run them with
node. - Day 5: promises and
async/await. Rewrite a nested callback as a chain, then asawait. Practise with JavaScript practice projects. - 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.


