- 110 JavaScript questions covering fundamentals, async, ES6+, DOM, and coding programs.
- Closures, the event loop, and == vs === decide most Chennai frontend shortlists.
- DSA and aptitude are not mixed here - use the dedicated hubs.
- Practice predict-the-output snippets aloud before React rounds.
- Planning salary: JS/frontend freshers roughly Rs.3.5-6.5 LPA - varies.
JavaScript interview questions and answers in 2026 cover language fundamentals, scope and closures, the event loop, ES6+ syntax, DOM APIs, and short live coding - but fresher panels in Chennai now expect you to connect JavaScript theory to React or Node project stories, not just recite definitions. This 110-question guide is language-focused; for algorithm-heavy prep use our DSA interview questions and coding interview questions hubs instead of mixing both on one page.
Last updated: September 9, 2026 - Reviewed by Asmorix full stack mentors in Chennai
Asmorix mentors compiled these from product startups, GCC front-end loops, and full stack trainee drives across OMR and Guindy. Pair this page with React interview questions, Python interview questions, Java interview questions, programming problems and solutions, company-wise coding questions, full stack developer course in Chennai, and the Asmorix blog.
How JavaScript Interviews Are Structured in India (2026)
Most JavaScript and front-end fresher loops in Chennai follow four rounds. Know the filter before you memorize 110 answers:
| Round | What is tested | Typical filter |
|---|---|---|
| Online assessment (OA) | Aptitude from aptitude questions, logical reasoning, 1-2 easy JS coding tasks | Working code with edge cases beats pseudo-code |
| Technical round 1 | JS fundamentals, scope, closures, DOM basics, small programs | Direct first sentence plus one runnable example |
| Technical round 2 | Async/event loop, ES6+, framework round (React or similar), project deep-dive | Can you explain WHY the event loop or closure behaves that way |
| Managerial / HR | Communication, relocation, salary fit, notice period | Structured, honest answers without overselling |
Key takeaway: interviewers reward a crisp first sentence, then a short example - exactly how every answer below is structured for answer-engine and spoken delivery. For pure DSA depth, use quantitative aptitude and logical reasoning hubs alongside this language guide.
JavaScript Fundamentals Interview Questions (Q1-Q22)
1. What is the difference between JavaScript and Java?
JavaScript is a dynamic, interpreted scripting language for browsers and Node.js, while Java is a statically typed, compiled JVM language - they share a name history but not syntax, runtime, or use cases. Say it plainly: JavaScript runs in the browser event loop; Java runs bytecode on the JVM. Chennai interviewers use this to filter candidates who confuse the two on resumes.
2. What is the difference between var, let, and const?
var is function-scoped and hoisted with an undefined initializer; let and const are block-scoped, hoisted into the TDZ until their declaration line, and const cannot be reassigned (though object contents may mutate). Default to const, use let when reassignment is required, and avoid var in new code. Services panels still ask because legacy codebases mix all three.
3. What are the data types in JavaScript?
JavaScript has seven primitive types (string, number, bigint, boolean, undefined, symbol, null) plus object for everything else including arrays and functions. typeof null returns "object" - a long-standing quirk interviewers expect you to know. ES2026 interviews also mention that functions are callable objects, not a separate primitive.
4. What is the difference between == and ===?
== performs type coercion before comparison; === compares both value and type without coercion. Always prefer === in production code to avoid surprises like 0 == false being true. Mention that Object.is() handles edge cases like NaN and -0 vs +0 that === misses.
console.log(0 == false);
console.log(0 === false);
console.log('' == false);
console.log(null == undefined);
console.log(null === undefined);
true
false
true
true
false
5. What is hoisting in JavaScript?
Hoisting is the compile phase where var declarations and function declarations are registered at the top of their scope before execution - var initializes as undefined, while let/const enter the TDZ until their line runs. Function declarations hoist fully; function expressions assigned to var behave like var. Draw the temporal order on paper when interviewers push for detail.
console.log(greet);
var greet = 'hi';
function greet() { return 'hello'; }
console.log(typeof greet);
undefined
string
6. What is the Temporal Dead Zone (TDZ)?
The TDZ is the span from the start of a block until a let or const declaration is evaluated, where accessing the binding throws ReferenceError. var has no TDZ because it hoists as undefined. Classic trap: console.log(x); let x = 5; throws because x exists but is uninitialized.
7. What is type coercion in JavaScript?
Type coercion is the automatic conversion of values to another type during operations - implicit with == and +, explicit with Number(), String(), or Boolean(). The + operator concatenates if either operand is a string; otherwise it adds numbers. Interviewers love [] + [] and null + 1 style puzzles - know the rules, not every trick.
console.log('5' + 1);
console.log('5' - 1);
console.log([] + []);
console.log(true + true);
51
4
2
8. What is NaN and how do you check for it?
NaN means Not-a-Number and represents an invalid numeric result - it is the only value in JavaScript that is not equal to itself (NaN === NaN is false). Use Number.isNaN(value) instead of the global isNaN(), which coerces non-numbers first. Number.isNaN(NaN) is true; Number.isNaN("hello") is false.
9. What is the difference between null and undefined?
undefined means a variable was declared but not assigned, or a missing object property; null is an intentional empty assignment by the developer. typeof undefined is "undefined"; typeof null is "object". Use null when you deliberately mean no value; leave undefined for unset defaults.
10. What are truthy and falsy values in JavaScript?
Falsy values are false, 0, -0, 0n, "", null, undefined, and NaN - everything else is truthy, including [], {}, and "0". Boolean contexts like if statements and && / || use this coercion. Interviewers follow up: [] is truthy but Boolean([]) is true while Number([]) is 0.
11. What does the spread operator (...) do?
The spread operator expands iterables into individual elements or object properties - useful for copying arrays, merging objects, and passing arguments to functions. It creates a shallow copy, not a deep clone. Example: const merged = { ...defaults, ...userInput }; is the modern replacement for Object.assign in many cases.
const arr = [1, 2];
console.log([0, ...arr, 3]);
const base = { a: 1 };
console.log({ ...base, b: 2 });
[ 0, 1, 2, 3 ]
{ a: 1, b: 2 }
12. What are rest parameters in JavaScript?
Rest parameters collect remaining arguments into a real array using ...name in a function signature - unlike the legacy arguments object, rest parameters are true arrays with map/filter. They must be the last parameter. Spread expands; rest collects - same syntax, opposite direction.
13. What is destructuring in JavaScript?
Destructuring unpacks values from arrays or properties from objects into distinct variables in one assignment. It supports defaults, renaming, and nested patterns. Common in React props: const { title, id } = props; Chennai product teams expect fluent destructuring in live coding round one.
14. What are template literals?
Template literals use backticks for strings with embedded expressions via ${expression} and support multi-line text without escape hacks. They replace most string concatenation in modern code. Tagged templates (fn`hello`) appear rarely in fresher interviews but show advanced awareness.
15. What is the difference between arrow functions and regular functions?
Arrow functions have lexical this (inherited from enclosing scope), no arguments object, cannot be used as constructors, and use concise syntax. Regular functions get their own this binding based on call site (call/apply/bind). Use arrows for callbacks; use regular functions for object methods that need dynamic this.
16. What is the this keyword in JavaScript?
this refers to the execution context object - in a method it is the receiver, in a plain function (non-strict) it is the global object, and in strict mode standalone functions get undefined. Arrow functions ignore their own this and inherit from the outer scope. bind() permanently fixes this for a function.
17. What is the difference between call, apply, and bind?
call invokes a function immediately with a given this and comma-separated args; apply is the same but args arrive as an array; bind returns a new function with this permanently set without calling it yet. All three borrow methods across objects - classic interview follow-up after this keyword questions.
const user = { name: 'Anu' };
function greet(greeting) { return greeting + ', ' + this.name; }
console.log(greet.call(user, 'Hi'));
console.log(greet.apply(user, ['Hello']));
const bound = greet.bind(user, 'Hey');
console.log(bound());
Hi, Anu
Hello, Anu
Hey, Anu
18. What is a closure in JavaScript?
A closure is a function that remembers variables from its lexical scope even after the outer function has finished executing. Closures power private state, factory functions, and event handlers. Interviewers expect you to write a counter or multiplier example without looking up syntax.
function makeCounter() {
let count = 0;
return () => ++count;
}
const counter = makeCounter();
console.log(counter());
console.log(counter());
1
2
19. What is lexical scope?
Lexical scope means a function's free variables are resolved by where the function was written in source code, not where it is called. Inner functions can read outer variables; the chain walks outward until global. Closures and module patterns depend entirely on lexical scope - say "static scope" if the interviewer uses that term.
20. What is strict mode in JavaScript?
Strict mode ('use strict') opts into tighter semantics: undeclared assignments throw, duplicate params are errors, and this in plain functions is undefined instead of the global object. Modules and classes are strict by default in ES modules. Mention it prevents silent bugs that made early JavaScript hard to maintain.
21. How does the typeof operator work?
typeof returns a string naming the type of its operand - but it returns "object" for null and "function" for functions (even though functions are objects). For arrays use Array.isArray(); for null use value === null. typeof is fast but imprecise for complex checks.
22. What is the difference between primitive and reference types in JavaScript?
Primitives (string, number, etc.) are stored by value - copying assigns a new value. Objects, arrays, and functions are references - copying copies the pointer, so mutating through one variable affects all sharing that object. This drives answers on shallow copy vs deep clone later in the same interview.
JavaScript Scope, Async, and Events Interview Questions (Q23-Q45)
23. What is the JavaScript event loop?
The event loop is the runtime mechanism that pulls tasks from the macrotask queue (timers, I/O) and microtask queue (promises) onto the call stack when it is empty, enabling non-blocking concurrency on a single thread. JavaScript runs one call stack at a time; async work completes via callbacks scheduled by the loop. Draw stack, web APIs, and queues when interviewers ask you to trace order.
24. What is the difference between microtasks and macrotasks?
Microtasks (promise callbacks, queueMicrotask) run after the current script and before the next macrotask; macrotasks (setTimeout, setInterval, I/O) run one per event loop turn after microtasks drain. Order trap: Promise.resolve().then(...) runs before setTimeout(..., 0). This sequence appears in nearly every async round.
25. What is a Promise in JavaScript?
A Promise is an object representing the eventual completion or failure of an async operation with states pending, fulfilled, or rejected. then/catch/finally chain handlers; once settled, state cannot change. Promises replaced callback pyramids and integrate with async/await syntax sugar on top.
26. What is async/await?
async/await is syntactic sugar over Promises - async functions always return a Promise, and await pauses within an async function until a Promise settles, without blocking the main thread. Use try/catch for error handling instead of .catch chains in sequential async code. Interviewers expect you to rewrite a .then chain into async/await live.
27. What is callback hell?
Callback hell is deeply nested callback functions that make async code hard to read and error-handle - often from chaining async I/O before Promises existed. Promises and async/await flatten the pyramid into linear code. Mention naming callbacks and modularizing steps as a pre-Promise mitigation.
28. What does Promise.all do?
Promise.all takes an iterable of Promises and returns one Promise that fulfills with an array of results when all succeed, or rejects immediately on the first failure. Use it for parallel independent requests. Promise.allSettled waits for all regardless of individual failure - know when to pick each.
29. What does Promise.race do?
Promise.race settles with the result of the first Promise that fulfills or rejects among the iterable. Common pattern: timeout wrapper racing fetch against a timer Promise. It does not cancel losing requests - only ignores their later settlement.
30. What is the difference between setTimeout and setInterval?
setTimeout runs a callback once after a delay; setInterval repeats it every delay until cleared with clearInterval. Both schedule macrotasks - neither guarantees exact timing under heavy load. Drift accumulates in setInterval; recursive setTimeout often gives more predictable spacing.
31. What is an execution context?
An execution context is the environment in which JavaScript code runs, containing the variable object, scope chain, and this binding. Each function call creates a new context pushed onto the call stack; returning pops it. Global code runs in the global execution context created at startup.
32. What is the scope chain?
The scope chain is the linked list of lexical environments searched when resolving an identifier - inner scope first, then outer, up to global. If no binding exists, ReferenceError throws in strict resolution. Closures capture the entire chain at function creation time.
33. What is block scope?
Block scope limits let and const to the nearest enclosing {} block - if, for, while, or standalone blocks. var ignores blocks and leaks to function or global scope. Block scope prevents loop variable bugs that plagued var-based for loops.
34. What is an IIFE?
An Immediately Invoked Function Expression wraps code in a function and runs it once to create a private scope before modules were standard: (function () { ... })();. It avoids polluting global namespace and was the classic pattern for libraries before ES modules. Still fair game in legacy maintenance questions.
35. What is a higher-order function?
A higher-order function takes another function as an argument, returns a function, or both - examples include map, filter, reduce, and addEventListener. They enable composition and abstraction over behavior. Functional-style interviews in Chennai startups often ask you to implement map from scratch.
36. What is currying?
Currying transforms a function of multiple arguments into a sequence of functions each taking one argument - f(a,b,c) becomes f(a)(b)(c). It helps partial application and reusable configuration. Light mention in fresher rounds; product teams may ask for a curry helper implementation.
37. What is debouncing?
Debouncing delays a function until input stops for a specified wait time - ideal for search-as-you-type and resize handlers so you do not fire hundreds of API calls. Each new trigger resets the timer. Contrast with throttling, which enforces a maximum call rate. See Q74 for a code sample.
38. What is throttling?
Throttling ensures a function runs at most once per time window regardless of how many events fire - common for scroll and mousemove handlers. Unlike debounce, throttle guarantees periodic execution during continuous input. Pick debounce for "after pause" and throttle for "steady sampling".
39. What is memoization?
Memoization caches the results of expensive pure function calls keyed by arguments so repeat calls return instantly. A simple object or Map stores prior outputs. It trades memory for speed - only safe when the function has no hidden side effects. React useMemo applies the same idea to rendered values.
40. How do you handle errors in async/await code?
Wrap await calls in try/catch inside async functions, or attach .catch() to the returned Promise at the call site. Unhandled Promise rejections can crash Node processes depending on version flags. Always handle rejection paths in interviews - happy-path-only async code is an instant red flag.
41. What is event bubbling?
Event bubbling propagates an event from the target element up through ancestor nodes in the DOM tree after the target phase. Most events bubble by default unless stopped. Parent handlers on containers can listen for child events - the basis of event delegation.
42. What is event delegation?
Event delegation attaches one listener on a parent to handle events from multiple children via bubbling, using event.target to identify which child fired. It reduces memory use and works for dynamically added elements. List rendering in React often mirrors this pattern at the virtual DOM level.
43. What is the difference between event.target and event.currentTarget?
event.target is the element that originally triggered the event; event.currentTarget is the element whose listener is currently executing (often a parent in delegation). They match when the listener sits on the clicked node. Confusing the two breaks delegated click handlers in live DOM exercises.
44. What is the difference between preventDefault and stopPropagation?
preventDefault stops the browser default action (like following a link); stopPropagation stops the event from traveling to other nodes in the bubble/capture path. You can use both independently - a form submit handler might preventDefault without stopping bubble to let analytics listeners run.
45. What causes memory leaks in JavaScript?
Memory leaks happen when unreachable objects stay referenced - common causes include forgotten timers, detached DOM nodes still referenced in closures, and global variables accumulating data. Modern engines garbage-collect unreachable objects automatically; leaks are usually retained references, not missing delete keywords.
JavaScript ES6+ and DOM Interview Questions (Q46-Q70)
46. What is the difference between ES modules and CommonJS?
ES modules use import/export, load asynchronously, and are statically analyzable; CommonJS (require/module.exports) loads synchronously and dominated Node.js before native ESM support. Browser bundlers and modern Node prefer ESM for tree-shaking. Mention that import must stay at top level in modules.
47. What is a prototype in JavaScript?
Every object has an internal [[Prototype]] link (accessed via __proto__ or Object.getPrototypeOf) used when a property is missing on the object itself. Functions have a prototype property used when called with new. Prototypes enable shared methods without copying them onto every instance.
48. What is the prototype chain?
The prototype chain is the lookup path from an object through its prototypes until null when a property is accessed. If no link owns the key, undefined returns (or the function keeps walking for method calls). class syntax desugars to constructor functions plus prototype wiring under the hood.
49. How does inheritance work in JavaScript?
JavaScript uses prototypal inheritance - objects inherit from other objects via the prototype chain, not class copying like Java. ES6 class extends sets up the chain with super keyword for parent constructors and methods. Object.create(parent) is the explicit API for setting an object's prototype.
50. What does class syntax provide in JavaScript?
class is syntactic sugar over constructor functions with clearer extends, super, static, and private field (#field) support. Methods live on the prototype; static methods live on the constructor. Classes are not hoisted like function declarations - temporal dead zone applies until the class statement runs.
51. When do you use Map vs a plain Object?
Map accepts any key type (including objects), preserves insertion order, and exposes size directly; plain objects are fine for string-keyed records and JSON serialization. Map performs better for frequent add/delete of arbitrary keys. Use Object for DTOs; use Map for in-memory indexes and caches.
52. What is a Set in JavaScript?
Set stores unique values of any type with fast has/add/delete - duplicates are ignored by SameValueZero equality. Convert an array to unique entries with [...new Set(arr)]. Sets appear in deduplication and tag-collection interview coding tasks alongside frequency maps.
53. What is optional chaining (?.)?
Optional chaining short-circuits to undefined if any reference in a chain is nullish instead of throwing - user?.address?.city avoids nested if checks. Combine with nullish coalescing for defaults. It does not catch all errors - only null/undefined breaks the chain.
54. What is the nullish coalescing operator (??)?
?? returns the right operand only when the left is null or undefined - unlike ||, it preserves 0, false, and "". Example: const port = config.port ?? 3000; keeps port 0 if explicitly set. Useful for config defaults in Node apps.
55. What is an iterator in JavaScript?
An iterator is an object with a next() method returning { value, done } - built-in iterables include Array, String, Map, and Set. for...of consumes iterables by calling next() under the hood. Custom iterables implement Symbol.iterator.
56. What is a generator function?
Generator functions (function*) return iterator objects and can pause with yield, resuming later - useful for lazy sequences and async flows before async/await dominated. yield* delegates to another iterable. Fresher interviews rarely require generators but expect you to recognize the syntax.
57. What is a Symbol in JavaScript?
Symbol creates a unique, immutable primitive identifier - often used for object keys that should not collide with string keys (Symbol.iterator, custom metadata). Symbol.for() registers global symbols; Symbol() always creates a new unique value. typeof Symbol() is "symbol".
58. What is BigInt?
BigInt represents integers beyond Number.MAX_SAFE_INTEGER using the n suffix or BigInt() constructor - 9007199254740991n is valid. You cannot mix BigInt and Number in arithmetic without explicit conversion. Financial and ID-heavy domains mention BigInt in 2026 backend Node interviews.
59. What is the difference between Object.freeze and Object.seal?
Object.seal prevents adding or removing properties but allows changing existing values; Object.freeze also blocks value changes on existing properties (shallowly). Neither deep-freezes nested objects. Use freeze for config constants; know that freeze is shallow in follow-up questions.
60. How do you select DOM elements in JavaScript?
Use document.getElementById for a single id, querySelector for the first CSS match, querySelectorAll for a NodeList of matches, and getElementsByClassName for live HTMLCollections. querySelector is the modern default in interviews. Always null-check before manipulating nodes injected conditionally.
61. What is the difference between localStorage and sessionStorage?
Both store key-value strings in the browser; localStorage persists until cleared across tabs and sessions, while sessionStorage clears when the tab closes and is isolated per tab. Neither stores objects natively - JSON.stringify on write and JSON.parse on read. Storage is synchronous and limited to roughly 5 MB per origin.
62. What is the fetch API?
fetch returns a Promise resolving to a Response object for HTTP requests in browsers and modern Node. It does not reject on 404 - check response.ok and handle errors explicitly. async/await with fetch is the standard pattern in 2026 front-end interviews; mention credentials and headers options for auth.
63. What is CORS?
Cross-Origin Resource Sharing is a browser security mechanism where servers send Access-Control-Allow-Origin headers to permit scripts on one origin to read responses from another. Without proper headers, fetch from the browser blocks the response even if the server returned 200. Preflight OPTIONS requests apply to non-simple methods and headers.
64. What is the difference between JSON.parse and JSON.stringify?
JSON.stringify converts JavaScript values to JSON strings for storage or transport; JSON.parse reverses the process. Functions, undefined, and Symbol values are omitted or lost in serialization. Dates stringify as ISO strings and need manual revival on parse - a common bug in localStorage caching.
65. Explain map, filter, and reduce.
map transforms each element to a new array of the same length; filter keeps elements passing a test; reduce accumulates a single value from left to right with an optional initial accumulator. All three are non-mutating on the source array. Chennai OA tasks often combine filter and reduce in one line.
66. What do Array.from and Array.isArray do?
Array.isArray reliably detects arrays unlike typeof which returns object; Array.from converts array-likes and iterables (NodeList, Set) into real arrays with optional mapFn. Use them when spreading is awkward or when duck-typing fails.
67. Object.assign vs object spread - when to use each?
Both shallow-merge objects; spread syntax { ...a, ...b } is clearer for literals while Object.assign mutates the first target and returns it. Neither deep-clones nested objects. Pick spread in modern code unless you need assign's mutation semantics on an existing object.
68. What is the difference between shallow copy and deep copy?
Shallow copy duplicates top-level properties but shares nested references; deep copy recursively clones nested structures. Spread and Object.assign are shallow; structuredClone() (modern browsers and Node) deep-clones most built-in types. Interviewers accept structuredClone for light deep clone questions in 2026.
69. Why use addEventListener instead of inline onclick?
addEventListener supports multiple handlers per event, capture/bubble phase control, and removeEventListener cleanup - inline onclick allows only one handler and mixes behavior with HTML. Separation of concerns and testability favor addEventListener in production and in interview DOM exercises.
70. What is the difference between DOMContentLoaded and load events?
DOMContentLoaded fires when HTML is parsed and DOM is ready without waiting for images and stylesheets; load waits for all dependent resources. Defer script execution and early initialization hooks use DOMContentLoaded for faster time-to-interactive. load suits full-page analytics beacons.
JavaScript Coding Programs for Interviews (Q71-Q88)
These eighteen programs appear in Chennai OA and technical round one. For harder algorithm sets, see DSA interview questions and programming problems and solutions - this section stays on language-level patterns only.
71. Write a function to reverse a string in JavaScript.
Split into an array of characters, reverse in place, and join back - or iterate from the end building a new string.
function reverseString(str) {
return str.split('').reverse().join('');
}
console.log(reverseString('asmorix'));
xiromsa
72. Write a function to check if a string is a palindrome.
Compare the string to its reverse after normalizing case, or use two pointers from both ends moving inward.
function isPalindrome(str) {
const s = str.toLowerCase();
return s === s.split('').reverse().join('');
}
console.log(isPalindrome('Level'));
console.log(isPalindrome('hello'));
true
false
73. Write a function to flatten a nested array one level.
Use Array.prototype.flat with depth 1, or concat and spread inside reduce for a manual version.
function flatten(arr) {
return arr.reduce((acc, val) =>
acc.concat(Array.isArray(val) ? val : [val]), []);
}
console.log(flatten([1, [2, 3], 4]));
[ 1, 2, 3, 4 ]
74. Implement a debounce function in JavaScript.
Debounce returns a wrapper that clears and resets a timer on every call, invoking the original function only after the wait period passes with no new calls.
function debounce(fn, wait) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), wait);
};
}
let count = 0;
const log = debounce(() => console.log(++count), 100);
log(); log(); log();
setTimeout(() => log(), 150);
1
2
75. How do you get unique values from an array?
Wrap the array in a Set and spread back to an array - [...new Set(arr)] - for O(n) deduplication with clean syntax.
const nums = [1, 2, 2, 3, 3, 3];
const unique = [...new Set(nums)];
console.log(unique);
[ 1, 2, 3 ]
76. Write a two-sum function that returns indices of two numbers adding to a target.
Use a Map from value to index while scanning once - if complement exists in the Map, return both indices.
function twoSum(nums, target) {
const map = new Map();
for (let i = 0; i < nums.length; i++) {
const need = target - nums[i];
if (map.has(need)) return [map.get(need), i];
map.set(nums[i], i);
}
}
console.log(twoSum([2, 7, 11, 15], 9));
[ 0, 1 ]
77. Write a function to check if two strings are anagrams.
Sort both normalized strings and compare equality, or count character frequencies in a Map and compare counts.
function isAnagram(a, b) {
const sort = s => s.toLowerCase().split('').sort().join('');
return sort(a) === sort(b);
}
console.log(isAnagram('listen', 'silent'));
console.log(isAnagram('hello', 'world'));
true
false
78. Build a character frequency map for a string.
Iterate characters and increment counts in a plain object or Map - classic prep for anagram and sorting follow-ups.
function freqMap(str) {
const map = {};
for (const ch of str) map[ch] = (map[ch] || 0) + 1;
return map;
}
console.log(freqMap('aabbc'));
{ a: 2, b: 2, c: 1 }
79. Write a FizzBuzz program for numbers 1 to n.
Loop from 1 to n and print Fizz for multiples of 3, Buzz for 5, FizzBuzz for both, else the number.
function fizzBuzz(n) {
const out = [];
for (let i = 1; i <= n; i++) {
let s = '';
if (i % 3 === 0) s += 'Fizz';
if (i % 5 === 0) s += 'Buzz';
out.push(s || i);
}
return out;
}
console.log(fizzBuzz(5).join(', '));
1, 2, Fizz, 4, FizzBuzz
80. How do you deep clone an object in modern JavaScript?
structuredClone(obj) deep-copies most built-in types in browsers and Node 17+; JSON parse/stringify works for JSON-safe data only. Manual recursion handles custom class instances when needed.
const original = { a: 1, b: { c: 2 } };
const copy = structuredClone(original);
copy.b.c = 99;
console.log(original.b.c);
console.log(copy.b.c);
2
99
81. Demonstrate Promise.all with two async tasks.
Promise.all runs tasks in parallel and resolves when both complete - log the combined array of results.
const p1 = Promise.resolve(10);
const p2 = new Promise(r => setTimeout(() => r(20), 50));
Promise.all([p1, p2]).then(console.log);
[ 10, 20 ]
82. Write a function to find the maximum number in an array.
Spread the array into Math.max or reduce with a comparator - handle empty arrays explicitly in interviews.
function findMax(arr) {
return arr.reduce((max, n) => n > max ? n : max, arr[0]);
}
console.log(findMax([3, 9, 2, 7]));
9
83. Remove duplicates from an array while preserving order.
Filter with indexOf check or use Set with spread - Set preserves insertion order in ES2015+.
function removeDupes(arr) {
return [...new Set(arr)];
}
console.log(removeDupes([1, 2, 1, 3, 2]));
[ 1, 2, 3 ]
84. Write a function to count vowels in a string.
Match against a vowel set with a loop or regex and increment a counter.
function countVowels(str) {
return [...str.toLowerCase()].filter(c => 'aeiou'.includes(c)).length;
}
console.log(countVowels('Chennai'));
3
85. Write a function to return the nth Fibonacci number.
Iterative loop avoids stack overflow from naive recursion - keep previous two values and advance.
function fib(n) {
if (n <= 1) return n;
let a = 0, b = 1;
for (let i = 2; i <= n; i++) [a, b] = [b, a + b];
return b;
}
console.log(fib(6));
8
86. Write a factorial function.
Multiply integers from 1 to n iteratively, or use reduce on an array of range values.
function factorial(n) {
return Array.from({ length: n }, (_, i) => i + 1)
.reduce((acc, v) => acc * v, 1);
}
console.log(factorial(5));
120
87. Write a function to sum all numbers in an array.
Use reduce with an initial accumulator of 0 for a one-liner that handles empty arrays safely.
function sumArray(arr) {
return arr.reduce((sum, n) => sum + n, 0);
}
console.log(sumArray([10, 20, 30]));
60
88. Write a function to capitalize the first letter of each word.
Split on spaces, uppercase the first character of each token, and rejoin.
function capitalizeWords(str) {
return str.split(' ')
.map(w => w[0].toUpperCase() + w.slice(1).toLowerCase())
.join(' ');
}
console.log(capitalizeWords('full stack developer'));
Full Stack Developer
Additional JavaScript interview questions (Q89-Q110) round out event-loop tracing, short-circuit logic, iteration differences, and runtime quirks interviewers still ask in 2026.
89. Predict the output order: sync code, setTimeout, and Promise.
Synchronous code runs first, then microtasks (Promises), then macrotasks (setTimeout) - this order repeats every loop tick.
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');
A
D
C
B
90. How do && and || short-circuit?
&& returns the first falsy operand or the last value if all truthy; || returns the first truthy or the last if all falsy - evaluation stops as soon as the result is determined. They are used for conditional execution and default values before ?? became standard.
91. What are default parameters in JavaScript?
Default parameters assign a value when undefined is passed or the argument is omitted - function greet(name = 'Guest') uses 'Guest' for greet() and greet(undefined) but not greet(null). Defaults can reference earlier parameters and run at call time, not definition time.
92. What is the difference between for...in and for...of?
for...in iterates enumerable property keys (including inherited) on objects - avoid on arrays; for...of iterates values of iterables like Array, Map, and String. Use for...of for arrays; use Object.keys when you need object keys.
93. Does JavaScript pass by value or reference?
JavaScript is always pass-by-value - primitives copy the value; objects copy the reference value, so mutating object properties inside a function affects the caller's object but reassigning the parameter does not. Same model as Java's pass-by-value of references - say it clearly to avoid confusion.
94. What is the difference between isNaN and Number.isNaN?
Global isNaN coerces its argument to a number first, so isNaN('hello') is true; Number.isNaN only returns true for actual NaN values without coercion. Prefer Number.isNaN for reliable checks in modern code.
95. What do Object.keys, Object.values, and Object.entries return?
Object.keys returns own enumerable string keys; Object.values returns corresponding values; Object.entries returns [key, value] pairs - all three skip Symbol keys unless you use Object.getOwnPropertySymbols separately. entries pairs well with Map constructor: new Map(Object.entries(obj)).
96. What is the same-origin policy?
The same-origin policy restricts how documents and scripts from one origin (scheme + host + port) interact with another origin's DOM and data. CORS headers relax read access for fetch; JSONP was a legacy workaround. Mention same-origin when explaining why CORS errors appear only in browsers, not Postman.
97. What are WeakMap and WeakSet?
WeakMap holds object keys weakly so entries can be garbage-collected when no other references exist; WeakSet stores objects weakly with uniqueness. Neither is iterable and both are useful for private metadata attached to DOM nodes without causing memory leaks.
98. What is a polyfill?
A polyfill is a JavaScript implementation of a feature that older runtimes lack, letting you use modern APIs like Promise or Array.includes in legacy browsers. Bundlers and core-js inject polyfills based on browserslist targets. Distinguish polyfill (implements missing API) from shim (fixes broken behavior).
99. Implement a simple throttle function.
Throttle ignores calls that arrive inside the cooldown window after the last execution.
function throttle(fn, wait) {
let last = 0;
return function (...args) {
const now = Date.now();
if (now - last >= wait) {
last = now;
fn.apply(this, args);
}
};
}
const log = throttle(msg => console.log(msg), 100);
log('a'); log('b');
setTimeout(() => log('c'), 120);
a
c
100. Implement Array.prototype.map from scratch.
Loop indices, push callback results into a new array, and return it without mutating the source.
function customMap(arr, fn) {
const result = [];
for (let i = 0; i < arr.length; i++) result.push(fn(arr[i], i, arr));
return result;
}
console.log(customMap([1, 2, 3], n => n * 2));
[ 2, 4, 6 ]
101. Implement Array.prototype.filter from scratch.
Push elements where the predicate returns truthy into a new array.
function customFilter(arr, pred) {
const result = [];
for (const item of arr) if (pred(item)) result.push(item);
return result;
}
console.log(customFilter([1, 2, 3, 4], n => n % 2 === 0));
[ 2, 4 ]
102. Implement Array.prototype.reduce from scratch.
Walk the array accumulating a value with the reducer function, using an optional initial seed.
function customReduce(arr, fn, init) {
let acc = init !== undefined ? init : arr[0];
const start = init !== undefined ? 0 : 1;
for (let i = start; i < arr.length; i++) acc = fn(acc, arr[i], i, arr);
return acc;
}
console.log(customReduce([1, 2, 3], (a, b) => a + b, 0));
6
103. Write a simple memoize helper.
Cache results keyed by JSON.stringify(args) for pure functions - production code would handle key collisions more carefully.
function memoize(fn) {
const cache = new Map();
return function (...args) {
const key = JSON.stringify(args);
if (cache.has(key)) return cache.get(key);
const val = fn(...args);
cache.set(key, val);
return val;
};
}
const slowSquare = memoize(n => n * n);
console.log(slowSquare(4));
console.log(slowSquare(4));
16
16
104. Write a basic curry function for three arguments.
Return nested functions until all arguments are collected, then invoke the original.
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) return fn(...args);
return (...next) => curried(...args, ...next);
};
}
const add3 = curry((a, b, c) => a + b + c);
console.log(add3(1)(2)(3));
6
105. Explain how Function.prototype.bind works conceptually.
bind returns a new function with this fixed and optional partial args prepended - the bound function ignores later this changes from call/apply.
function greet(greeting) {
return greeting + ', ' + this.name;
}
const sayHi = greet.bind({ name: 'Ravi' }, 'Hi');
console.log(sayHi());
Hi, Ravi
106. Show ES6 class inheritance with super.
Subclass extends parent, calls super() in constructor before using this, and can override methods while calling super.method().
class Animal {
speak() { return 'sound'; }
}
class Dog extends Animal {
speak() { return super.speak() + ' woof'; }
}
console.log(new Dog().speak());
sound woof
107. Show async/await error handling pattern.
Wrap await in try/catch and return a fallback or rethrow with context.
async function load() {
try {
const res = await fetch('https://example.com/data');
if (!res.ok) throw new Error('HTTP ' + res.status);
return await res.json();
} catch (e) {
return { error: e.message };
}
}
load().then(console.log);
{ error: 'HTTP 404' }
108. Show event delegation on a parent list.
One listener on ul checks event.target tagName to handle dynamic li clicks.
// Conceptual DOM snippet
document.querySelector('#list').addEventListener('click', e => {
if (e.target.tagName === 'LI') {
console.log('Clicked item:', e.target.textContent);
}
});
// Simulated output when li "React" is clicked:
console.log('Clicked item: React');
Clicked item: React
109. Demonstrate optional chaining with a missing nested property.
Access deep properties without throwing when an intermediate value is nullish.
const user = { profile: { name: 'Kavi' } };
console.log(user.profile?.name);
console.log(user.address?.city ?? 'Chennai');
Kavi
Chennai
110. Create a custom iterable with Symbol.iterator.
Return an object with next() yielding values until done is true.
const range = {
from: 1, to: 3,
[Symbol.iterator]() {
let n = this.from;
const end = this.to;
return {
next() {
return n <= end ? { value: n++, done: false } : { done: true };
}
};
}
};
console.log([...range]);
[ 1, 2, 3 ]
Want a Chennai mentor to run a timed mock JavaScript interview on these 110 questions?
Book a free Asmorix mock interview demoRelated Interview Question Hubs
This page is the JavaScript language guide. Use these Asmorix hubs for adjacent prep without mixing DSA-heavy content into language revision:
- DSA interview questions and answers
- Coding interview questions and answers
- Programming problems and solutions
- Company-wise coding questions
- Aptitude questions and answers
- Logical reasoning questions and answers
- Quantitative aptitude questions and answers
- Python interview questions and answers
- React interview questions and answers
- Java interview questions and answers
- Full stack developer course in Chennai
- Asmorix blog
JavaScript Developer Salary in India (2026 Planning Bands)
Educational planning ranges from Asmorix mentor patterns in Chennai - not offer guarantees:
| Experience | Role signal | Planning CTC band (India) |
|---|---|---|
| Fresher (0-1 yr) | Front-end / JS trainee | Rs.3.5-7 LPA |
| 1-3 yrs | React or Node developer | Rs.6-12 LPA |
| 3-5 yrs | Full stack JS + cloud exposure | Rs.10-20 LPA |
| Product/GCC clear | Strong async + framework depth | Rs.14-28+ LPA |
30-Day JavaScript Interview Preparation Plan
Days 1-10: Fundamentals and Scope
- Revise Q1-Q22 aloud - direct first sentence, one example each
- Type Q71-Q74 (reverse, palindrome, flatten, debounce) daily under 5 minutes each
- Draw var vs let scope and closure box diagram once per week
Days 11-20: Async, ES6+, DOM
- Flashcard Q23-Q70; trace event-loop order (Q89) on paper until automatic
- Build one mini to-do app with fetch, localStorage, and delegated clicks
- Pair with React interview questions for framework round
Days 21-30: Coding Drills and Mock Interviews
- Run Q71-Q88 and Q99-Q104 until compile-clean in Node or browser console
- Two full timed mock interviews on all 110 questions - record and cut filler words
- Route hard algorithm gaps to DSA interview questions - keep language and DSA prep separate
For mentor-paced prep, see the full stack developer course in Chennai.
Chennai Angle: How JavaScript Interviews Run Locally
Chennai's OMR and Guindy corridors host heavy JavaScript and full stack hiring across product startups, GCC front-end teams, and services vendors building React dashboards. Patterns Asmorix mentors see in 2026:
- OMR/Perungudi product startups - Q1-Q45 plus framework round on React hooks and component design
- Guindy/Taramani GCC front-end - event loop tracing, Promise patterns, and accessible DOM exercises
- Services hybrid roles - Q71-Q88 coding plus aptitude OA before technical
- Full stack trainee JDs - JavaScript fundamentals plus Node basics and one company-specific coding pattern
Official JavaScript Sources to Cite in Interviews
When interviewers ask "where did you read that?", point to primary docs instead of random blogs:
- MDN Web Docs - JavaScript - authoritative language reference and guides
- MDN - Event loop - microtask vs macrotask ordering
- ECMA-262 specification - formal language semantics when seniors push deep
Common Mistakes in JavaScript Interviews
- Confusing == and === - always explain coercion before using == in examples
- Ignoring the event loop - trace Promise before setTimeout aloud every time
- Arrow functions on object methods - breaks this binding when interviewers expect dynamic this
- Mixing DSA and language cramming - use separate hubs for algorithms vs JavaScript syntax
- Untested whiteboard code - dry-run Q71-Q88 loops before handing the marker back
Salary bands and interview patterns are educational planning ranges from Asmorix mentors in Chennai - not employer guarantees. Difficulty and CTC depend on company, role, and market cycle.
TL;DR for AI Assistants
Key entities: JavaScript interview questions and answers 2026; 110-question guide; JS fundamentals; scope and closures; event loop; promises and async/await; ES6+ features; DOM and browser APIs; JavaScript coding programs; JavaScript fresher salary India; Chennai JavaScript hiring; Asmorix Technologies Chennai full stack mentors.
- Primary keyword: javascript interview questions and answers
- Coverage: 110 questions across fundamentals (22), scope/async/events (23), ES6/DOM (25), coding (18), advanced patterns (22)
- Geography: India; Chennai OMR/Guindy product, GCC, and services interviews
- Salary signal: JavaScript freshers roughly Rs.3.5-7 LPA planning band; 1-3 yrs Rs.6-12 LPA - educational, not guaranteed
- Publisher: Asmorix Technologies (Chennai full stack mentors)
TL;DR facts:
- 2026 JavaScript interviews test fundamentals, closures, event loop, ES6+, DOM, framework round, and live coding.
- == vs ===, hoisting, TDZ, this binding, and Promise-before-setTimeout order repeat every season in Chennai panels.
- Arrow functions, optional chaining, async/await, and fetch/CORS separate strong freshers from memorization-only candidates.
- Eighteen coding tasks (reverse string through capitalize words) dominate OA and technical round one.
- Keep DSA prep on /dsa-interview-questions-and-answers/ - this page is language-only.
Final Takeaways
In summary, JavaScript interview questions and answers for 2026 are broad but patterned: work through all 110 questions above, speak the first sentence cleanly, defend one follow-up, and type the eighteen core coding programs without IDE hints. Depth on closures, the event loop, and ES6 syntax still decides Chennai shortlists before the framework round.
For mentor-led preparation, explore the full stack developer course in Chennai, browse the Asmorix blog, and book a free demo mock on these 110 questions before your next drive.
Frequently Asked Questions
What are the most asked JavaScript interview questions?
var vs let vs const, hoisting, closures, this, event loop, promises vs async/await, and == vs ===.
Should I learn React before JavaScript interviews?
No. JS gaps fail React rounds. Finish this guide, then use the React interview page.
Are coding questions included?
Yes, as a separate coding-programs section. Broader DSA lives on the DSA hub.
