π JavaScript Interview Questions with Answers β Part 5
41. How do arrays work in JavaScript?
An array is an ordered collection of values. JS arrays can hold different data types and use zero-based indexing.
Example:
Important Points:
β’ Index starts at 0
β’ Arrays are objects in JavaScript
β’ Arrays can grow or shrink dynamically
β’ Arrays can contain mixed data types
42. What is the difference between map() and forEach()?
Both iterate over an array, but used differently.
map()
Creates and returns a new array.
forEach()
Executes a function for each element but does not return a new array.
Key Difference:
β’ map(): Returns a new array. Used for transformation. Can be chained.
β’ forEach(): Returns undefined. Used for side effects.
43. What is filter()?
Creates a new array with elements that pass a condition. Original array is not modified.
Example:
44. What is reduce()?
Processes an array and produces a single accumulated value.
Example:
Common Uses: Calculate totals, averages, count items, group data, build objects.
Interview Tip: Understand the accumulator and current value arguments.
45. What is find()?
Returns the first element that satisfies a condition. Returns undefined if none match.
Example:
find() vs filter(): find = first match, filter = all matches.
46. What is findIndex()?
Returns the index of the first element that satisfies a condition. Returns -1 if none match.
Example:
47. What is some()?
Checks if at least one element satisfies a condition. Returns Boolean.
Example:
48. What is every()?
Checks if all elements satisfy a condition. Returns Boolean.
Example:
some() vs every(): some = at least one, every = all.
49. What is the difference between slice() and splice()?
slice()
Returns a portion without modifying the original.
splice()
Adds, removes, or replaces elements and modifies the original.
41. How do arrays work in JavaScript?
An array is an ordered collection of values. JS arrays can hold different data types and use zero-based indexing.
Example:
const items = ["Apple", 25, true];
console.log(items[0]); // Apple
console.log(items.length); // 3
Important Points:
β’ Index starts at 0
β’ Arrays are objects in JavaScript
β’ Arrays can grow or shrink dynamically
β’ Arrays can contain mixed data types
42. What is the difference between map() and forEach()?
Both iterate over an array, but used differently.
map()
Creates and returns a new array.
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2); // [2, 4, 6]
forEach()
Executes a function for each element but does not return a new array.
numbers.forEach(num => console.log(num * 2));
Key Difference:
β’ map(): Returns a new array. Used for transformation. Can be chained.
β’ forEach(): Returns undefined. Used for side effects.
43. What is filter()?
Creates a new array with elements that pass a condition. Original array is not modified.
Example:
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0); // [2, 4]
44. What is reduce()?
Processes an array and produces a single accumulated value.
Example:
const numbers = [10, 20, 30];
const total = numbers.reduce((sum, num) => sum + num, 0); // 60
Common Uses: Calculate totals, averages, count items, group data, build objects.
Interview Tip: Understand the accumulator and current value arguments.
45. What is find()?
Returns the first element that satisfies a condition. Returns undefined if none match.
Example:
const numbers = [10, 20, 30, 40];
const result = numbers.find(num => num > 20); // 30
find() vs filter(): find = first match, filter = all matches.
46. What is findIndex()?
Returns the index of the first element that satisfies a condition. Returns -1 if none match.
Example:
const numbers = [10, 20, 30, 40];
const index = numbers.findIndex(num => num > 20); // 2
47. What is some()?
Checks if at least one element satisfies a condition. Returns Boolean.
Example:
const numbers = [1, 3, 5, 8];
const result = numbers.some(num => num % 2 === 0); // true
48. What is every()?
Checks if all elements satisfy a condition. Returns Boolean.
Example:
const numbers = [2, 4, 6, 8];
const result = numbers.every(num => num % 2 === 0); // true
some() vs every(): some = at least one, every = all.
49. What is the difference between slice() and splice()?
slice()
Returns a portion without modifying the original.
const numbers = [1, 2, 3, 4, 5];
const result = numbers.slice(1, 4); // [2, 3, 4]
splice()
Adds, removes, or replaces elements and modifies the original.
const numbers = [1, 2, 3, 4, 5];
numbers.splice(1, 2); // removes 2 elements at index 1
console.log(numbers); // [1, 4, 5]
β€5π2
Key Difference:
β’ slice(): Does not modify original. Extracts elements. Returns copied portion.
β’ splice(): Modifies original. Adds/removes/replaces. Returns removed elements.
50. What are push(), pop(), shift(), and unshift()?
Methods that modify arrays.
β’ push(): Add to END β
β’ pop(): Remove from END β
β’ unshift(): Add to START β
β’ shift(): Remove from START β
Quick Memory Trick:
push/pop = END, unshift/shift = START
β€οΈ Double Tap For Part 6
β’ slice(): Does not modify original. Extracts elements. Returns copied portion.
β’ splice(): Modifies original. Adds/removes/replaces. Returns removed elements.
50. What are push(), pop(), shift(), and unshift()?
Methods that modify arrays.
β’ push(): Add to END β
arr.push(3) β’ pop(): Remove from END β
arr.pop() β’ unshift(): Add to START β
arr.unshift(0) β’ shift(): Remove from START β
arr.shift() Quick Memory Trick:
push/pop = END, unshift/shift = START
β€οΈ Double Tap For Part 6
β€2
β
JavaScript Acronyms You MUST Know π»π₯
JS β JavaScript
ES β ECMAScript
DOM β Document Object Model
BOM β Browser Object Model
JSON β JavaScript Object Notation
AJAX β Asynchronous JavaScript And XML
API β Application Programming Interface
SPA β Single Page Application
MPA β Multi Page Application
SSR β Server Side Rendering
CSR β Client Side Rendering
TS β TypeScript
NPM β Node Package Manager
NPX β Node Package Execute
CDN β Content Delivery Network
IIFE β Immediately Invoked Function Expression
HOF β Higher Order Function
MVC β Model View Controller
MVVM β Model View ViewModel
V8 β Google JavaScript Engine
REPL β Read Evaluate Print Loop
CORS β Cross Origin Resource Sharing
JWT β JSON Web Token
SSE β Server Sent Events
WS β WebSocket
π¬ Double Tap β₯οΈ For More π
JS β JavaScript
ES β ECMAScript
DOM β Document Object Model
BOM β Browser Object Model
JSON β JavaScript Object Notation
AJAX β Asynchronous JavaScript And XML
API β Application Programming Interface
SPA β Single Page Application
MPA β Multi Page Application
SSR β Server Side Rendering
CSR β Client Side Rendering
TS β TypeScript
NPM β Node Package Manager
NPX β Node Package Execute
CDN β Content Delivery Network
IIFE β Immediately Invoked Function Expression
HOF β Higher Order Function
MVC β Model View Controller
MVVM β Model View ViewModel
V8 β Google JavaScript Engine
REPL β Read Evaluate Print Loop
CORS β Cross Origin Resource Sharing
JWT β JSON Web Token
SSE β Server Sent Events
WS β WebSocket
π¬ Double Tap β₯οΈ For More π
β€14π₯4
π Full Stack Projects You Should Build (With Source Code)
1οΈβ£ AI SaaS Tool
Learn authentication, subscriptions, APIs & AI integration.
π Source Code: https://github.com/ayusshrathore/ai-saas
2οΈβ£ Real-Time Collaborative Code Editor
Just like Google Docs but for coding. Multiple users can edit code simultaneously.
π Source Code: https://github.com/Mohitur669/Realtime-Collaborative-Code-Editor
3οΈβ£ Trading Simulator
A virtual stock trading platform to practice trading strategies.
π Source Code: https://github.com/nikolatechie/trading-simulator
4οΈβ£ Microservices E-Commerce Platform
Learn scalable architecture using microservices, APIs, and backend systems.
π Source Code: https://github.com/ShahandFahad/E-Commerce
5οΈβ£ Real-Time Chat Application
Build a WhatsApp-like chat app with real-time messaging.
π Tutorial + Code: https://youtu.be/B_l8nD-bvI0?si=M4N5p1wiPiBW-XA8
6οΈβ£ Developer Portfolio SaaS
Create a platform where developers can generate their own portfolio websites.
π Source Code: https://github.com/akhilub/portfolio-saas
7οΈβ£ Job Referral Platform
A platform where users can request and provide job referrals.
π Source Code: https://github.com/RutikKulkarni/ReferralNetworkHub
8οΈβ£ Food Delivery App
Build your own Swiggy/Zomato-like full stack application.
π Source Code: https://github.com/Mshandev/Food-Delivery
9οΈβ£ Ride Sharing App
Learn how ride booking systems like Uber work.
π Source Code: https://github.com/codinggita/ride_share
π Video Streaming Platform
Build your own YouTube-like video streaming platform.
π Source Code: https://github.com/soumanpaul/Video-streaming-web-app
β¨ Donβt forget to react to this message for more awesome content like this! π
π Thank you all for joining! π
1οΈβ£ AI SaaS Tool
Learn authentication, subscriptions, APIs & AI integration.
π Source Code: https://github.com/ayusshrathore/ai-saas
2οΈβ£ Real-Time Collaborative Code Editor
Just like Google Docs but for coding. Multiple users can edit code simultaneously.
π Source Code: https://github.com/Mohitur669/Realtime-Collaborative-Code-Editor
3οΈβ£ Trading Simulator
A virtual stock trading platform to practice trading strategies.
π Source Code: https://github.com/nikolatechie/trading-simulator
4οΈβ£ Microservices E-Commerce Platform
Learn scalable architecture using microservices, APIs, and backend systems.
π Source Code: https://github.com/ShahandFahad/E-Commerce
5οΈβ£ Real-Time Chat Application
Build a WhatsApp-like chat app with real-time messaging.
π Tutorial + Code: https://youtu.be/B_l8nD-bvI0?si=M4N5p1wiPiBW-XA8
6οΈβ£ Developer Portfolio SaaS
Create a platform where developers can generate their own portfolio websites.
π Source Code: https://github.com/akhilub/portfolio-saas
7οΈβ£ Job Referral Platform
A platform where users can request and provide job referrals.
π Source Code: https://github.com/RutikKulkarni/ReferralNetworkHub
8οΈβ£ Food Delivery App
Build your own Swiggy/Zomato-like full stack application.
π Source Code: https://github.com/Mshandev/Food-Delivery
9οΈβ£ Ride Sharing App
Learn how ride booking systems like Uber work.
π Source Code: https://github.com/codinggita/ride_share
π Video Streaming Platform
Build your own YouTube-like video streaming platform.
π Source Code: https://github.com/soumanpaul/Video-streaming-web-app
β¨ Donβt forget to react to this message for more awesome content like this! π
π Thank you all for joining! π
β€9π₯1
π JavaScript Interview Questions with Answers β Part 6
51. How do you sort arrays?
The
Sorting Strings
Output:
Sorting Numbers
By default,
Output:
Descending Order:
Interview Tip:
52. What is array destructuring?
Array destructuring allows you to extract values from an array and assign them to variables.
Example:
Output:
10
20
30
Skipping Values:
Output:
10 30
Default Values:
Output:
10 20
53. What are Sets?
A
Duplicate values are automatically removed.
Example:
The Set contains:
Common Methods:
Convert Set to Array:
54. What are Maps?
A
Unlike regular objects, a
Example:
Output:
Deepak
Common Methods:
Example:
Output:
true
Map vs Object:
Map
β’ Any value can be a key
β’ Has size property
β’ Built-in methods
β’ Designed for key-value collections
Object
β’ Keys are primarily strings/symbols
β’ No built-in size
β’ Different object APIs
β’ General-purpose objects
55. What are Symbols?
Example:
Output:
false
Even though both have the same description, each
Using Symbol as an Object Property:
Common Use:
56. What are generators?
Generators are special functions that can pause and resume execution.
They are created using
Example:
51. How do you sort arrays?
The
sort() method is used to sort the elements of an array.Sorting Strings
const fruits = ["Banana", "Apple", "Mango"];
fruits.sort();
console.log(fruits);
Output:
["Apple", "Banana", "Mango"]Sorting Numbers
By default,
sort() converts elements to strings, so a comparison function should be used for numbers.const numbers = [10, 5, 20, 2];
numbers.sort((a, b) => a - b);
console.log(numbers);
Output:
[2, 5, 10, 20]Descending Order:
numbers.sort((a, b) => b - a);
Interview Tip:
sort() mutates the original array.52. What is array destructuring?
Array destructuring allows you to extract values from an array and assign them to variables.
Example:
const numbers = [10, 20, 30];
const [a, b, c] = numbers;
console.log(a);
console.log(b);
console.log(c);
Output:
10
20
30
Skipping Values:
const numbers = [10, 20, 30];
const [first, , third] = numbers;
console.log(first, third);
Output:
10 30
Default Values:
const numbers = [10];
const [a, b = 20] = numbers;
console.log(a, b);
Output:
10 20
53. What are Sets?
A
Set is a collection of unique values.Duplicate values are automatically removed.
Example:
const numbers = new Set([1, 2, 2, 3, 3]);
console.log(numbers);
The Set contains:
{1, 2, 3}Common Methods:
const numbers = new Set();
numbers.add(10);
numbers.add(20);
console.log(numbers.has(10));
numbers.delete(20);
Convert Set to Array:
const arr = [...numbers];
54. What are Maps?
A
Map is a collection of key-value pairs.Unlike regular objects, a
Map can use different data types as keys.Example:
const users = new Map();
users.set(1, "Deepak");
users.set(2, "John");
console.log(users.get(1));
Output:
Deepak
Common Methods:
users.set(key, value);
users.get(key);
users.has(key);
users.delete(key);
users.clear();
Example:
console.log(users.has(2));
Output:
true
Map vs Object:
Map
β’ Any value can be a key
β’ Has size property
β’ Built-in methods
β’ Designed for key-value collections
Object
β’ Keys are primarily strings/symbols
β’ No built-in size
β’ Different object APIs
β’ General-purpose objects
55. What are Symbols?
Symbol is a primitive data type used to create unique identifiers.Example:
const id1 = Symbol("id");
const id2 = Symbol("id");
console.log(id1 === id2);Output:
false
Even though both have the same description, each
Symbol is unique.Using Symbol as an Object Property:
const id = Symbol("id");
const user = {
name: "Deepak",
[id]: 101
};
console.log(user[id]);Common Use:
Symbols are useful when you need unique property keys that are unlikely to conflict with other properties.56. What are generators?
Generators are special functions that can pause and resume execution.
They are created using
function* and use the yield keyword.Example:
β€3
function* numbers() {
yield 1;
yield 2;
yield 3;
}
const generator = numbers();
console.log(generator.next());
console.log(generator.next());Output:
{ value: 1, done: false }{ value: 2, done: false }After all values are consumed:
{ value: 3, done: false }{ value: undefined, done: true }Important:
Calling a generator function doesn't immediately execute its body. It returns a generator object.
57. What are iterators?
An iterator is an object that provides a way to access values one at a time using the
next() method.Example:
const numbers = [10, 20, 30];
const iterator = numbers[Symbol.iterator]();
console.log(iterator.next());
console.log(iterator.next());
Output:
{ value: 10, done: false }{ value: 20, done: false }The iterator eventually returns:
{ value: undefined, done: true }Common Iterables:
β’ Arrays
β’ Strings
β’ Maps
β’ Sets
That's why they can be used with
for...of.for (const number of numbers) {
console.log(number);
}58. What is destructuring assignment?
Destructuring assignment allows values to be extracted from arrays or objects and assigned to variables.
Object Example:
const user = {
name: "Deepak",
age: 25
};
const { name, age } = user;Array Example:
const numbers = [10, 20];
const [a, b] = numbers;
Why Use It?
It makes code shorter and easier to read, especially when working with API responses and function parameters.
59. What is dynamic import?
Dynamic import allows a JavaScript module to be loaded when it is needed, instead of loading it immediately.
It uses:
import()Example:
async function loadModule() {
const module = await import("./math.js");
console.log(module.add(10, 20));
}Important:
Unlike a static import:
import { add } from "./math.js";dynamic imports return a Promise.
Common Uses:
β’ Lazy loading
β’ Code splitting
β’ Loading features only when required
β’ Improving initial page performance
60. What are ES6 modules?
ES6 modules provide a standard way to divide JavaScript applications into separate files.
They use
export and import.Export:
// math.js
export function add(a, b) {
return a + b;
}
Import:
// app.js
import { add } from "./math.js";
console.log(add(10, 20));
Default Export:
export default function greet() {
console.log("Hello");
}Import:
import greet from "./greet.js";
Benefits:
β Code organization
β Reusability
β Encapsulation
β Easier maintenance
β Avoids unnecessary global variables
β€οΈ Double Tap For Part 7
β€2π1
π JavaScript Interview Questions with Answers β Part 8
71. What is fetch()?
It returns a Promise.
Example:
Using async/await:
Interview Tip:
72. What is AJAX?
AJAX stands for Asynchronous JavaScript and XML.
It is a technique for communicating with a server and updating parts of a webpage without reloading the entire page.
Despite the name, AJAX doesn't require XML. Modern applications commonly exchange JSON.
Example:
A webpage can request:
Modern Approach:
Today,
73. What are Web APIs?
Web APIs are browser-provided interfaces that allow JavaScript to interact with browser features and the environment.
Examples include:
β’
β’
β’ DOM APIs
β’ Local Storage
β’ Geolocation API
β’ Web Workers
β’ Clipboard API
Example:
The timer functionality is provided by the host environment, such as a browser or Node.js runtime, rather than being part of the JavaScript language itself.
Interview Tip:
Don't confuse JavaScript language features with browser Web APIs.
74. What is setTimeout()?
Example:
The callback becomes eligible to run after approximately 2 seconds.
Important:
The delay is not a guarantee that the function executes exactly at that time.
It may execute later if the JavaScript runtime is busy.
75. What is setInterval()?
Example:
The callback runs approximately every second until the interval is cancelled.
Stop It:
Common Uses:
β’ Timers
β’ Polling
β’ Repeated UI updates
β’ Periodic tasks
76. What is clearTimeout()?
Example:
The callback will not execute because the timeout was cancelled before it became eligible to run.
Common Use:
Useful when you need to cancel a scheduled action.
77. What is clearInterval()?
Example:
71. What is fetch()?
fetch() is a modern JavaScript API used to make HTTP requests and communicate with servers.It returns a Promise.
Example:
fetch("https://api.example.com/users")
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.log(error);
});Using async/await:
async function getUsers() {
try {
const response = await fetch(
"https://api.example.com/users"
);
const data = await response.json();
console.log(data);
} catch (error) {
console.log(error);
}
}Interview Tip:
fetch() rejects its Promise for network-level failures, but an HTTP error such as 404 or 500 does not automatically reject it. You should check response.ok.72. What is AJAX?
AJAX stands for Asynchronous JavaScript and XML.
It is a technique for communicating with a server and updating parts of a webpage without reloading the entire page.
Despite the name, AJAX doesn't require XML. Modern applications commonly exchange JSON.
Example:
A webpage can request:
User data β Server
β
JSON
β
JavaScript
β
Update webpage
Modern Approach:
Today,
fetch() is commonly used instead of the older XMLHttpRequest API.73. What are Web APIs?
Web APIs are browser-provided interfaces that allow JavaScript to interact with browser features and the environment.
Examples include:
β’
fetch()β’
setTimeout()β’ DOM APIs
β’ Local Storage
β’ Geolocation API
β’ Web Workers
β’ Clipboard API
Example:
setTimeout(() => {
console.log("Hello");
}, 1000);The timer functionality is provided by the host environment, such as a browser or Node.js runtime, rather than being part of the JavaScript language itself.
Interview Tip:
Don't confuse JavaScript language features with browser Web APIs.
74. What is setTimeout()?
setTimeout() schedules a function to run after a specified delay.Example:
setTimeout(() => {
console.log("Hello");
}, 2000);The callback becomes eligible to run after approximately 2 seconds.
Important:
The delay is not a guarantee that the function executes exactly at that time.
It may execute later if the JavaScript runtime is busy.
75. What is setInterval()?
setInterval() repeatedly schedules a function at approximately specified intervals.Example:
const interval = setInterval(() => {
console.log("Running...");
}, 1000);The callback runs approximately every second until the interval is cancelled.
Stop It:
clearInterval(interval);
Common Uses:
β’ Timers
β’ Polling
β’ Repeated UI updates
β’ Periodic tasks
76. What is clearTimeout()?
clearTimeout() cancels a timeout that was previously scheduled using setTimeout().Example:
const timer = setTimeout(() => {
console.log("Hello");
}, 5000);
clearTimeout(timer);The callback will not execute because the timeout was cancelled before it became eligible to run.
Common Use:
Useful when you need to cancel a scheduled action.
77. What is clearInterval()?
clearInterval() stops an interval created using setInterval().Example:
let count = 0;
const interval = setInterval(() => {
count++;
console.log(count);
if (count === 5) {
clearInterval(interval);
}
}, 1000);
Output:
1
2
3
4
5
After 5, the interval is stopped.
78. What is callback hell?
Callback hell occurs when multiple asynchronous operations are nested inside one another, making code difficult to read and maintain.
Example:
getUser(user => {
getOrders(user, orders => {
getPayment(orders, payment => {
processPayment(payment, result => {
console.log(result);
});
});
});
});This creates deeply nested code.
Problems:
β Difficult to read
β Difficult to debug
β Difficult to maintain
β Error handling becomes complicated
79. How do you avoid callback hell?
Several approaches can make asynchronous code cleaner.
1. Use Promises
getUser()
.then(getOrders)
.then(getPayment)
.then(processPayment)
.catch(handleError);
2. Use async/await
async function process() {
try {
const user = await getUser();
const orders = await getOrders(user);
const payment = await getPayment(orders);
await processPayment(payment);
} catch (error) {
console.log(error);
}
}3. Break large functions into smaller functions
Instead of putting everything into one deeply nested callback, separate responsibilities into reusable functions.
Interview Tip:
For modern JavaScript, Promises and async/await are the most common solutions.
80. What are microtasks and macrotasks?
This is an important advanced JavaScript interview topic.
The JavaScript runtime has different queues for asynchronous work.
Microtasks
Examples include:
β’ Promise callbacks
β’
queueMicrotask()β’ MutationObserver callbacks in browsers
Macrotasks / Tasks
Common examples include:
β’
setTimeout()β’
setInterval()β’ Some browser events
Example:
console.log("Start");
setTimeout(() => {
console.log("Timeout");
}, 0);
Promise.resolve().then(() => {
console.log("Promise");
});
console.log("End");Output:
Start
End
Promise
Timeout
Why?
After the synchronous code finishes, the runtime processes available microtasks before moving to the next task.
So:
Synchronous code
β
Microtasks
β
Next task / macrotask
β€οΈ Double Tap For Part 9
β€1
π JavaScript Interview Questions with Answers β Part 10
91. What is throttling?
Throttling limits how frequently a function can execute within a given time interval.
Even if an event fires many times, the function is allowed to execute at most once during each interval.
Example:
Common Uses:
β’ Scroll events
β’ Mouse movement
β’ Window resizing
β’ Continuous user interactions
Debounce vs Throttle:
Debounce β Execute after activity stops
Throttle β Execute at controlled intervals
92. What is memoization?
Memoization is an optimization technique where the result of a function is cached so that the same calculation doesn't have to be performed again.
Example:
Example Usage:
The first call performs the calculation.
The second call can use the cached result.
Benefits:
β Faster repeated calculations
β Avoids unnecessary work
Drawback:
β Uses additional memory for cached results.
93. What is currying?
Currying transforms a function that takes multiple arguments into a sequence of functions that each take one argument.
Normal Function:
Curried Function:
Usage:
Output:
Arrow Function Version:
Common Uses:
β’ Functional programming
β’ Creating reusable functions
β’ Partial application
β’ Configuration-based functions
94. What is prototype inheritance?
JavaScript uses objects as the foundation of its inheritance system.
Objects can access properties and methods through their prototype chain.
Example:
Although dog doesn't directly contain speak(), it can access the method through its prototype.
Prototype Chain:
dog
β
animal
β
Object.prototype
β
null
JavaScript searches this chain when a property isn't found directly on the object.
95. What is prototypal inheritance?
Prototypal inheritance is JavaScript's mechanism for allowing one object to inherit behavior from another object through the prototype chain.
Example:
Here:
student has its own study() method.
greet() comes from its prototype, person.
96. What are classes in JavaScript?
Classes provide a cleaner syntax for creating objects and implementing object-oriented programming patterns.
Classes were introduced in ES6.
Example:
91. What is throttling?
Throttling limits how frequently a function can execute within a given time interval.
Even if an event fires many times, the function is allowed to execute at most once during each interval.
Example:
function throttle(callback, delay) {
let lastTime = 0;
return function(...args) {
const now = Date.now();
if (now - lastTime >= delay) {
lastTime = now;
callback.apply(this, args);
}
};
}Common Uses:
β’ Scroll events
β’ Mouse movement
β’ Window resizing
β’ Continuous user interactions
Debounce vs Throttle:
Debounce β Execute after activity stops
Throttle β Execute at controlled intervals
92. What is memoization?
Memoization is an optimization technique where the result of a function is cached so that the same calculation doesn't have to be performed again.
Example:
function memoize(fn) {
const cache = new Map();
return function(n) {
if (cache.has(n)) {
return cache.get(n);
}
const result = fn(n);
cache.set(n, result);
return result;
};
}Example Usage:
function square(n) {
console.log("Calculating...");
return n * n;
}
const memoizedSquare = memoize(square);
console.log(memoizedSquare(5));
console.log(memoizedSquare(5));The first call performs the calculation.
The second call can use the cached result.
Benefits:
β Faster repeated calculations
β Avoids unnecessary work
Drawback:
β Uses additional memory for cached results.
93. What is currying?
Currying transforms a function that takes multiple arguments into a sequence of functions that each take one argument.
Normal Function:
function add(a, b, c) {
return a + b + c;
}
console.log(add(1, 2, 3));Curried Function:
function add(a) {
return function(b) {
return function(c) {
return a + b + c;
};
};
}Usage:
console.log(add(1)(2)(3));
Output:
6
Arrow Function Version:
const add = a => b => c => a + b + c;
Common Uses:
β’ Functional programming
β’ Creating reusable functions
β’ Partial application
β’ Configuration-based functions
94. What is prototype inheritance?
JavaScript uses objects as the foundation of its inheritance system.
Objects can access properties and methods through their prototype chain.
Example:
const animal = {
speak() {
console.log("Animal speaks");
}
};
const dog = Object.create(animal);
dog.speak();Although dog doesn't directly contain speak(), it can access the method through its prototype.
Prototype Chain:
dog
β
animal
β
Object.prototype
β
null
JavaScript searches this chain when a property isn't found directly on the object.
95. What is prototypal inheritance?
Prototypal inheritance is JavaScript's mechanism for allowing one object to inherit behavior from another object through the prototype chain.
Example:
const person = {
greet() {
console.log("Hello");
}
};
const student = Object.create(person);
student.study = function() {
console.log("Studying");
};
student.greet();
student.study();Here:
student has its own study() method.
greet() comes from its prototype, person.
96. What are classes in JavaScript?
Classes provide a cleaner syntax for creating objects and implementing object-oriented programming patterns.
Classes were introduced in ES6.
Example:
β€2
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, I am ${this.name}`);
}
}
const person = new Person("Deepak", 25);
person.greet();Output:
Hello, I am Deepak
Important:
JavaScript classes are built on top of JavaScript's prototype-based inheritance.
Classes Support:
β’ Constructors
β’ Methods
β’ Inheritance
β’ Getters and setters
β’ Static methods
β’ Private fields
97. What is garbage collection?
Garbage collection is the automatic process of identifying and reclaiming memory that is no longer reachable or needed by a JavaScript program.
Developers don't normally manually free JavaScript objects.
Example:
let user = {
name: "Deepak"
};
user = null;If the original object is no longer reachable from the program, it can eventually become eligible for garbage collection.
Important:
Garbage collection timing is determined by the JavaScript engine. You cannot normally force it from standard JavaScript code.
98. How does JavaScript manage memory?
JavaScript automatically manages memory using mechanisms such as:
1. Memory allocation
2. Program execution
3. Garbage collection
Simplified Process:
Create value
β
Memory allocated
β
Program uses value
β
Value becomes unreachable
β
Garbage collector
β
Memory can be reclaimed
What is a Memory Leak?
A memory leak occurs when a program unintentionally keeps references to objects that it no longer needs.
Common Causes:
β’ Unremoved event listeners
β’ Unnecessary global variables
β’ Timers that aren't cleared
β’ Large objects retained in closures
β’ Growing caches without limits
Example:
const cache = [];
function addData(data) {
cache.push(data);
}
If cache keeps growing indefinitely, it can consume increasing amounts of memory.
99. What are CommonJS and ES Modules?
Both are module systems used in JavaScript applications.
CommonJS
Commonly associated with Node.js and uses require() and module.exports.
// math.js
function add(a, b) {
return a + b;
}
module.exports = { add };
Import:
const { add } = require("./math");ES Modules
The standardized JavaScript module system uses import and export.
// math.js
export function add(a, b) {
return a + b;
}
Import:
import { add } from "./math.js";Modern JavaScript development commonly uses ES Modules, while CommonJS remains important when working with existing Node.js projects.
100. What are the latest JavaScript features introduced in ES2025 and beyond?
JavaScript continues to evolve through yearly ECMAScript releases.
For ES2025 (ECMAScript 2025), notable standardized additions include:
π₯ Iterator Helpers
Methods such as:
iterator.map(...)iterator.filter(...)iterator.take(...)allow lazy processing of iterator values.
π₯ Iterator.from()
Allows an object to be converted into an iterator.
const iterator = Iterator.from([1, 2, 3]);
π₯ Set Methods
Modern Set operations include methods such as:
β’
union()β’
intersection()β’
difference()β’
symmetricDifference()Example:
const a = new Set([1, 2, 3]);
const b = new Set([3, 4, 5]);
const result = a.union(b);
console.log(result);
β€2
π₯ Regular Expression Improvements
ES2025 also introduced improvements to regular expressions, including support for enhanced Unicode-related matching capabilities.
π₯ Promise.try()
β οΈ Important Interview Point
JavaScript features are standardized through the ECMAScript specification, and browser/Node.js support can vary by feature and version.
So when discussing "latest JavaScript," distinguish between:
Standardized features
β Officially included in an ECMAScript release.
Proposed features
β Still moving through the TC39 proposal process.
Runtime support
β Whether a particular browser or Node.js version actually supports the feature.
Double Tap β€οΈ For More
ES2025 also introduced improvements to regular expressions, including support for enhanced Unicode-related matching capabilities.
π₯ Promise.try()
Promise.try() provides a convenient way to turn a synchronous function call into a Promise-based operation.Promise.try(() => {
return someFunction();
});β οΈ Important Interview Point
JavaScript features are standardized through the ECMAScript specification, and browser/Node.js support can vary by feature and version.
So when discussing "latest JavaScript," distinguish between:
Standardized features
β Officially included in an ECMAScript release.
Proposed features
β Still moving through the TC39 proposal process.
Runtime support
β Whether a particular browser or Node.js version actually supports the feature.
Double Tap β€οΈ For More
β€2
Free Resources to Learn Each Tech Stack π§ β¨
No excuses. Everything you need is free!
1. Frontend Development
β― freeCodeCamp.org β HTML, CSS, JS
β― MDN Web Docs β Best docs for web tech
β― Frontend Mentor β Real-world challenges
β― CSS Tricks β CSS deep dives
β― YouTube: Kevin Powell, Web Dev Simplified
β
2. Backend Development
β― Node.js Docs
β― Django Girls Tutorial
β― The Odin Project β Full Stack
β― Spring Boot Guides
β― YouTube: Amigoscode, CodeWithHarry (Hindi), Tech With Tim
β
3. Full-Stack Development
β― Full Stack Open β React + Node
β― The Odin Project
β― CS50 Web β Harvardβs free course
β― YouTube: Traversy Media, Clever Programmer, JavaScript Mastery
β
4. Data Analytics
β― Kaggle Learn β Python, SQL, Viz
β― Maven Analytics β Free Power BI/Tableau projects
β― Google Data Analytics Course
β― W3Schools SQL
β― YouTube: Luke Barousse, Alex The Analyst
β
5. Machine Learning
β― Googleβs ML Crash Course
β― fast.ai β Deep learning made easy
β― Kaggle Courses β End-to-end ML
β― Coursera β Andrew Ng
β― YouTube: StatQuest, Krish Naik, Codebasics
β
6. DevOps
β― KodeKloud β Docker, K8s, Ansible
β― Learn Git Branching
β― Katacoda β Interactive Linux & DevOps
β― Roadmap.sh β What to learn
β― YouTube: TechWorld with Nana, Nana Janashia
No excuses. Everything you need is free!
1. Frontend Development
β― freeCodeCamp.org β HTML, CSS, JS
β― MDN Web Docs β Best docs for web tech
β― Frontend Mentor β Real-world challenges
β― CSS Tricks β CSS deep dives
β― YouTube: Kevin Powell, Web Dev Simplified
β
2. Backend Development
β― Node.js Docs
β― Django Girls Tutorial
β― The Odin Project β Full Stack
β― Spring Boot Guides
β― YouTube: Amigoscode, CodeWithHarry (Hindi), Tech With Tim
β
3. Full-Stack Development
β― Full Stack Open β React + Node
β― The Odin Project
β― CS50 Web β Harvardβs free course
β― YouTube: Traversy Media, Clever Programmer, JavaScript Mastery
β
4. Data Analytics
β― Kaggle Learn β Python, SQL, Viz
β― Maven Analytics β Free Power BI/Tableau projects
β― Google Data Analytics Course
β― W3Schools SQL
β― YouTube: Luke Barousse, Alex The Analyst
β
5. Machine Learning
β― Googleβs ML Crash Course
β― fast.ai β Deep learning made easy
β― Kaggle Courses β End-to-end ML
β― Coursera β Andrew Ng
β― YouTube: StatQuest, Krish Naik, Codebasics
β
6. DevOps
β― KodeKloud β Docker, K8s, Ansible
β― Learn Git Branching
β― Katacoda β Interactive Linux & DevOps
β― Roadmap.sh β What to learn
β― YouTube: TechWorld with Nana, Nana Janashia
β€8
π JavaScript Tips β Part 2
1οΈβ£ Use strict mode when appropriate
Strict mode helps catch certain common mistakes and prevents some unsafe behaviors.
2οΈβ£ Use optional chaining for uncertain data
When working with API responses or nested objects, optional chaining can prevent errors when a property doesn't exist.
3οΈβ£ Understand || vs ??
They behave differently when dealing with falsy values.
Use
4οΈβ£ Don't overuse ternary operators
Ternary operators are great for simple conditions.
For complicated logic, a normal
5οΈβ£ Use destructuring when it improves readability
Destructuring can make working with objects and arrays cleaner.
6οΈβ£ Understand spread vs rest
The same
Spread β expands values
Rest β collects values
7οΈβ£ Don't rely on implicit type coercion
JavaScript can automatically convert types, sometimes producing surprising results.
Be explicit when conversion matters.
8οΈβ£ Handle asynchronous errors properly
Don't assume every API request or asynchronous operation will succeed.
9οΈβ£ Don't block the main thread
Heavy calculations or large amounts of synchronous work can make a web application unresponsive.
For expensive tasks, consider:
β’ Breaking work into smaller tasks
β’ Web Workers
β’ Efficient algorithms
β’ Avoiding unnecessary rendering
π Use debounce and throttle appropriately
These techniques are useful when an event fires repeatedly.
Debounce β Run after activity stops.
Throttle β Limit execution to a controlled frequency.
Common use cases: Search inputs, Scrolling, Resizing, Mouse movement
1οΈβ£1οΈβ£ Use const objects carefully
Understanding this distinction is important.
1οΈβ£2οΈβ£ Don't blindly use JSON.parse() and JSON.stringify()
They are useful for JSON data, but they aren't universal deep-copy solutions. They can lose or alter certain JavaScript values and don't preserve all object types.
For structured cloning, consider
1οΈβ£3οΈβ£ Use === consistently
Strict equality makes your comparisons easier to reason about.
1οΈβ£ Use strict mode when appropriate
Strict mode helps catch certain common mistakes and prevents some unsafe behaviors.
"use strict";
2οΈβ£ Use optional chaining for uncertain data
When working with API responses or nested objects, optional chaining can prevent errors when a property doesn't exist.
const user = {};
console.log(user.address?.city);3οΈβ£ Understand || vs ??
They behave differently when dealing with falsy values.
const count = 0;
console.log(count || 10); // 10
console.log(count ?? 10); // 0
Use
?? when 0, false, or an empty string are valid values.4οΈβ£ Don't overuse ternary operators
Ternary operators are great for simple conditions.
const age = 20;
const status = age >= 18 ? "Adult" : "Minor";
For complicated logic, a normal
if...else is usually easier to read.5οΈβ£ Use destructuring when it improves readability
Destructuring can make working with objects and arrays cleaner.
const user = {
name: "Alex",
age: 25
};
const { name, age } = user;6οΈβ£ Understand spread vs rest
The same
... syntax has two different purposes.Spread β expands values
const numbers = [1, 2, 3];
const copy = [...numbers];
Rest β collects values
function sum(...numbers) {
return numbers.length;
}7οΈβ£ Don't rely on implicit type coercion
JavaScript can automatically convert types, sometimes producing surprising results.
console.log("10" + 5); // "105"
console.log("10" - 5); // 5Be explicit when conversion matters.
8οΈβ£ Handle asynchronous errors properly
Don't assume every API request or asynchronous operation will succeed.
async function getData() {
try {
const response = await fetch("/api/data");
const data = await response.json();
return data;
} catch (error) {
console.error("Request failed:", error);
}
}9οΈβ£ Don't block the main thread
Heavy calculations or large amounts of synchronous work can make a web application unresponsive.
For expensive tasks, consider:
β’ Breaking work into smaller tasks
β’ Web Workers
β’ Efficient algorithms
β’ Avoiding unnecessary rendering
π Use debounce and throttle appropriately
These techniques are useful when an event fires repeatedly.
Debounce β Run after activity stops.
Throttle β Limit execution to a controlled frequency.
Common use cases: Search inputs, Scrolling, Resizing, Mouse movement
1οΈβ£1οΈβ£ Use const objects carefully
const prevents reassignment of the variable, but it doesn't make the object immutable.const user = {
name: "Alex"
};
user.name = "Sam"; // AllowedUnderstanding this distinction is important.
1οΈβ£2οΈβ£ Don't blindly use JSON.parse() and JSON.stringify()
They are useful for JSON data, but they aren't universal deep-copy solutions. They can lose or alter certain JavaScript values and don't preserve all object types.
For structured cloning, consider
structuredClone() when appropriate.1οΈβ£3οΈβ£ Use === consistently
Strict equality makes your comparisons easier to reason about.
if (status === "active") {
console.log("User is active");
}β€4
1οΈβ£4οΈβ£ Learn the event loop
Understanding the event loop helps you predict the execution order of: Synchronous code, Promise callbacks, Timers, Events
This is especially important for JavaScript interviews.
1οΈβ£5οΈβ£ Practice reading error messages
Don't immediately search for a solution when your code fails.
First understand: What error occurred β Where did it occur β Why did it occur β How can it be fixed?
π₯ Golden Tip: The faster you become at understanding your own errors, the faster you'll become at solving JavaScript problems.
Double Tap β€οΈ For More Useful Tips
Understanding the event loop helps you predict the execution order of: Synchronous code, Promise callbacks, Timers, Events
This is especially important for JavaScript interviews.
1οΈβ£5οΈβ£ Practice reading error messages
Don't immediately search for a solution when your code fails.
First understand: What error occurred β Where did it occur β Why did it occur β How can it be fixed?
π₯ Golden Tip: The faster you become at understanding your own errors, the faster you'll become at solving JavaScript problems.
Double Tap β€οΈ For More Useful Tips
β€5
π 20 Backend Project Ideas π₯π¨π»βπ»
πΉREST API for a Blog
πΉUser Authentication System
πΉURL Shortener
πΉE-commerce Backend
πΉOnline Banking API
πΉTask Management API
πΉReal-time Chat Backend
πΉFile Upload & Storage API
πΉExpense Tracker API
πΉMovie Database API
πΉFood Delivery Backend
πΉJob Portal Backend
πΉOnline Bookstore API
πΉInventory Management System
πΉPayment Gateway Integration
πΉNotification Service
πΉSocial Media Backend
πΉHospital Management System
πΉEvent Booking API
πΉLearning Management System
β€οΈ React to this message for more coding & project ideas!
πΉREST API for a Blog
πΉUser Authentication System
πΉURL Shortener
πΉE-commerce Backend
πΉOnline Banking API
πΉTask Management API
πΉReal-time Chat Backend
πΉFile Upload & Storage API
πΉExpense Tracker API
πΉMovie Database API
πΉFood Delivery Backend
πΉJob Portal Backend
πΉOnline Bookstore API
πΉInventory Management System
πΉPayment Gateway Integration
πΉNotification Service
πΉSocial Media Backend
πΉHospital Management System
πΉEvent Booking API
πΉLearning Management System
β€οΈ React to this message for more coding & project ideas!
β€12