Guides › TypeScript & Modern JavaScript
JavaScript Interview Questions and Answers: Complete Guide
Prepare for JavaScript interviews with questions on closures, scope, prototypes, promises, async/await, arrays, DOM, and coding problems.
JavaScript Interview Questions and Answers: Complete Guide
1. What Is JavaScript?
JavaScript is a programming language used to create interactive web pages and applications. It runs in browsers and in server-side environments such as Node.js.
JavaScript supports multiple programming styles, including procedural, functional, and object-oriented programming.
2. What Is the Difference Between var, let, and const?
varis function-scoped and can be redeclared.letis block-scoped and can be reassigned.constis block-scoped and cannot be reassigned.
Prefer const by default and use let when reassignment is needed.
3. What Are Primitive and Reference Types?
Primitive values include strings, numbers, booleans, null, undefined, BigInts, and Symbols.
Objects, arrays, and functions are objects.
const first = 10;
const second = first;
The second variable receives the primitive value.
const a = { count: 1 };
const b = a;
b.count = 2;
console.log(a.count); // 2
Both variables refer to the same object.
4. What Is the Difference Between == and ===?
== performs equality comparison with type coercion in many cases. === compares without that coercion.
console.log(5 == "5"); // true
console.log(5 === "5"); // false
Use === by default unless coercion is specifically intended.
5. What Is Hoisting?
Hoisting describes how declarations are processed before code executes.
- Function declarations can generally be called before their declaration.
vardeclarations are initialized toundefined.letandconstremain inaccessible before their initialization.
console.log(value); // undefined
var value = 10;
Accessing a let or const binding before initialization throws a ReferenceError.
6. What Is the Temporal Dead Zone?
The temporal dead zone is the period between entering a scope and initializing a let or const binding.
{
// Accessing value here throws ReferenceError.
let value = 10;
}
It helps prevent accidental access before initialization.
7. What Is Scope?
Scope determines where a variable can be accessed.
Common types include:
- Global scope
- Function scope
- Block scope
- Module scope
let and const use block scope, while var uses function scope.
8. What Is a Closure?
A closure occurs when a function retains access to variables from its surrounding lexical scope.
function createCounter() {
let count = 0;
return function () {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
Closures are useful for private state, callbacks, and function factories.
9. What Is Lexical Scope?
Lexical scope means variable access is determined by where functions and blocks are written in the source code.
const greeting = "Hello";
function sayHello() {
console.log(greeting);
}
The function can access greeting because it is defined in the surrounding scope.
10. What Is this in JavaScript?
this generally depends on how a function is called.
- In a method call, it usually refers to the receiver object.
- In a regular function, it depends on the call and execution mode.
- Arrow functions capture
thisfrom their surrounding lexical context. call(),apply(), andbind()can setthisfor regular functions.
const user = {
name: "Aman",
greet() {
return this.name;
}
};
console.log(user.greet());
11. What Are call(), apply(), and bind()?
These methods control the this value of regular functions.
call()invokes the function with individual arguments.apply()invokes the function with arguments supplied as an array-like value.bind()returns a new function with a boundthisvalue and optional preset arguments.
function introduce(city) {
return `${this.name} lives in ${city}`;
}
const user = { name: "Aman" };
console.log(introduce.call(user, "Jaipur"));
const boundIntroduce = introduce.bind(user, "Jaipur");
console.log(boundIntroduce());
12. What Is Prototypal Inheritance?
JavaScript objects can inherit properties and methods through their prototype chain.
const animal = {
speak() {
return "Sound";
}
};
const dog = Object.create(animal);
console.log(dog.speak());
Classes provide a more familiar syntax for working with prototypes.
13. What Is the Difference Between null and undefined?
undefinedoften means a value has not been assigned or a property is missing.nullis commonly used to represent an intentional absence of a value.
let value;
console.log(value); // undefined
const selected = null;
14. What Are Higher-Order Functions?
A higher-order function accepts another function as an argument, returns a function, or both.
function applyOperation(a, b, operation) {
return operation(a, b);
}
console.log(applyOperation(5, 3, (x, y) => x + y));
Array methods such as map(), filter(), and reduce() commonly use callbacks.
15. What Is a Callback Function?
A callback is a function passed to another function to be invoked later or during an operation.
function greet(name, callback) {
callback(`Hello, ${name}`);
}
greet("Aman", message => console.log(message));
Callbacks are used for event handling, array operations, and asynchronous workflows.
16. What Is a Promise?
A Promise represents the eventual completion or failure of an asynchronous operation.
Its states are:
- Pending
- Fulfilled
- Rejected
Promise.resolve("Success")
.then(value => console.log(value))
.catch(error => console.error(error));
17. What Is async/await?
async and await provide syntax for writing Promise-based code in a sequential style.
async function loadData() {
try {
const response = await fetch("/api/data");
if (!response.ok) {
throw new Error("Request failed");
}
return await response.json();
} catch (error) {
console.error(error);
throw error;
}
}
Remember that fetch() normally resolves even when the server returns an HTTP error status. Check response.ok.
18. What Is the Event Loop?
The event loop coordinates JavaScript execution with asynchronous work in the host environment.
A simplified explanation:
- Synchronous JavaScript runs on the current call stack.
- Asynchronous operations are handled by the runtime or host environment.
- Promise reactions are scheduled as microtasks.
- Tasks such as timer callbacks are processed through task queues.
- The runtime processes queued work when the current stack is clear.
The exact scheduling behavior also depends on the host environment.
19. What Is the Difference Between Microtasks and Tasks?
Promise reactions use the microtask queue. Timer callbacks such as setTimeout() are typically scheduled as tasks.
console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("D");
Typical browser output:
A
D
C
B
A zero-millisecond timer does not mean that its callback runs immediately.
20. What Is Destructuring?
Destructuring extracts values from arrays and properties from objects.
const user = { name: "Aman", age: 21 };
const { name, age } = user;
const numbers = [10, 20];
const [first, second] = numbers;
21. What Are Spread and Rest Operators?
Both use ....
Spread expands values:
const numbers = [1, 2];
const combined = [...numbers, 3, 4];
Rest collects values:
function total(...numbers) {
return numbers.reduce((sum, number) => sum + number, 0);
}
Spread creates shallow copies, not deep copies.
22. What Is the Difference Between map(), filter(), and reduce()?
map()transforms each item.filter()selects matching items.reduce()combines items into a single result.
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(n => n * 2);
const even = numbers.filter(n => n % 2 === 0);
const sum = numbers.reduce((total, n) => total + n, 0);
23. What Is Event Delegation?
Event delegation uses a listener on a parent element to handle events from its descendants, often through event bubbling.
document.querySelector("#list").addEventListener("click", event => {
const item = event.target.closest("li");
if (item && event.currentTarget.contains(item)) {
console.log(item.textContent);
}
});
It can simplify handling dynamically added elements.
24. What Is Debouncing?
Debouncing delays a function until a specified period has passed without another call.
It is useful for search inputs and resize handlers.
function debounce(callback, delay) {
let timeoutId;
return (...args) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
callback(...args);
}, delay);
};
}
In production code, also consider cancellation and component cleanup.
25. What Is Throttling?
Throttling limits how frequently a function can run over time.
It can be useful for scroll and pointer events. Debouncing waits for activity to stop; throttling limits execution frequency while activity continues.
26. What Is the Difference Between localStorage and sessionStorage?
Both store string data in the browser.
localStoragepersists across browser sessions until cleared.sessionStorageis scoped to a page session and is generally cleared when that tab session ends.
Neither should be treated as a secure storage location for sensitive secrets. Data may be accessible to JavaScript running on the same origin.
27. What Is JSON?
JSON is a text format for exchanging structured data.
const user = { name: "Aman", age: 21 };
const json = JSON.stringify(user);
const parsed = JSON.parse(json);
JSON.parse() throws for invalid JSON, and JSON does not preserve all JavaScript types.
28. What Is Strict Mode?
Strict mode enables stricter parsing and runtime behavior for certain JavaScript mistakes.
"use strict";
ES modules and class bodies are strict by default.
Strict mode can prevent some silent errors, but it does not replace linting, testing, or security checks.
29. What Is the Difference Between Shallow and Deep Copy?
A shallow copy duplicates the outer structure while nested objects remain shared.
const original = {
name: "Aman",
address: { city: "Jaipur" }
};
const copy = { ...original };
copy.address.city = "Delhi";
console.log(original.address.city); // Delhi
For supported data, structuredClone() can create a deeper copy:
const deepCopy = structuredClone(original);
Choose a copying strategy that matches the data type and application requirements.
30. What Are ES Modules?
ES modules provide standardized import and export syntax.
// math.js
export const add = (a, b) => a + b;
// app.js
import { add } from "./math.js";
console.log(add(2, 3));
Modules help organize code and define explicit dependencies.
31. What Is the Difference Between Synchronous and Asynchronous Code?
Synchronous operations run in sequence and block further execution on the same thread until they complete.
Asynchronous operations allow the runtime to continue executing other work while waiting for an operation to finish.
Promises, timers, and many network operations use asynchronous APIs.
32. What Is Garbage Collection?
Garbage collection automatically reclaims memory used by objects that are no longer reachable.
Developers should avoid unnecessary references, clean up subscriptions and listeners, and investigate memory leaks with runtime tools.
JavaScript does not guarantee immediate reclamation of a particular object.
33. What Is CORS?
Cross-Origin Resource Sharing is a browser security mechanism that controls whether a webpage can access resources from another origin.
The server uses HTTP headers to specify which cross-origin requests are allowed.
CORS is not a substitute for authentication or authorization, and frontend code cannot simply bypass the browser's policy.
34. How Can JavaScript Performance Be Improved?
- Measure performance before changing code.
- Avoid unnecessary DOM work.
- Reduce oversized bundles.
- Load noncritical resources when appropriate.
- Cache appropriate data.
- Use pagination or virtualization for large lists.
- Avoid repeated expensive computations.
- Remove memory leaks.
- Optimize network requests.
- Use browser performance tools.
35. JavaScript Coding Interview Problems
Problem 1: Reverse a String
function reverseString(value) {
return [...value].reverse().join("");
}
console.log(reverseString("Codify"));
This handles Unicode code points better than indexing UTF-16 code units, but it does not fully handle every grapheme cluster, such as all combined emoji sequences.
Problem 2: Check for a Palindrome
function isPalindrome(value) {
const normalized = value
.toLowerCase()
.replace(/[^a-z0-9]/g, "");
return normalized === [...normalized].reverse().join("");
}
This example uses an English-letter and digit normalization rule. Other languages require an appropriate Unicode-aware strategy.
Problem 3: Find the Largest Number
function findLargest(numbers) {
if (numbers.length === 0) {
throw new Error("Array cannot be empty");
}
return Math.max(...numbers);
}
For very large arrays, consider a loop to avoid spreading too many arguments.
Problem 4: Remove Duplicates
function uniqueValues(values) {
return [...new Set(values)];
}
Problem 5: Count Character Frequency
function countCharacters(value) {
const frequency = {};
for (const character of value) {
frequency[character] = (frequency[character] ?? 0) + 1;
}
return frequency;
}
For arbitrary untrusted keys, a Map or an object with a null prototype may be a better choice.
Problem 6: FizzBuzz
function fizzBuzz(limit) {
const result = [];
for (let i = 1; i <= limit; i++) {
if (i % 15 === 0) result.push("FizzBuzz");
else if (i % 3 === 0) result.push("Fizz");
else if (i % 5 === 0) result.push("Buzz");
else result.push(String(i));
}
return result;
}
Problem 7: Flatten a Nested Array
const nested = [1, [2, [3, 4]]];
const flattened = nested.flat(Infinity);
console.log(flattened);
Problem 8: Find the Missing Number
Assume an array contains unique integers from 1 through n with one missing.
function findMissing(numbers, n) {
const expected = (n * (n + 1)) / 2;
const actual = numbers.reduce((sum, number) => sum + number, 0);
return expected - actual;
}
This arithmetic approach assumes the stated input constraints and safe numeric values.
36. Interview Preparation Strategy
Beginner Level
Focus on variables, types, scope, functions, arrays, objects, and basic coding problems.
Intermediate Level
Practice closures, prototypes, array methods, asynchronous code, DOM, and event handling.
Advanced Level
Study the event loop, performance, module design, memory behavior, security, testing, and architecture.
Practice Routine
- Explain each concept in your own words.
- Write a small example without looking at notes.
- Predict the output of tricky code.
- Solve coding problems with edge cases.
- Explain time and space complexity.
- Build a project using the concepts.
- Review mistakes and improve your explanation.
37. Final Checklist
- Explain scope, hoisting, and closures.
- Understand
thisand prototypes. - Use array and object methods.
- Explain Promises and async/await.
- Understand event-loop scheduling.
- Work with DOM events and delegation.
- Understand browser storage and CORS.
- Solve common coding problems.
- Write tests and handle errors.
- Discuss performance and security trade-offs.
Conclusion
Strong JavaScript interview preparation requires more than memorizing definitions. Learn how the language behaves, write code regularly, explain trade-offs, and test your solutions with edge cases.
More guides
- How to Use Codify: A 7-Day Start Plan — New here? Pick a roadmap, make a study plan, start the DSA sheet, revise with notes, practise for placements and test yourself — one step a day, then a daily routine.
- Infosys Preparation Guide: Online Test, Pseudocode and Interview — Roles (SE, DSE, SP), what each section of the Infosys online test checks, how to crack pseudocode and reasoning, a 4-week plan and the interview.
- Wipro Elite NLTH Preparation: Aptitude, Essay and Coding — The Wipro fresher test round by round — quant, logical and verbal, the written essay, two coding problems — plus a 3-week plan and interview tips.
- Accenture Preparation Guide: Cognitive, Technical, Coding and Communication — Every Accenture round explained — cognitive, MS Office/networking/cloud technical MCQs, pseudocode, coding and the spoken-English test — with a 4-week plan.