JavaScript interview questions: answers with real output
The "what does this print?" questions, answered in plain words with code that was actually run.
JavaScript interviews focus on scope (var, let, const), equality (== vs ===), closures, how this is set, the event loop (why promises run before setTimeout), promises and async/await, array methods and copying objects. Below are 20 questions from basic to advanced; every example was run in Node.js and shows its real output.
Basic javascript interview questions
Basic1. What is the difference between var, let and const?
var is function-scoped and hoisted with the value undefined. let and const are block-scoped and cannot be used before their declaration (the temporal dead zone). const prevents reassignment, but an object declared with const can still be changed.
Javascriptfor (var i = 0; i < 2; i++) {}
console.log('var after loop:', i);
for (let j = 0; j < 2; j++) {}
console.log('let after loop:', typeof j);
const user = { name: 'Ava' };
user.name = 'Ben';
console.log(user);
try { eval('const k = 1; k = 2;'); } catch (e) { console.log(e.name + ':', e.message); }Output (Node.js 24.15.0)var after loop: 2
let after loop: undefined
{ name: 'Ben' }
TypeError: Assignment to constant variable.Basic2. What is the difference between == and ===?
=== compares value and type with no conversion. == converts types first, which produces surprising results. Use === by default.
Javascriptconsole.log(0 == '0', 0 === '0');
console.log(null == undefined, null === undefined);
console.log('' == 0, [] == false);Output (Node.js 24.15.0)true false true false true true
Basic3. What is the difference between null and undefined?
undefined means a value was never assigned; null is an intentional empty value. typeof null returns 'object', a long-standing quirk of the language.
Javascriptlet a;
const b = null;
console.log(a, b);
console.log(typeof a, typeof b);
console.log({ x: 1 }.y);Output (Node.js 24.15.0)undefined null undefined object undefined
Basic4. 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 as undefined; let, const and class are hoisted but unusable until declared.
Javascriptconsole.log(early());
function early() { return 'function declarations are hoisted'; }
console.log(typeof later);
var later = 1;
try { console.log(notYet); let notYet = 2; } catch (e) { console.log(e.name); }Output (Node.js 24.15.0)function declarations are hoisted undefined ReferenceError
Basic5. What do ?? and ?. do?
Optional chaining (?.) stops and returns undefined if the value before it is null or undefined. Nullish coalescing (??) supplies a default only for null or undefined, unlike ||, which also replaces 0, '' and false.
Javascriptconst job = { pay: 0, company: null };
console.log(job.company?.name);
console.log(job.pay || 50000, job.pay ?? 50000);
console.log(job.title ?? 'untitled');Output (Node.js 24.15.0)undefined 50000 0 untitled
Basic6. How do map, filter and reduce differ?
map transforms every item and returns a new array of the same length; filter keeps the items that pass a test; reduce combines items into one value. None of them changes the original array.
Javascriptconst salaries = [52000, 70000, 95000, 120000];
console.log(salaries.map(s => s / 1000));
console.log(salaries.filter(s => s >= 70000));
console.log(salaries.reduce((sum, s) => sum + s, 0));Output (Node.js 24.15.0)[ 52, 70, 95, 120 ] [ 70000, 95000, 120000 ] 337000
Basic7. How do you remove duplicates from an array?
Create a Set (which keeps unique values) and spread it back into an array. For objects, deduplicate by a key with a Map.
Javascriptconst skills = ['sql', 'js', 'sql', 'python', 'js'];
console.log([...new Set(skills)]);
const people = [{ id: 1, n: 'Ava' }, { id: 2, n: 'Ben' }, { id: 1, n: 'Ava' }];
console.log([...new Map(people.map(p => [p.id, p])).values()]);Output (Node.js 24.15.0)[ 'sql', 'js', 'python' ]
[ { id: 1, n: 'Ava' }, { id: 2, n: 'Ben' } ]Intermediate javascript interview questions
Intermediate8. What is a closure?
A closure is a function that keeps access to the variables of the scope where it was created, even after that scope has finished. It is how private state and factories work.
Javascriptfunction counter() {
let count = 0;
return { inc: () => ++count, get: () => count };
}
const c = counter();
c.inc(); c.inc();
console.log(c.get());
console.log(typeof count);Output (Node.js 24.15.0)2 undefined
Intermediate9. How does this differ in arrow functions and regular functions?
A regular function's this depends on how it is called (the object before the dot). An arrow function has no this of its own: it uses the this of the surrounding code (here the top level, so this?.name is undefined). That is why arrow functions are handy for callbacks but wrong for object methods that need the object.
Javascriptconst team = {
name: 'Platform',
regular() { return this.name; },
arrow: () => this?.name,
later() { return [1].map(() => this.name); },
};
console.log(team.regular());
console.log(team.arrow());
console.log(team.later());
const detached = team.regular;
console.log(detached.call({ name: 'Other' }));Output (Node.js 24.15.0)Platform undefined [ 'Platform' ] Other
Intermediate10. What is the difference between call, apply and bind?
All three set this. call invokes the function with arguments listed one by one; apply invokes it with an array of arguments; bind returns a new function with this (and optionally some arguments) fixed, without calling it.
Javascriptfunction intro(greeting, punct) { return `${greeting}, ${this.name}${punct}`; }
const ava = { name: 'Ava' };
console.log(intro.call(ava, 'Hi', '!'));
console.log(intro.apply(ava, ['Hello', '.']));
const hey = intro.bind(ava, 'Hey');
console.log(hey('?'));Output (Node.js 24.15.0)Hi, Ava! Hello, Ava. Hey, Ava?
Intermediate11. In what order do setTimeout, promises and synchronous code run?
Synchronous code runs first. Then the microtask queue empties (promise callbacks, queueMicrotask). Only then does the event loop take the next macrotask, such as a setTimeout callback, even one with a delay of 0.
Javascriptconsole.log('1 sync');
setTimeout(() => console.log('4 timeout'), 0);
Promise.resolve().then(() => console.log('3 promise'));
console.log('2 sync');Output (Node.js 24.15.0)1 sync 2 sync 3 promise 4 timeout
Intermediate12. What is the difference between promises and async/await?
async/await is syntax on top of promises: an async function always returns a promise, and await pauses that function until the promise settles. Errors are handled with try/catch instead of .catch().
Javascriptconst wait = (v, fail) => new Promise((res, rej) => setTimeout(() => fail ? rej(new Error(v)) : res(v), 10));
wait('then-style').then(v => console.log(v));
(async () => {
console.log(await wait('await-style'));
try { await wait('boom', true); } catch (e) { console.log('caught', e.message); }
})();Output (Node.js 24.15.0)then-style await-style caught boom
Intermediate13. What is the difference between Promise.all and Promise.allSettled?
Promise.all resolves with every result, or rejects as soon as any promise rejects. Promise.allSettled waits for all of them and reports each one's status, which suits independent tasks where some may fail.
Javascriptconst ok = Promise.resolve('ok');
const bad = Promise.reject(new Error('down'));
Promise.all([ok, bad]).catch(e => console.log('all rejected:', e.message));
Promise.allSettled([ok, bad]).then(r => console.log(r.map(x => x.status)));Output (Node.js 24.15.0)all rejected: down [ 'fulfilled', 'rejected' ]
Intermediate14. How do you deep copy an object?
Spread ({...obj}) and Object.assign make shallow copies, so nested objects are shared. structuredClone makes a deep copy of plain data, including dates, maps and sets (not functions). JSON round-tripping also works but drops dates and undefined.
Javascriptconst original = { name: 'Ava', skills: ['sql'], since: new Date(0) };
const shallow = { ...original };
const deep = structuredClone(original);
original.skills.push('js');
console.log(shallow.skills, deep.skills);
console.log(deep.since instanceof Date);Output (Node.js 24.15.0)[ 'sql', 'js' ] [ 'sql' ] true
Intermediate15. How would you write a debounce function?
Debounce delays a function until calls stop for a set time: each new call clears the previous timer. It is used for search boxes and resize handlers.
Javascriptfunction debounce(fn, ms) {
let t;
return (...args) => { clearTimeout(t); t = setTimeout(() => fn(...args), ms); };
}
const search = debounce(q => console.log('search for', q), 50);
search('j'); search('ja'); search('java');Output (Node.js 24.15.0)search for java
Advanced javascript interview questions
Advanced16. How does prototypal inheritance work?
Every object has a prototype it falls back to when a property is missing. Classes are syntax over this: methods live on the prototype, and extends links one prototype to another.
Javascriptclass Person {
constructor(name) { this.name = name; }
hello() { return `I am ${this.name}`; }
}
class Engineer extends Person {
hello() { return super.hello() + ', an engineer'; }
}
const e = new Engineer('Cara');
console.log(e.hello());
console.log(Object.getPrototypeOf(Engineer.prototype) === Person.prototype);
console.log(Object.hasOwn(e, 'hello'));Output (Node.js 24.15.0)I am Cara, an engineer true false
Advanced17. Why does [10, 1, 2].sort() return [1, 10, 2]?
Without a compare function, sort converts items to strings and compares them as text, so '10' comes before '2'. Pass (a, b) => a - b for numbers. sort also changes the original array; toSorted() returns a sorted copy.
Javascriptconst nums = [10, 1, 2];
console.log([...nums].sort());
console.log([...nums].sort((a, b) => a - b));
console.log(nums.toSorted((a, b) => b - a), nums);Output (Node.js 24.15.0)[ 1, 10, 2 ] [ 1, 2, 10 ] [ 10, 2, 1 ] [ 10, 1, 2 ]
Advanced18. Why is 0.1 + 0.2 not equal to 0.3?
JavaScript numbers are 64-bit binary floating point, which cannot represent 0.1 or 0.2 exactly. Compare with a tolerance, or work in integers (such as cents). BigInt handles large integers exactly.
Javascriptconsole.log(0.1 + 0.2);
console.log(0.1 + 0.2 === 0.3);
console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON);
console.log(2n ** 64n);Output (Node.js 24.15.0)0.30000000000000004 false true 18446744073709551616n
Advanced19. Does const make an object immutable?
No. const stops the variable from being reassigned; the object's contents can still change. Object.freeze prevents changes to the top level only (nested objects stay mutable). In strict mode, writing to a frozen object throws an error.
Javascript'use strict';
const cfg = Object.freeze({ env: 'prod', db: { host: 'a' } });
try { cfg.env = 'dev'; } catch (e) { console.log(e.name); }
cfg.db.host = 'b';
console.log(cfg);Output (Node.js 24.15.0)TypeError
{ env: 'prod', db: { host: 'b' } }Advanced20. How do you group items by a key?
Object.groupBy (available in recent engines, including Node 21+) groups an array by the value a callback returns. reduce does the same in older environments.
Javascriptconst roles = [{ n: 'Ava', team: 'eng' }, { n: 'Dev', team: 'sales' }, { n: 'Ben', team: 'eng' }];
const grouped = Object.groupBy(roles, r => r.team);
console.log(Object.fromEntries(Object.entries(grouped).map(([k, v]) => [k, v.map(r => r.n)])));
const viaReduce = roles.reduce((acc, r) => ((acc[r.team] ??= []).push(r.n), acc), {});
console.log(viaReduce);Output (Node.js 24.15.0){ eng: [ 'Ava', 'Ben' ], sales: [ 'Dev' ] }
{ eng: [ 'Ava', 'Ben' ], sales: [ 'Dev' ] }How to practice with this page
- Read each example and predict the output before looking.
- Explain why, not just what: interviewers ask follow-ups.
- Run the examples in a browser console or Node.js and change one line at a time.
- Front-end roles: practice the DOM and your framework as well.
Related interview prep
Disclosure: TryHired makes HIRED, a paid job-search program, so we have a conflict of interest when we mention it. This question bank is free, with no TryHired signup.
Framework and backend rounds: continue with React interview questions and Java interview questions.
Questions people ask
What JavaScript questions are asked in interviews?
How do I prepare for a JavaScript interview?
Is JavaScript the same as Java?
Which JavaScript version do these examples use?
Do I need to know TypeScript for a JavaScript interview?
How this page is built
TryHired wrote these questions and answers. Every code block on this page was executed with Node.js 24.15.0 when the page was built, and the output shown is the real output; the build stops if any example fails. The question list is general practice: it does not predict what a particular employer will ask.
- Interviewers ask different questions for different roles and levels.
- Answers are short explanations, not complete language references.
- Examples ran in Node.js; browsers behave the same for these examples, but Object.groupBy and toSorted need a recent browser.
- MDN Web Docs, JavaScript reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
- MDN Web Docs, the event loop: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Event_loop
- ECMAScript language specification: https://tc39.es/ecma262/