How to Generate a Random Number from 1 to 100 in JavaScript? (With Examples)

Generating random numbers is one of the most common tasks in JavaScript—whether you are building games, quizzes, OTP systems, or randomized features.

In this post, you’ll learn exactly how to generate a random number between 1 and 100 using JavaScript, with examples and outputs.


🎯 The Simple Answer

JavaScript provides the built-in function:

Math.random()

This returns a random decimal between 0 (inclusive) and 1 (exclusive):

0.00023
0.89233
0.55555

To convert it into a number from 1 to 100, use:

Math.floor(Math.random() * 100) + 1;


Example: Get a Random Number from 1 to 100

const randomNum = Math.floor(Math.random() * 100) + 1;
console.log(randomNum);

Sample Output

73

(Your number will be different every time.)


🔍 How It Works? (Step-by-Step)

1. Math.random()

Generates random values like:

0.12
0.98
0.45

2. Multiply by 100

0.45 * 100 = 45
0.98 * 100 = 98

3. Math.floor()

Removes decimals (round down):

45.67 → 45
98.12 → 98

4. Add +1

Because random numbers could be 0, we add 1 to shift the range from:

0–99  →  1–100


🔁 Generate and Print 10 Random Numbers (1–100)

for (let i = 0; i < 10; i++) {
  console.log(Math.floor(Math.random() * 100) + 1);
}

Sample Output

18
77
9
42
100
13
65
2
88
50


Bonus: Function to Easily Reuse Anywhere

function randomFrom1To100() {
  return Math.floor(Math.random() * 100) + 1;
}

console.log(randomFrom1To100());


🎮 Practical Uses

You can use this method in:

✔ Games

Random enemies, damage points, levels.

✔ Quiz Apps

Random questions, random rewards.

✔ OTP / Token Generators

Random 2-digit numbers.

✔ Simulations

Random probability calculations.


🚀 Conclusion

To generate a random number between 1 and 100 in JavaScript, use:

Math.floor(Math.random() * 100) + 1;

It is simple, accurate, and used widely in real-world applications.

Top 50 JavaScript Coding Interview Questions & Answers (2025 Edition)

JavaScript interviews focus heavily on logic, string manipulation, array operations, recursion, and problem-solving.
Here are the top 50 JavaScript coding interview questions with solutions + outputs.


1. Reverse a String

function reverseString(str) {
  return str.split("").reverse().join("");
}

console.log(reverseString("hello"));

Output:

olleh


2. Check Palindrome

function isPalindrome(str) {
  return str === str.split("").reverse().join("");
}

console.log(isPalindrome("madonna"));
console.log(isPalindrome("madam"));

Output:

false
true


3. Reverse an Integer

function reverseInt(num) {
  return parseInt(num.toString().split("").reverse().join(""));
}

console.log(reverseInt(12345));

Output:

54321


4. Factorial of a Number

function factorial(n) {
  return n === 0 ? 1 : n * factorial(n - 1);
}

console.log(factorial(5));

Output:

120


5. Largest Number in Array

console.log(Math.max(...[3, 10, 6, 2]));

Output:

10


6. Smallest Number in Array

console.log(Math.min(...[3, 10, 6, 2]));

Output:

2


7. Sum of Array Numbers

function sumArray(arr) {
  return arr.reduce((a, b) => a + b, 0);
}

console.log(sumArray([5, 5, 5]));

Output:

15


8. Remove Duplicates

console.log([...new Set([1, 2, 2, 3, 3, 4])]);

Output:

[1, 2, 3, 4]


9. Anagram Check

console.log(isAnagram("listen", "silent"));

function isAnagram(a, b) {
  return a.split("").sort().join("") === b.split("").sort().join("");
}

Output:

true


10. Character Count

console.log(charCount("hello"));

function charCount(str) {
  return str.split("").reduce((acc, ch) => {
    acc[ch] = (acc[ch] || 0) + 1;
    return acc;
  }, {});
}

Output:

{ h: 1, e: 1, l: 2, o: 1 }


11. Fibonacci Sequence (Iterative)

function fibonacci(n) {
  const arr = [0, 1];
  for (let i = 2; i <= n; i++) {
    arr[i] = arr[i - 1] + arr[i - 2];
  }
  return arr;
}

console.log(fibonacci(7));

Output:

[0, 1, 1, 2, 3, 5, 8, 13]


12. Check Prime Number

function isPrime(n) {
  if (n < 2) return false;
  for (let i = 2; i <= Math.sqrt(n); i++) {
    if (n % i === 0) return false;
  }
  return true;
}

console.log(isPrime(11));
console.log(isPrime(20));

Output:

true
false


13. Find Second Largest Number

function secondLargest(arr) {
  const unique = [...new Set(arr)];
  unique.sort((a, b) => b - a);
  return unique[1];
}

console.log(secondLargest([10, 20, 30, 30, 5]));

Output:

20


14. Find Missing Number

function missingNumber(arr) {
  const n = arr.length + 1;
  const sum = (n * (n + 1)) / 2;
  return sum - arr.reduce((a, b) => a + b, 0);
}

console.log(missingNumber([1,2,3,5]));

Output:

4


15. Flatten Array

console.log([1, [2, [3, 4]]].flat(Infinity));

Output:

[1, 2, 3, 4]


16. Check if Arrays are Equal

function arraysEqual(a, b) {
  return JSON.stringify(a) === JSON.stringify(b);
}

console.log(arraysEqual([1,2,3], [1,2,3]));
console.log(arraysEqual([1,2,3], [3,2,1]));

Output:

true
false


17. Array Intersection

console.log([1,2,3,4].filter(x => [3,4,5].includes(x)));

Output:

[3, 4]


18. Count Vowels

function countVowels(str) {
  return str.match(/[aeiou]/gi)?.length || 0;
}

console.log(countVowels("javascript"));

Output:

3


19. Capitalize First Letter of Each Word

console.log("hello world".replace(/\b\w/g, c => c.toUpperCase()));

Output:

Hello World


20. Random Number (Range)

function random(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

console.log(random(10, 20));

Output Example:

14


21. Validate Email

console.log(/^\S+@\S+\.\S+$/.test("abc@gmail.com"));
console.log(/^\S+@\S+\.\S+$/.test("hello@com"));

Output:

true
false


22. Check Numeric String

console.log(/^\d+$/.test("12345"));
console.log(/^\d+$/.test("12a45"));

Output:

true
false


23. Convert to Title Case

function titleCase(str) {
  return str.toLowerCase().replace(/\b\w/g, c => c.toUpperCase());
}

console.log(titleCase("welcome to javascript"));

Output:

Welcome To Javascript


24. GCD (Greatest Common Divisor)

function gcd(a, b) {
  return b === 0 ? a : gcd(b, a % b);
}

console.log(gcd(20, 8));

Output:

4


25. LCM

function gcd(a, b) {
  return b === 0 ? a : gcd(b, a % b);
}
function lcm(a, b) {
  return (a * b) / gcd(a, b);
}

console.log(lcm(5, 10));

Output:

10


26. String Rotation Check

console.log(isRotation("abcde", "cdeab"));

function isRotation(a, b) {
  return a.length === b.length && (a + a).includes(b);
}

Output:

true


27. Longest Word

function longestWord(str) {
  return str.split(" ").reduce((a, b) => b.length > a.length ? b : a);
}

console.log(longestWord("JavaScript coding interview questions"));

Output:

interview


28. Remove All Spaces

console.log("a b  c d".replace(/\s+/g, ""));

Output:

abcd


29. Word Count

console.log("  JavaScript is awesome  ".trim().split(/\s+/).length);

Output:

3


30. Array to Object

console.log(Object.assign({}, ["a", "b", "c"]));

Output:

{ '0': 'a', '1': 'b', '2': 'c' }


31. Check Empty Object

console.log(Object.keys({}).length === 0);
console.log(Object.keys({a:1}).length === 0);

Output:

true
false


32. Merge Two Objects

console.log({ ...{a:1}, ...{b:2} });

Output:

{ a: 1, b: 2 }


33. Debounce Function

function debounce(fn, delay) {
  let timer;
  return function(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  }
}

const fn = debounce(() => console.log("Executed"), 500);
fn(); fn(); fn(); // Only last one runs

Output:

Executed


34. Throttle Function

function throttle(fn, delay) {
  let last = 0;
  return (...args) => {
    const now = Date.now();
    if (now - last >= delay) {
      last = now;
      fn.apply(this, args);
    }
  }
}

const fn = throttle(() => console.log("Called"), 1000);
fn(); fn(); fn();

Output:

Called


35. Shuffle Array

function shuffle(arr) {
  for (let i = arr.length - 1; i > 0; i--) {
    let j = Math.floor(Math.random() * (i + 1));
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
  return arr;
}

console.log(shuffle([1,2,3,4,5]));

Output Example:

[3, 5, 1, 4, 2]


36. Object to Array

console.log(Object.entries({a:1, b:2}));

Output:

[ ['a',1], ['b',2] ]


37. Sum of Digits

function sumDigits(num) {
  return num.toString().split("")
    .reduce((a,b) => a + Number(b), 0);
}

console.log(sumDigits(987));

Output:

24


38. Same Digits Check

console.log(sameDigits(123, 321));
console.log(sameDigits(121, 112));

function sameDigits(a, b) {
  return a.toString().split("").sort().join("") === 
         b.toString().split("").sort().join("");
}

Output:

true
true


39. Clean Array (Remove Null/Empty)

console.log([0, null, undefined, 5, "", 3].filter(Boolean));

Output:

[5, 3]


40. Count Unique Values

console.log(new Set([1,2,2,3,4,4,5]).size);

Output:

5


41. Unique Elements

console.log([...new Set([1,2,2,3,4])]);

Output:

[1,2,3,4]


42. Find Duplicate Values

console.log([1,2,2,3,3,4].filter((v,i,arr)=>arr.indexOf(v)!==i));

Output:

[2,3]


43. Number to Binary

console.log((10).toString(2));

Output:

1010


44. Binary to Number

console.log(parseInt("1010", 2));

Output:

10


45. Range Sum

function rangeSum(a,b){
  let sum=0;
  for(let i=a;i<=b;i++) sum+=i;
  return sum;
}

console.log(rangeSum(1,5));

Output:

15


46. Armstrong Number

function isArmstrong(num){
  const digits = num.toString().split("");
  const power = digits.length;
  return digits.reduce((a,b)=>a+Math.pow(b,power),0)==num;
}

console.log(isArmstrong(153));

Output:

true


47. Longest Repeating Character

function longestRepeat(str){
  let max=0, curr=1;
  for(let i=1;i<str.length;i++){
    if(str[i]==str[i-1]) curr++;
    else curr=1;
    max = Math.max(max, curr);
  }
  return max;
}

console.log(longestRepeat("aaabbccccdde"));

Output:

4


48. Median of Array

function median(arr){
  arr.sort((a,b)=>a-b);
  let mid = Math.floor(arr.length/2);
  return arr.length%2? arr[mid] : (arr[mid-1]+arr[mid])/2;
}

console.log(median([1,3,4,2,6]));

Output:

3


49. Balanced Parentheses

function isBalanced(str){
  const stack=[];
  const map={')':'(', ']':'[', '}':'{'};
  for(let ch of str){
    if("({[".includes(ch)) stack.push(ch);
    else if(map[ch]!==stack.pop()) return false;
  }
  return stack.length===0;
}

console.log(isBalanced("{[()]}"));
console.log(isBalanced("{[(])}"));

Output:

true
false


50. Add Without + Operator

function add(a,b){
  while(b!==0){
    let carry = (a & b) << 1;
    a = a ^ b;
    b = carry;
  }
  return a;
}

console.log(add(5,7));

Output:

12


Top 100 React.js Interview Questions and Answers (2025 Edition)

React.js continues to be one of the most demanded frontend libraries in 2025. Whether you are preparing for an internship, junior role, or senior React developer position, these Top 100 React Interview Questions will help you crack your next interview with confidence.


1. What is React?

React is an open-source JavaScript library used for building user interfaces, especially single-page applications.


2. What are the key features of React?

  • Virtual DOM
  • Component-based architecture
  • One-way data binding
  • JSX support
  • Reusable components

3. What is JSX?

JSX is a JavaScript XML-like syntax used to write HTML inside JavaScript.


4. What is Virtual DOM?

Virtual DOM is an in-memory representation of the real DOM. React updates the UI efficiently by comparing differences (diffing) and applying only necessary changes.


5. What are components in React?

Components are reusable UI blocks. They can be class components or functional components.


6. What is the difference between functional and class components?

Functional components use functions and hooks.
Class components use ES6 classes and lifecycle methods.


7. What is a state in React?

State is a built-in object that stores dynamic data that affects the component’s output.


8. What is props?

Props (properties) are read-only values passed from parent to child components.


9. Can you modify props?

No, props are immutable.


10. What is lifting state up?

Sharing state between components by moving it to their nearest common ancestor.


11. What is React Hook?

Hooks allow functional components to manage state, lifecycle, and side effects.


12. What is useState?

A hook used to maintain state in functional components.


13. What is useEffect?

A hook to handle side effects like API calls, timers, subscriptions.


14. What is dependency array in useEffect?

It tells React when the effect should re-run.


15. What happens if dependency array is empty?

The effect runs only once like componentDidMount.


16. What is useRef?

A hook used to store mutable values that do not cause re-render.


17. What is useMemo?

Used for memoizing expensive calculations to improve performance.


18. What is useCallback?

Used to memoize functions to prevent unnecessary re-renders.


19. What is React Fragment?

A wrapper to group elements without adding extra DOM nodes:
<>...</>


20. What is reconciliation?

The process where React updates the UI by comparing the Virtual DOM with the previous version.


21. What is the difference between state and props?

State is mutable and local.
Props are immutable and passed from parent.


22. What is the purpose of key in lists?

Keys help identify items in lists to optimize rendering.


23. What happens if you don’t use keys?

React may re-render inefficiently or incorrectly.


24. What is conditional rendering?

Rendering UI based on a condition:
{isLoggedIn ? <Home/> : <Login/>}


25. What is React Router?

A library used for navigation between pages in React apps.


26. What are the main components of React Router?

  • BrowserRouter
  • Routes
  • Route
  • Link
  • useNavigate

27. What is Single Page Application (SPA)?

A web app that loads once and updates UI without refreshing.


28. What is Redux?

A predictable state management library.


29. What are the main principles of Redux?

  • Single source of truth
  • State is read-only
  • Pure reducers

30. What is a reducer?

A pure function that returns new state based on action.


31. What is an action?

An object that describes an event, usually containing a type and payload.


32. What is Redux Thunk?

A middleware that enables async actions.


33. What is Redux Toolkit?

An official, simplified way of writing Redux logic.


34. What is context API?

A React feature used to avoid prop drilling.


35. What is prop drilling?

Passing props through multiple levels unnecessarily.


36. What is StrictMode?

A development-mode tool that highlights potential issues.


37. What is React.memo?

A higher-order component to memoize functional components.


38. What is an error boundary?

A component that catches JavaScript errors in children.


39. What is lazy loading?

Loading components only when needed using React.lazy().


40. What is Suspense?

A component used to show a fallback UI while lazy components load.


41. What is hydration?

Attaching event listeners to server-rendered HTML (for SSR).


42. What is SSR?

Server Side Rendering: rendering pages on the server instead of client.


43. What is CSR?

Client Side Rendering: rendering done in the browser.


44. What is Next.js?

A React framework for SSR, SSG, API routes and performance.


45. What is SSG?

Static Site Generation: pre-rendering pages at build time.


46. What is useLayoutEffect?

Like useEffect but runs synchronously after DOM mutations.


47. What is portal in React?

Rendering children into a DOM node outside the parent.


48. What is synthetic event?

A wrapper around browser events for cross-browser compatibility.


49. What is the difference between controlled and uncontrolled components?

Controlled: data controlled by React.
Uncontrolled: data controlled by DOM.


50. What is forwardRef?

Allows passing refs from parent to child.


51. What is a custom hook?

A reusable function that uses React hooks.


52. What is reconciliation algorithm?

React’s diffing algorithm used to update UI efficiently.


53. What is componentDidMount?

A class component lifecycle method fired after initial render.


54. What is shouldComponentUpdate?

Used to control whether a component should re-render.


55. What is componentWillUnmount?

Called just before component is destroyed.


56. What is PureComponent?

A component that updates only when props/state change.


57. What is the difference between useMemo and useCallback?

useMemo memoizes values.
useCallback memoizes functions.


58. Why React is fast?

Because of virtual DOM, diffing algorithm, and component reusability.


59. What is rendering in React?

The process of generating UI from component code.


60. What causes re-render in React?

  • State change
  • Props change
  • Parent re-render

61. What is the difference between map and forEach in React rendering?

map() returns an array of elements; forEach() does not.


62. What is HOC (Higher-Order Component)?

A function that takes a component and returns a new component.


63. What is children prop?

A special prop used to pass elements as content:
<Card>Content</Card>


64. What is React Fiber?

A re-written core engine of React for faster rendering.


65. What is concurrent mode?

A set of features that make rendering interruptible and smoother.


66. What is batching?

React groups multiple state updates into one re-render.


67. What is diffing?

Calculating differences between two virtual DOM trees.


68. What is useId?

A hook to generate unique IDs for accessibility.


69. What is useTransition?

Helps mark state updates as non-urgent to avoid blocking UI.


70. What is useDeferredValue?

Lets you defer updating non-urgent parts of UI.


71. What is event bubbling?

Events propagate from child to parent DOM elements.


72. What is event capturing?

Opposite of bubbling; event moves from parent → child.


73. What is React Native?

A framework to build mobile apps using React.


74. What are keys in React lists?

Unique identifiers used to track list items.


75. What is the purpose of index as key?

Avoid using indexes unless list is static.


76. What is double rendering in StrictMode?

React intentionally renders components twice in development to detect side-effects.


77. What is code splitting?

Breaking code into smaller chunks for faster load.


78. What is a bundler in React?

Tools like Webpack, Vite, Parcel to bundle code.


79. What is NPM?

Node Package Manager for installing libraries.


80. What is yarn?

An alternative package manager to npm.


81. What is Vite?

A fast development server and build tool for React apps.


82. What is minification?

Compressing code to reduce file size.


83. What is tree shaking?

Removing unused code during bundling.


84. What is CSR vs SSR in React?

CSR: Render in browser
SSR: Render on server


85. What is hydration in SSR?

Activating a server-rendered static HTML page.


86. Why React uses one-way data flow?

To make apps predictable and easier to debug.


87. What is a ref?

A reference to DOM elements or component values.


88. Why should keys be unique?

To help React differentiate items for efficient updates.


89. What is shallow rendering?

Testing technique that renders component without children.


90. What is Jest?

A testing framework used for React apps.


91. What is React Testing Library (RTL)?

A testing tool focused on UI behavior rather than implementation.


92. What is enzyme?

A testing utility (old) used for shallow and full DOM rendering.


93. What is snapshot testing?

Stores component UI and compares for unexpected changes.


94. What is forwardRef?

Passing refs to nested child components.


95. What is the difference between mount and shallow in testing?

Mount renders full DOM; shallow renders only component.


96. What is SSR in Next.js?

Rendering React components on the server for better SEO.


97. What is Image Optimization in Next.js?

Automatic compression and responsive image generation.


98. What is API Routes in Next.js?

Serverless functions used as backend APIs.


99. What is hydration error?

Mismatch between server-rendered HTML and client-rendered HTML.


100. Why should you learn React in 2025?

  • High demand
  • Strong community
  • Supports web + mobile
  • Easy to learn
  • Flexible and scalable

Redux Interview Questions and Answers

useSelector is a React-Redux hook that allows a component to read data from the Redux store.
It subscribes the component to the store, and the component re-renders whenever the selected state changes.

useSelector accepts a selector function that returns the desired portion of state.

Example:

const count = useSelector((state) => state.counter.value);

Here:

  • state = entire Redux store
  • state.counter.value = specific slice of data needed
  • Component re-renders only when this value changes

How useSelector Works Internally

  1. Component calls useSelector with a selector function
  2. useSelector subscribes to the Redux store
  3. Whenever the store updates:
    • Selector is re-executed
    • It compares the new value with the previous selected value (shallow compare by default)
  4. If the selected value changes → Component re-renders
  5. If value does NOT change → No re-render (performance optimization)

Example Code

import { useSelector } from "react-redux";

function Profile() {
  const username = useSelector(state => state.user.name);

  return <h3>Welcome, {username}</h3>;
}

Real-World Use Case

Imagine you have a dashboard with many widgets.
If each widget used the entire Redux store, everything would re-render on every update 😵

But with useSelector, each widget only re-renders when its specific data changes → huge performance improvement.

export const hasAccess = (state: Object): boolean => {
  return get(state, ['settings', 'admin']) === true;
};

This function is a Redux selector that uses Lodash’s get() to safely read deeply nested properties (settings.admin) from the Redux state.

It returns a boolean value (true or false) based on whether admin access is enabled.

Using it with useSelector:

const hasAdminAccess = useSelector(hasAccess);

This ensures your component automatically updates whenever state.settings.admin changes.

A selector is a pure function that takes the Redux state and returns the required piece of data.

Selectors improve:

BenefitExplanation
ReusabilitySame logic used everywhere
MaintainabilityState structure changes only affect selectors
Performance (with memoization)Can use reselect to avoid recomputing expensive values

📌 Example with nested access:

const selectUserEmail = (state) => state.user?.profile?.email;

📌 Memoized selector (advanced):

import { createSelector } from "reselect";

const selectUser = (state) => state.user;
const selectUserEmail = createSelector(
  [selectUser],
  (user) => user.profile.email
);

    useSelector subscribes to the Redux store and:

    1. Calls your selector whenever the state updates
    2. Compares new value with previous value using ===
    3. If changed → component re-renders
      If same → no re-render (optimization)

    📌 Example behavior:

    Previous valueNew valueRe-render?
    "test""test"❌ No
    "test""hello"✅ Yes
    {user:1}{user:1} (new object)✅ Yes (shallow compare fails)

    Performance Tip

    If selecting objects/arrays, use memoized selectors with createSelector to avoid unnecessary re-renders.

    How WhatsApp Notifications Work Internally — A System Design Perspective

    Have you ever wondered how WhatsApp notifies you instantly when someone sends a message — even when your app is closed? Let’s peel back the layers and look at how WhatsApp’s notification system actually works from a system design point of view.


    🧠 The Big Picture

    When you receive a new WhatsApp message like

    “Ravi: Hey Raju!”

    that notification travels through a complex, highly optimized system involving encryption, real-time messaging, and push infrastructure.

    Let’s break it down step by step 👇


    ⚙️ 1. Message Creation — The Journey Begins

    When Ravi sends a message to Raju:

    • The WhatsApp client on Ravi’s phone encrypts the message using end-to-end encryption (E2EE).
    • The encrypted payload is sent to WhatsApp’s Message Server through a persistent socket connection.

    At this point, the message is unreadable to anyone — even WhatsApp itself.


    📡 2. Message Routing — Finding the Recipient

    The Message Server receives Ravi’s encrypted message and determines that it needs to reach Raju’s device.

    • If Raju is online, the message is sent immediately via a persistent connection (using XMPP or WebSockets).
    • If Raju is offline, WhatsApp stores the encrypted message temporarily in its Storage Service until Raju reconnects.

    📬 3. Triggering a Notification — When the App Is Closed

    If Raju’s app is in the background or not connected, WhatsApp triggers a push notification.

    Here’s how it works:

    1. The Notification Service in WhatsApp’s backend detects that Raju is offline.
    2. It prepares a lightweight message payload — something like: { "to": "<Raju_Device_Token>", "notification": { "title": "WhatsApp", "body": "Ravi: Hey Raju!" }, "data": { "message_id": "abc123", "chat_id": "ravi_123" } }
    3. It sends this payload to Firebase Cloud Messaging (FCM) for Android or Apple Push Notification Service (APNS) for iPhone.

    ☁️ 4. Push Infrastructure — Google & Apple Step In

    Once WhatsApp sends the notification request:

    • FCM/APNS looks up the device token (a unique ID representing Raju’s phone).
    • They route the message through their global notification delivery networks.
    • Raju’s phone receives it instantly — even if the app isn’t open.

    This is possible because FCM and APNS maintain their own persistent channels with your device at the OS level.


    🔔 5. Notification Delivery on Device

    When Raju’s phone receives the notification:

    • The OS wakes up WhatsApp’s background receiver.
    • A notification appears on the lock screen or notification tray: “Ravi: Hey Raju!”

    When Raju taps it:

    • WhatsApp opens and establishes its secure socket connection to the server.
    • The actual encrypted message is fetched and decrypted locally using Raju’s private key.

    At this point, the two ticks ✅ (message delivered) appear on Ravi’s chat screen.
    When Raju reads it, WhatsApp sends a “read receipt” (blue ticks 💙) back.


    🔐 6. End-to-End Encryption (E2EE)

    One of WhatsApp’s strongest features is end-to-end encryption.

    • Messages are encrypted on Ravi’s device.
    • Stored in encrypted form on WhatsApp’s server (if needed).
    • Decrypted only on Raju’s device.

    Even WhatsApp’s servers can’t see the content — they only know that a message exists and who it’s meant for.


    🧩 7. Behind-the-Scenes Components

    Here’s what’s happening under the hood:

    ComponentRole
    Message ServiceHandles message routing between users
    Notification ServiceSends push notifications via FCM/APNS
    Encryption ServiceEncrypts and decrypts message payloads
    Storage ServiceStores encrypted messages for offline users
    Delivery TrackerTracks sent, delivered, and read states
    User Presence ServiceDetermines whether users are online or offline

    🧱 8. System Architecture Overview

    Conceptually, it looks like this:

    Ravi's Phone ──►(Encrypt Message) ──► Message Server ──► (Route + Store ) ──► Notification Service ──►(Push Notification) ──► FCM/APNS ──► Raju's Phone
    
    

    ⚡ 9. Why This Design Works So Well

    GoalHow WhatsApp Achieves It
    Real-time deliveryPersistent sockets (XMPP/WebSockets)
    Offline supportStored encrypted messages + push
    SecurityEnd-to-end encryption keys per user
    ScalabilityMicroservices + distributed queues
    Low latencyGlobal servers + efficient routing
    Battery efficiencyOS-managed push (via FCM/APNS)

    🚀 10. Key Takeaways for System Design Interviews

    If you’re designing a notification system like WhatsApp’s, remember these principles:

    1. Decouple message delivery and notification logic (use queues).
    2. Use push services (FCM/APNS) for offline or background delivery.
    3. Maintain persistent connections for real-time chat.
    4. Ensure reliability with retry, message persistence, and acknowledgment mechanisms.
    5. Design for privacy with end-to-end encryption and minimal metadata storage.

    🏁 Final Thoughts

    WhatsApp’s notification system is a perfect blend of real-time communication, security, and scalability.
    As a system architect, understanding how these layers interact — from event queues to encryption — is crucial for designing any large-scale, user-facing application.