<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: gunjangidwani</title>
    <description>The latest articles on Forem by gunjangidwani (@gunjangidwani).</description>
    <link>https://forem.com/gunjangidwani</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F593108%2Fe7e59337-23d8-4785-bd8f-e8c5a1e1a265.png</url>
      <title>Forem: gunjangidwani</title>
      <link>https://forem.com/gunjangidwani</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/gunjangidwani"/>
    <language>en</language>
    <item>
      <title>Why Javascript fundamentals are stopping you!!!</title>
      <dc:creator>gunjangidwani</dc:creator>
      <pubDate>Tue, 26 Aug 2025 17:21:11 +0000</pubDate>
      <link>https://forem.com/gunjangidwani/why-javascript-fundamentals-are-stopping-you-2n4g</link>
      <guid>https://forem.com/gunjangidwani/why-javascript-fundamentals-are-stopping-you-2n4g</guid>
      <description>&lt;p&gt;&lt;strong&gt;D𝗶𝘀𝗮𝗽𝗽𝗲𝗮𝗿 𝗳𝗼𝗿 𝟮 𝗺𝗼𝗻𝘁𝗵𝘀 𝗮𝗻𝗱 𝗳𝗶𝘅 𝗝𝗮𝘃𝗮𝘀𝗰𝗿𝗶𝗽𝘁 𝗳𝘂𝗻𝗱𝗮𝗺𝗲𝗻𝘁𝗮𝗹𝘀&lt;/strong&gt;🔥&lt;br&gt;
When i started the development journey, hoping from one video to another in order to get the job, I prepared 2-3 MERN/MEAN stack projects. I got the job and after that once again when I wanted to switch and prepare for high package job I got stuck in tutorial hell for months.&lt;/p&gt;

&lt;p&gt;React tutorials, Next.js courses, TypeScript bootcamps - nothing clicked.&lt;/p&gt;

&lt;p&gt;𝗧𝗵𝗲𝗻 𝗜 𝗿𝗲𝗮𝗹𝗶𝘇𝗲𝗱 𝘁𝗵𝗲 𝗽𝗿𝗼𝗯𝗹𝗲𝗺: I was building a house without a foundation.&lt;/p&gt;

&lt;p&gt;𝗦𝗼 𝗜 𝘀𝘁𝗼𝗽𝗽𝗲𝗱 𝗲𝘃𝗲𝗿𝘆𝘁𝗵𝗶𝗻𝗴. 𝗪𝗲𝗻𝘁 𝗯𝗮𝗰𝗸 𝘁𝗼 𝘃𝗮𝗻𝗶𝗹𝗹𝗮 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁.&lt;/p&gt;

&lt;p&gt;2 weeks of pure fundamentals.&lt;/p&gt;

&lt;p&gt;The result? &lt;br&gt;
I haven't touched a tutorial in 2 months. &lt;br&gt;
Problems I used to Google for hours? &lt;br&gt;
Solved in minutes.&lt;/p&gt;

&lt;p&gt;𝗛𝗲𝗿𝗲'𝘀 𝘄𝗵𝗮𝘁 𝗜 𝘄𝗶𝘀𝗵 𝘀𝗼𝗺𝗲𝗼𝗻𝗲 𝘁𝗼𝗹𝗱 𝗺𝗲 𝗲𝗮𝗿𝗹𝗶𝗲𝗿:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Stop chasing frameworks. &lt;/li&gt;
&lt;li&gt;Master the language first.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Most developers learn React before understanding JavaScript. It's like learning to drive before understanding how cars work.&lt;/p&gt;

&lt;p&gt;𝗧𝗵𝗲 𝟳 𝗳𝘂𝗻𝗱𝗮𝗺𝗲𝗻𝘁𝗮𝗹𝘀 𝘁𝗵𝗮𝘁 𝗰𝗵𝗮𝗻𝗴𝗲𝗱 𝗲𝘃𝗲𝗿𝘆𝘁𝗵𝗶𝗻𝗴:&lt;br&gt;
🔹 Closures - Why your variables sometimes "disappear" &lt;br&gt;
🔹 Event Loop - Why your app freezes (and how to fix it) &lt;br&gt;
🔹 Prototypes - How JavaScript really works under the hood &lt;br&gt;
🔹 Hoisting - Why your code breaks in production but works locally &lt;br&gt;
🔹 Async/Await - Why your API calls fail silently &lt;br&gt;
🔹 Scope Chain - Why your functions can't find variables &lt;br&gt;
🔹 Reference vs Value - Why your state updates don't work&lt;/p&gt;

&lt;p&gt;The uncomfortable truth:&lt;br&gt;
𝟵𝟬% 𝗼𝗳 𝗥𝗲𝗮𝗰𝘁 𝗯𝘂𝗴𝘀 𝗮𝗿𝗲 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗽𝗿𝗼𝗯𝗹𝗲𝗺𝘀 𝗶𝗻 𝗱𝗶𝘀𝗴𝘂𝗶𝘀𝗲.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;That infinite re-render? JavaScript closure issue. &lt;/li&gt;
&lt;li&gt;That undefined error? JavaScript hoisting problem. &lt;/li&gt;
&lt;li&gt;That state not updating? JavaScript reference issue.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱 𝘄𝗵𝘆 𝗳𝗿𝗮𝗺𝗲𝘄𝗼𝗿𝗸𝘀 𝘄𝗼𝗿𝗸 𝘁𝗵𝗲 𝘄𝗮𝘆 𝘁𝗵𝗲𝘆 𝗱𝗼&lt;/p&gt;

&lt;p&gt;The biggest mistake I made:&lt;br&gt;
I thought fundamentals were boring. They're not.&lt;/p&gt;

&lt;p&gt;They're the difference between copying code and understanding code.&lt;/p&gt;

&lt;p&gt;Bottom line: You can't build advanced React apps on shaky JavaScript foundations.&lt;/p&gt;

&lt;p&gt;Fix the foundation first. Everything else becomes easier.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>interview</category>
      <category>react</category>
    </item>
    <item>
      <title>Understanding the Call Stack in JavaScript</title>
      <dc:creator>gunjangidwani</dc:creator>
      <pubDate>Thu, 03 Jul 2025 03:26:45 +0000</pubDate>
      <link>https://forem.com/gunjangidwani/understanding-the-call-stack-in-javascript-3ojl</link>
      <guid>https://forem.com/gunjangidwani/understanding-the-call-stack-in-javascript-3ojl</guid>
      <description>&lt;p&gt;The Call Stack is a fundamental concept in programming that helps manage function calls in a program. Let's break it down in simple terms.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is the Call Stack?
&lt;/h2&gt;

&lt;p&gt;The Call Stack is a special type of data structure that keeps track of the functions that are currently being executed in your program. It's like a stack of plates: you can only add or remove plates from the top. In programming terms, this is called a "LIFO" (Last In, First Out) structure.&lt;/p&gt;

&lt;h2&gt;
  
  
  How Does the Call Stack Work?
&lt;/h2&gt;

&lt;p&gt;When a function is called, it is "pushed" onto the Call Stack. When the function finishes executing, it is "popped" off the stack. This process ensures that functions are executed in the correct order and that each function has its own context (variables, parameters, etc.).&lt;br&gt;
&lt;strong&gt;Example&lt;/strong&gt;&lt;br&gt;
Let's look at a simple example to understand how the Call Stack works:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function greet(name) {
    return `Hello, ${name}!`;
}

function sayHello() {
    const message = greet("Kimi");
    console.log(message);
}
sayHello();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step-by-Step Execution:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Initial Call:&lt;/strong&gt; The program starts executing &lt;code&gt;sayHello()&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt; &lt;code&gt;sayHello&lt;/code&gt; is pushed onto the Call Stack.&lt;/li&gt;
&lt;li&gt;     Inside &lt;code&gt;sayHello&lt;/code&gt;, &lt;code&gt;greet("Kimi")&lt;/code&gt; is called.&lt;/li&gt;
&lt;li&gt;    &lt;code&gt;greet&lt;/code&gt; is pushed onto the Call Stack.&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Executing greet:&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;greet&lt;/code&gt; executes and returns "Hello, Kimi!".&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;greet&lt;/code&gt; is popped off the Call Stack.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Back to sayHello:&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;sayHello&lt;/code&gt; continues executing with the returned value "Hello, Kimi!".&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;sayHello&lt;/code&gt; logs the message to the console.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;sayHello&lt;/code&gt; is popped off the Call Stack.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Program Ends:&lt;/strong&gt; The Call Stack is now empty, and the program execution is complete.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Visual Representation&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Initial Call:
Call Stack: [sayHello]

Inside sayHello, greet is called:
Call Stack: [sayHello, greet]

greet executes and returns:
Call Stack: [sayHello]

sayHello continues and completes:
Call Stack: []

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Importance of the Call Stack
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Function Execution Order:&lt;/strong&gt;&lt;br&gt;
The Call Stack ensures that functions are executed in the correct order.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Error Handling:&lt;/strong&gt;&lt;br&gt;
When an error occurs, the Call Stack provides a trace of where the error happened, making debugging easier.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Memory Management:&lt;/strong&gt;&lt;br&gt;
Each function call has its own context (local variables, parameters), which is stored on the stack. This helps manage memory efficiently.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Common Issues
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. Stack Overflow:&lt;/strong&gt;&lt;br&gt;
If you have too many nested function calls (like in infinite recursion), the Call Stack can overflow, causing the program to crash.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Debugging:&lt;/strong&gt;&lt;br&gt;
 Understanding the Call Stack is crucial for debugging, as it helps you trace the flow of function calls and identify where things went wrong.&lt;/p&gt;

&lt;p&gt;Conclusion&lt;/p&gt;

&lt;p&gt;The Call Stack is a powerful tool that helps manage function calls in your program. It ensures that functions are executed in the correct order and provides a way to trace errors. Understanding how the Call Stack works will make you a better programmer and help you debug more effectively.&lt;/p&gt;

&lt;p&gt;Happy coding! 🚀&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>programming</category>
      <category>javascript</category>
      <category>learning</category>
    </item>
    <item>
      <title>Access Token v/s Refresh Token</title>
      <dc:creator>gunjangidwani</dc:creator>
      <pubDate>Fri, 20 Jun 2025 15:27:17 +0000</pubDate>
      <link>https://forem.com/gunjangidwani/access-token-vs-refresh-token-4942</link>
      <guid>https://forem.com/gunjangidwani/access-token-vs-refresh-token-4942</guid>
      <description>&lt;p&gt;🔐 &lt;strong&gt;What is an Access Token?&lt;/strong&gt;&lt;br&gt;
Purpose: It’s the short-lived credential you present to access protected APIs.&lt;/p&gt;

&lt;p&gt;Lifespan: Typically expires in minutes or hours.&lt;/p&gt;

&lt;p&gt;Analogy: Think of it as a temporary pass that lets you in—but once it’s expired, you’re locked out.&lt;/p&gt;

&lt;p&gt;Why short-lived? Limits risk if stolen—once expired, it’s useless.&lt;/p&gt;

&lt;p&gt;🕶️ &lt;strong&gt;What is a Refresh Token?&lt;/strong&gt;&lt;br&gt;
Purpose: This long-lived token allows you to seamlessly obtain a new access token.&lt;/p&gt;

&lt;p&gt;Lifespan: Can last days to months.&lt;/p&gt;

&lt;p&gt;Analogy: It's like a passport—when your pass (access token) expires, you present your passport (refresh token) to get a new pass.&lt;/p&gt;

&lt;p&gt;Why use it? Keeps you logged in without re-entering your password and avoids constant short-lived login loops.&lt;/p&gt;

&lt;p&gt;🔄** How They Work Together**&lt;br&gt;
Initial login → Server issues both tokens.&lt;/p&gt;

&lt;p&gt;Client uses the access token to call APIs.&lt;/p&gt;

&lt;p&gt;Upon expiration, the client silently sends the refresh token to the Auth Server.&lt;/p&gt;

&lt;p&gt;Auth back-end validates it, then returns a new access token—and often rotates the refresh token too.&lt;/p&gt;

&lt;p&gt;The client stores these securely and continues operations seamlessly.&lt;/p&gt;

&lt;p&gt;🛡️ &lt;strong&gt;Security Best Practices&lt;/strong&gt;&lt;br&gt;
Rotate refresh tokens: Best practice is to issue a new refresh token each time one is used, invalidating the old one—reducing the damage if stolen.&lt;/p&gt;

&lt;p&gt;Reuse detection: If a refresh token is reused, immediately revoke that token chain to protect the user.&lt;/p&gt;

&lt;p&gt;Secure storage:&lt;/p&gt;

&lt;p&gt;Access tokens can live in memory or secure HTTP-only cookies (minimizes XSS).&lt;/p&gt;

&lt;p&gt;Refresh tokens must be stored more securely—preferably server-side or in secure device keychains.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;🧭 Why Not Use Just One Token?&lt;/strong&gt;&lt;br&gt;
Access tokens alone must either be long-lived (bad for security) or require constant re-login (bad for user experience).&lt;/p&gt;

&lt;p&gt;Refresh tokens enable:&lt;/p&gt;

&lt;p&gt;Short-lived access tokens (safer),&lt;/p&gt;

&lt;p&gt;Seamless long sessions,&lt;/p&gt;

&lt;p&gt;Controlled session invalidation.&lt;/p&gt;

&lt;p&gt;This balanced flow mitigates risk while preserving usability.&lt;/p&gt;

&lt;p&gt;🧩** In Summary**&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;strong&gt;Token Type&lt;/strong&gt;&lt;/th&gt;
&lt;th&gt;&lt;strong&gt;Lifespan&lt;/strong&gt;&lt;/th&gt;
&lt;th&gt;&lt;strong&gt;Use Case&lt;/strong&gt;&lt;/th&gt;
&lt;th&gt;&lt;strong&gt;Security Consideration&lt;/strong&gt;&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Access Token&lt;/td&gt;
&lt;td&gt;Short-lived&lt;/td&gt;
&lt;td&gt;Access protected resources (APIs)&lt;/td&gt;
&lt;td&gt;Clean exposure window; vulnerable if stolen&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Refresh Token&lt;/td&gt;
&lt;td&gt;Long-lived&lt;/td&gt;
&lt;td&gt;Renew access token without requiring login&lt;/td&gt;
&lt;td&gt;Must be stored securely; should be rotated or revoked&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Refresh tokens are the backup that keeps your session alive.&lt;/p&gt;

&lt;p&gt;The duo work together to balance security and user experience—reducing the risk of token theft while avoiding annoying logouts.&lt;/p&gt;

&lt;p&gt;If you're building APIs or web/mobile apps, implementing this two-token system with rotation and secure storage is considered the modern best practice.&lt;/p&gt;

&lt;p&gt;Also if you want more info for Authorization in Node.js please watch &lt;a href="https://www.youtube.com/watch?v=7DVpag3cO0g&amp;amp;t=13s" rel="noopener noreferrer"&gt;https://www.youtube.com/watch?v=7DVpag3cO0g&amp;amp;t=13s&lt;/a&gt;&lt;br&gt;
This is very helpful series on Node.js&lt;/p&gt;

</description>
      <category>programming</category>
      <category>backend</category>
      <category>node</category>
      <category>authorization</category>
    </item>
    <item>
      <title>HTTP crash course | http Methods | http headers</title>
      <dc:creator>gunjangidwani</dc:creator>
      <pubDate>Thu, 19 Jun 2025 05:17:57 +0000</pubDate>
      <link>https://forem.com/gunjangidwani/http-crash-course-http-methods-http-headers-2hm7</link>
      <guid>https://forem.com/gunjangidwani/http-crash-course-http-methods-http-headers-2hm7</guid>
      <description>&lt;h2&gt;
  
  
  HTTP Basics and Client-Server Model
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;HTTP communication follows a client-server model, where the client (e.g., mobile app) sends requests to the server, and the server responds accordingly.&lt;/li&gt;
&lt;li&gt;URL (Uniform Resource Locator) identifies the location of a resource; related terms include URI and URN, which are technical identifiers, but URL is commonly used for location referencing.&lt;/li&gt;
&lt;li&gt;HTTP is one of many protocols used for communication; protocols like SRV, SRV-W exist too. HTTP mainly transfers data in clear text, while HTTPS encrypts data for security.&lt;/li&gt;
&lt;li&gt;HTTP stands for HyperText Transfer Protocol, primarily designed to transfer text and other data efficiently across the internet, optimizing for lightweight data structures to reduce processing and network load.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  HTTP Request and Response Headers
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;HTTP headers carry metadata about the request or response, structured as key-value pairs. They provide additional context such as file name, size, creation/modification dates, and more.&lt;/li&gt;
&lt;li&gt;Headers are open and extensible; some are standardized while others can be custom-defined by developers.&lt;/li&gt;
&lt;li&gt;Headers exist in both requests (from client) and responses (from server), indicating details like the source of the request (e.g., browser or Postman), response status, content type, etc.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Common uses of headers include:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Caching:&lt;/strong&gt; To check if cached data can be reused.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Authentication:&lt;/strong&gt; Using tokens like Bearer tokens, JWT, session cookies, refresh tokens.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;State management:&lt;/strong&gt; Tracking user status (guest or logged-in), cart contents, etc.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Older headers used an "X-" prefix (e.g., X-Name), but this convention has mostly been deprecated since around 2012-2013.&lt;/p&gt;

&lt;h2&gt;
  
  
  Headers can be categorized into:
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Request headers:&lt;/strong&gt; Sent by client with data or metadata.&lt;br&gt;
**Response headers: **Sent by server with status and metadata.&lt;br&gt;
**Representation headers: **Indicate encoding or compression of data (e.g., gzip).&lt;/p&gt;

&lt;p&gt;Some headers enforce security and access policies (e.g., CORS), but they require explicit implementation in server code and do not act automatically.&lt;/p&gt;

&lt;h2&gt;
  
  
  Common HTTP Headers Examples
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;strong&gt;Header Name&lt;/strong&gt;&lt;/th&gt;
&lt;th&gt;&lt;strong&gt;Purpose&lt;/strong&gt;&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;Accept&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Specifies the media types the client can handle (e.g., &lt;code&gt;application/json&lt;/code&gt;)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;User-Agent&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Identifies the client application or browser making the request&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;Authorization&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Contains credentials like Bearer tokens for authentication&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;Content-Type&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Indicates the media type of the request or response body (e.g., JSON, PDF)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;Cookie&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Stores key-value pairs for session management&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;Cache-Control&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Controls caching policies for requests and responses&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  HTTP Methods Overview
&lt;/h2&gt;

&lt;p&gt;HTTP methods specify the type of operation performed on a resource:&lt;br&gt;
&lt;strong&gt;GET:&lt;/strong&gt; Retrieve a resource or list (no message body in request).&lt;/p&gt;

&lt;p&gt;**HEAD: **Retrieve only headers of a resource (no body), useful for metadata checks like cache status or user agent info.&lt;/p&gt;

&lt;p&gt;**POST: **Send data to create a new resource, commonly used for adding new entries in a database.&lt;/p&gt;

&lt;p&gt;**PUT: **Replace an entire resource with the request payload.&lt;/p&gt;

&lt;p&gt;*&lt;em&gt;PATCH: *&lt;/em&gt; Partially update a resource, modifying only specified fields without replacing the entire object.&lt;/p&gt;

&lt;p&gt;*&lt;em&gt;DELETE: *&lt;/em&gt; Remove a resource from server.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;OPTIONS:&lt;/strong&gt; Query the server for supported HTTP methods on a specific endpoint, useful for API discovery and CORS preflight requests.&lt;/p&gt;

&lt;p&gt;*&lt;em&gt;TRACE: *&lt;/em&gt; Used mostly for debugging; echoes back the received request to detect proxies or routing issues.&lt;/p&gt;

&lt;p&gt;*&lt;em&gt;GET, POST, PUT, DELETE, and PATCH *&lt;/em&gt; are the most commonly used methods; others like OPTIONS and TRACE are less frequent but important for specific use cases.&lt;/p&gt;

&lt;p&gt;HTTP status codes are standard response codes given by web servers on the internet. They help indicate whether a request has been successfully completed or if an error occurred. Here's a quick overview of the main categories:&lt;/p&gt;

&lt;p&gt;🔵 1xx – Informational&lt;br&gt;
100 Continue – Request received, continue to send the rest.&lt;/p&gt;

&lt;p&gt;101 Switching Protocols – Switching to a different protocol.&lt;/p&gt;

&lt;p&gt;🟢 2xx – Success&lt;br&gt;
200 OK – Request succeeded.&lt;/p&gt;

&lt;p&gt;201 Created – Resource created.&lt;/p&gt;

&lt;p&gt;204 No Content – Successful, but no content to return.&lt;/p&gt;

&lt;p&gt;🟡 3xx – Redirection&lt;br&gt;
301 Moved Permanently – Resource moved to a new URL permanently.&lt;/p&gt;

&lt;p&gt;302 Found – Temporary redirect.&lt;/p&gt;

&lt;p&gt;304 Not Modified – Resource not changed since last request.&lt;/p&gt;

&lt;p&gt;🔴 4xx – Client Errors&lt;br&gt;
400 Bad Request – Invalid request.&lt;/p&gt;

&lt;p&gt;401 Unauthorized – Authentication required.&lt;/p&gt;

&lt;p&gt;403 Forbidden – Access denied.&lt;/p&gt;

&lt;p&gt;404 Not Found – Resource not found.&lt;/p&gt;

&lt;p&gt;429 Too Many Requests – Rate limit exceeded.&lt;/p&gt;

&lt;p&gt;🔴 5xx – Server Errors&lt;br&gt;
500 Internal Server Error – Server encountered an error.&lt;/p&gt;

&lt;p&gt;502 Bad Gateway – Invalid response from upstream server.&lt;/p&gt;

&lt;p&gt;503 Service Unavailable – Server is down or overloaded.&lt;/p&gt;

&lt;p&gt;504 Gateway Timeout – Upstream server didn't respond in time.&lt;/p&gt;

&lt;h2&gt;
  
  
  HTTP Status Codes and Their Categories
&lt;/h2&gt;

&lt;p&gt;Knowing status codes is essential for backend developers to handle requests and errors properly; exact memorization is unnecessary, but understanding usage and ranges is important.&lt;/p&gt;

&lt;h2&gt;
  
  
  Practical Insights and Learning Approach
&lt;/h2&gt;

&lt;p&gt;Understanding HTTP deeply involves knowledge of data structures, operating systems, networking, and cryptography, as these affect how data is transferred, processed, and secured.&lt;br&gt;
Developers should gain a broad overview of HTTP before writing backend controllers; this foundational knowledge distinguishes good programmers from average ones s s .&lt;br&gt;
Tools like Postman or Thunder Client are commonly used to test and explore HTTP methods and headers interactively s s .&lt;br&gt;
The learning journey includes exploring network latency, data optimization, and efficient communication strategies ... .&lt;br&gt;
💡 Key Insight: HTTP is fundamentally about transferring text and data efficiently and reliably between clients and servers using defined methods, headers, and status codes. Mastery of these basics enables building robust web applications and services.&lt;/p&gt;

</description>
      <category>productivity</category>
      <category>http</category>
      <category>fullstack</category>
      <category>backenddevelopment</category>
    </item>
    <item>
      <title>Data modeling And Error Handling in Mongoose/Node.js</title>
      <dc:creator>gunjangidwani</dc:creator>
      <pubDate>Wed, 18 Jun 2025 02:40:35 +0000</pubDate>
      <link>https://forem.com/gunjangidwani/data-modeling-and-error-handling-in-mongodb-4gp3</link>
      <guid>https://forem.com/gunjangidwani/data-modeling-and-error-handling-in-mongodb-4gp3</guid>
      <description>&lt;p&gt;Couple of days ago I had some issue with data modelling and in researching the topic i found so many useful things from &lt;a href="https://mongoosejs.com/docs/guide.html#models" rel="noopener noreferrer"&gt;mongoose&lt;/a&gt; docs I have put summerized view of it. Hope you enjoy!!&lt;/p&gt;

&lt;p&gt;Data modeling in MongoDB is a crucial aspect of designing efficient and scalable applications. MongoDB is a NoSQL database that stores data in flexible, JSON-like documents. &lt;/p&gt;

&lt;p&gt;&lt;u&gt;&lt;/u&gt;Key Concepts in MongoDB Data Modeling&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Documents:
A document in MongoDB is a basic unit of data, similar to a row in a relational database. Documents are stored in collections and can have varying structures.
Example:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "_id": ObjectId("507f1f77bcf86cd799439011"),
  "name": "John Doe",
  "age": 30,
  "address": {
    "street": "123 Main St",
    "city": "Anytown",
    "state": "CA"
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Collections:
A collection is a group of MongoDB documents. It is similar to a table in a relational database.
Example:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[
  {
    "_id": ObjectId("507f1f77bcf86cd799439011"),
    "name": "John Doe",
    "age": 30
  },
  {
    "_id": ObjectId("507f1f77bcf86cd799439012"),
    "name": "Jane Smith",
    "age": 25
  }
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Embedded Documents:
MongoDB allows embedding documents within other documents, which can be useful for representing hierarchical data.
Example:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "_id": ObjectId("507f1f77bcf86cd799439011"),
  "name": "John Doe",
  "address": {
    "street": "123 Main St",
    "city": "Anytown",
    "state": "CA"
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Arrays:
Arrays can be used to store multiple values within a single document field.
Example:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "_id": ObjectId("507f1f77bcf86cd799439011"),
  "name": "John Doe",
  "hobbies": ["reading", "hiking", "coding"]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;Let's dive deeper into data modeling in MongoDB by some examples with schemas. MongoDB schemas are typically defined using the Mongoose library in Node.js applications, but the concepts apply to MongoDB in general.&lt;/p&gt;

&lt;h2&gt;
  
  
  Example 1: Blogging Platform
&lt;/h2&gt;

&lt;p&gt;Collections:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Users: Stores information about users.&lt;/li&gt;
&lt;li&gt;Posts: Stores blog posts.&lt;/li&gt;
&lt;li&gt;Comments: Stores comments on blog posts.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;User Schema:&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mongoose = require('mongoose');
const { Schema } = mongoose;

const userSchema = new Schema({
  username: { type: String, required: true, unique: true },
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  createdAt: { type: Date, default: Date.now },
  updatedAt: { type: Date, default: Date.now }
});

const User = mongoose.model('User', userSchema);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;&lt;em&gt;Post Schema:&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const postSchema = new Schema({
  title: "{ type: String, required: true },"
  content: { type: String, required: true },
  author: { type: Schema.Types.ObjectId, ref: 'User', required: true },
  createdAt: { type: Date, default: Date.now },
  updatedAt: { type: Date, default: Date.now },
  comments: [
    {
      type: Schema.Types.ObjectId,
      ref: 'Comment'
    }
  ]
});

const Post = mongoose.model('Post', postSchema);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;&lt;em&gt;Comment Schema:&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const commentSchema = new Schema({
  content: { type: String, required: true },
  author: { type: Schema.Types.ObjectId, ref: 'User', required: true },
  post: { type: Schema.Types.ObjectId, ref: 'Post', required: true },
  createdAt: { type: Date, default: Date.now },
  updatedAt: { type: Date, default: Date.now }
});

const Comment = mongoose.model('Comment', commentSchema);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  All this is fine but How does Mongoose handle schema validation?
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Answer&lt;/strong&gt;: Mongoose provides robust schema validation capabilities that allow you to define rules and constraints for your data. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Basic Validation&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mongoose = require('mongoose');
const { Schema } = mongoose;

const userSchema = new Schema({
  username: { type: String, required: true, unique: true },
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true, minlength: 6 },
  age: { type: Number, min: 18, max: 99 },
  createdAt: { type: Date, default: Date.now },
  updatedAt: { type: Date, default: Date.now }
});

const User = mongoose.model('User', userSchema);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;em&gt;username&lt;/em&gt; and email are required fields.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;password&lt;/em&gt; is required and must be at least 6 characters long.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;age&lt;/em&gt; must be between 18 and 99.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Custom Validation Functions&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Mongoose also allows you to define custom validation functions. These functions can perform more complex validation logic. For example, you can validate that an email address is in a proper format:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const userSchema = new Schema({
  username: { type: String, required: true, unique: true },
  email: {
    type: String,
    required: true,
    unique: true,
    validate: {
      validator: function(v) {
        return /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(v);
      },
      message: props =&amp;gt; `${props.value} is not a valid email address!`
    }
  },
  password: { type: String, required: true, minlength: 6 },
  age: { type: Number, min: 18, max: 99 },
  createdAt: { type: Date, default: Date.now },
  updatedAt: { type: Date, default: Date.now }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;&lt;em&gt;Async Validation&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Mongoose also supports asynchronous validation, which is useful for validation logic that involves database operations. For example, you might want to check if a username already exists:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const userSchema = new Schema({
  username: {
    type: String,
    required: true,
    unique: true,
    validate: {
      isAsync: true,
      validator: function(v, cb) {
        User.findOne({ username: v }, function(err, user) {
          cb(!user);
        });
      },
      message: 'Username already exists!'
    }
  },
  email: {
    type: String,
    required: true,
    unique: true,
    validate: {
      validator: function(v) {
        return /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(v);
      },
      message: props =&amp;gt; `${props.value} is not a valid email address!`
    }
  },
  password: { type: String, required: true, minlength: 6 },
  age: { type: Number, min: 18, max: 99 },
  createdAt: { type: Date, default: Date.now },
  updatedAt: { type: Date, default: Date.now }
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;&lt;em&gt;Built-in Validators&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Mongoose provides several built-in validators for common validation needs:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;required: Ensures the field is not null.&lt;/li&gt;
&lt;li&gt;min and max: Ensures the field is within a specified range.&lt;/li&gt;
&lt;li&gt;enum: Ensures the field value is one of a specified set of values.&lt;/li&gt;
&lt;li&gt;match: Ensures the field value matches a regular expression.&lt;/li&gt;
&lt;li&gt;unique: Ensures the field value is unique across all documents in the collection.
Example with Built-in Validators
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const userSchema = new Schema({
  username: { type: String, required: true, unique: true },
  email: {
    type: String,
    required: true,
    unique: true,
    match: /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/
  },
  password: { type: String, required: true, minlength: 6 },
  age: { type: Number, min: 18, max: 99 },
  gender: {
    type: String,
    enum: ['male', 'female', 'other'],
    required: true
  },
  createdAt: { type: Date, default: Date.now },
  updatedAt: { type: Date, default: Date.now }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;&lt;em&gt;Handling Validation Errors&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When a validation error occurs, Mongoose throws a ValidationError. You can handle these errors in your application logic:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const user = new User({
  username: 'john_doe',
  email: 'john.doe@example.com',
  password: 'password123',
  age: 25
});

user.save((err, user) =&amp;gt; {
  if (err) {
    console.error(err);
    return;
  }
  console.log('User saved:', user);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  what about Real project - how do we handle error in real project ?
&lt;/h2&gt;

&lt;p&gt;Applying validation rules in a real project using Mongoose involves several steps. You need to define your schemas with the appropriate validation rules, handle validation errors in your application logic, and ensure that your application provides meaningful feedback to the user. Below is a step-by-step guide to applying these validation rules in a real project.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Step 1: Define Your Schemas with Validation Rules&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;First, define your Mongoose schemas with the necessary validation rules. Here’s an example of a user schema with various validation rules:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mongoose = require('mongoose');
const { Schema } = mongoose;

const userSchema = new Schema({
  username: {
    type: String,
    required: [true, 'Username is required'],
    unique: true,
    trim: true,
    minlength: [3, 'Username must be at least 3 characters long']
  },
  email: {
    type: String,
    required: [true, 'Email is required'],
    unique: true,
    match: [/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, 'Invalid email address']
  },
  password: {
    type: String,
    required: [true, 'Password is required'],
    minlength: [6, 'Password must be at least 6 characters long']
  },
  age: {
    type: Number,
    min: [18, 'Age must be at least 18'],
    max: [99, 'Age must be less than 100']
  },
  gender: {
    type: String,
    enum: ['male', 'female', 'other'],
    required: [true, 'Gender is required']
  },
  createdAt: { type: Date, default: Date.now },
  updatedAt: { type: Date, default: Date.now }
});

const User = mongoose.model('User', userSchema);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;&lt;em&gt;Step 2: Handle Validation Errors in Your Application Logic&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When you attempt to save a document, Mongoose will automatically validate the data against the schema rules. If validation fails, Mongoose will throw a ValidationError. You need to handle these errors in your application logic.&lt;/p&gt;

&lt;p&gt;Here’s an example of how to handle validation errors in an Express.js route:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require('express');
const mongoose = require('mongoose');
const User = require('./models/User'); // Assume User model is defined in models/User.js

const app = express();
app.use(express.json());

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/mydatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

app.post('/register', async (req, res) =&amp;gt; {
  try {
    const user = new User(req.body);
    await user.save();
    res.status(201).send(user);
  } catch (error) {
    if (error instanceof mongoose.Error.ValidationError) {
      res.status(400).json({ errors: error.errors });
    } else {
      res.status(500).send('Internal Server Error');
    }
  }
});

app.listen(3000, () =&amp;gt; {
  console.log('Server is running on port 3000');
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example:&lt;br&gt;
The /register route attempts to create a new user based on the request body.&lt;br&gt;
If validation fails, Mongoose throws a ValidationError, which is caught and handled.&lt;br&gt;
The response sends a 400 status code with the validation errors.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Step 3: Provide Meaningful Feedback to the User&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When validation fails, it’s important to provide meaningful feedback to the user. Mongoose’s ValidationError object contains detailed information about the validation errors. You can extract this information and send it back to the user.&lt;br&gt;
Here’s an example of how to format the validation errors:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.post('/register', async (req, res) =&amp;gt; {
  try {
    const user = new User(req.body);
    await user.save();
    res.status(201).send(user);
  } catch (error) {
    if (error instanceof mongoose.Error.ValidationError) {
      const errors = Object.values(error.errors).map(err =&amp;gt; ({
        path: err.path,
        message: err.message
      }));
      res.status(400).json({ errors });
    } else {
      res.status(500).send('Internal Server Error');
    }
  }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example:&lt;br&gt;
The validation errors are extracted and formatted into an array of objects, each containing the field path and the error message.&lt;br&gt;
This formatted error information is sent back to the user with a 400 status code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Step 4: Use Middleware for Error Handling&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For larger projects, it’s a good practice to use middleware for error handling. This keeps your route handlers clean and separates error handling logic.&lt;br&gt;
Here’s an example of a custom error handling middleware:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require('express');
const mongoose = require('mongoose');
const User = require('./models/User'); // Assume User model is defined in models/User.js

const app = express();
app.use(express.json());

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/mydatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

// Custom error handling middleware
app.use((err, req, res, next) =&amp;gt; {
  if (err instanceof mongoose.Error.ValidationError) {
    const errors = Object.values(err.errors).map(err =&amp;gt; ({
      path: err.path,
      message: err.message
    }));
    res.status(400).json({ errors });
  } else {
    res.status(500).send('Internal Server Error');
  }
});

app.post('/register', async (req, res) =&amp;gt; {
  const user = new User(req.body);
  await user.save();
  res.status(201).send(user);
});

app.listen(3000, () =&amp;gt; {
  console.log('Server is running on port 3000');
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example:&lt;br&gt;
The custom error handling middleware is added to the Express app.&lt;br&gt;
This middleware catches any ValidationError and formats the errors before sending them back to the user.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Conclusion:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;By defining your schemas with appropriate validation rules, handling validation errors in your application logic, and providing meaningful feedback to the user, you can effectively apply validation rules in a real project using Mongoose. This ensures that your application maintains data integrity and provides a good user experience.&lt;/p&gt;

</description>
      <category>database</category>
      <category>mongoose</category>
      <category>schema</category>
      <category>fullstack</category>
    </item>
    <item>
      <title>Event Loop &amp; Asynchronous JS</title>
      <dc:creator>gunjangidwani</dc:creator>
      <pubDate>Wed, 11 Jun 2025 00:14:13 +0000</pubDate>
      <link>https://forem.com/gunjangidwani/event-loop-asynchronous-js-lek</link>
      <guid>https://forem.com/gunjangidwani/event-loop-asynchronous-js-lek</guid>
      <description>&lt;p&gt;JavaScript is single-threaded, meaning it executes code in a single sequence. But thanks to the Event Loop and asynchronous features like setTimeout, Promises, and async/await, it can handle tasks like I/O operations, timers, and HTTP requests without blocking execution.&lt;/p&gt;

&lt;p&gt;🔁 Event Loop: The Core Concept&lt;br&gt;
The event loop allows JavaScript to perform non-blocking operations by putting them in a queue and continuing to execute other code. When the call stack is clear, it checks the queue and processes the next task.&lt;/p&gt;

&lt;p&gt;🧠 Components Involved:&lt;br&gt;
Call Stack&lt;br&gt;
Where JS code is executed. It's LIFO (Last In, First Out).&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Web APIs (provided by browser)&lt;br&gt;
Handles timers, DOM events, fetch requests, etc.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Callback Queue (Task Queue)&lt;br&gt;
Stores callback functions to be executed after the stack is empty.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Microtask Queue&lt;br&gt;
For promises and queueMicrotask. Has higher priority than the callback queue.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;🔄 How It Works (Simplified Flow)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log("Start");

setTimeout(() =&amp;gt; {
  console.log("Timeout");
}, 0);

Promise.resolve().then(() =&amp;gt; {
  console.log("Promise");
});

console.log("End");

Start
End
Promise
Timeout

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;✅ Why?&lt;br&gt;
console.log("Start") → Synchronous → executed immediately.&lt;/p&gt;

&lt;p&gt;setTimeout(...) → Sent to Web APIs → callback sent to task queue after delay.&lt;/p&gt;

&lt;p&gt;Promise.then(...) → Microtask queue.&lt;/p&gt;

&lt;p&gt;console.log("End") → Synchronous → executed.&lt;/p&gt;

&lt;p&gt;Microtask queue runs: Promise.&lt;/p&gt;

&lt;p&gt;Task queue runs: Timeout.&lt;/p&gt;

&lt;p&gt;📘 Asynchronous JS Tools&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;setTimeout / setInterval – Schedule tasks.&lt;/li&gt;
&lt;li&gt;Promises – Represent a future value.&lt;/li&gt;
&lt;li&gt;async/await – Syntactic sugar for working with promises.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Example with async/await:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async function fetchData() {
  console.log("Fetching...");
  const response = await fetch("https://api.example.com");
  const data = await response.json();
  console.log("Done:", data);
}

fetchData();
console.log("This runs first");

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;📌 Summary&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;JavaScript is non-blocking via the event loop.&lt;/li&gt;
&lt;li&gt;Async operations are deferred via Web APIs and queued via task and microtask queues.&lt;/li&gt;
&lt;li&gt;Promises and async/await make async code more readable and manageable.&lt;/li&gt;
&lt;li&gt;Microtasks (Promises) always run before tasks (setTimeout, etc.).&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>javascript</category>
      <category>interview</category>
      <category>frontendchallenge</category>
      <category>programming</category>
    </item>
    <item>
      <title>Currying !!Wonder of Closures in JavaScript</title>
      <dc:creator>gunjangidwani</dc:creator>
      <pubDate>Wed, 11 Jun 2025 00:05:39 +0000</pubDate>
      <link>https://forem.com/gunjangidwani/currying-wonder-of-closures-in-javascript-4nn8</link>
      <guid>https://forem.com/gunjangidwani/currying-wonder-of-closures-in-javascript-4nn8</guid>
      <description>&lt;h2&gt;
  
  
  *&lt;em&gt;What is currying, and how do closures make it possible in JavaScript? *&lt;/em&gt;
&lt;/h2&gt;

&lt;h2&gt;
  
  
  Currying is hot topic in frontend interview,it is usually the next question after closure because it is an example. Recently i got hit with the &lt;strong&gt;INFINITE CURRYING&lt;/strong&gt; Question. Here is full detail
&lt;/h2&gt;

&lt;p&gt;⚙️ Practical Benefit of Currying:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Delays execution until all arguments are provided&lt;/li&gt;
&lt;li&gt;Enables function reusability (partial application)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Function currying is when functions are nested. This helps us to execute partially functions if there is a requirement of waiting. Example to add two number using curring&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function add() {
  function arg1(a) {
    function arg2(b) {
      return a+b
    }
    return arg2
  }
  return arg1
}

// this returns arg1
const addnum = add()
// this takes first input and  return arg2
const firstArg = add(2);
// taken second input and returns the sum
const final = firstArg(3)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;✅ Clean Curried Add Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function add(a) {
  return function(b) {
    return a + b;
  };
}

console.log(add(2)(3)); // Output: 5

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Explanation:&lt;/p&gt;

&lt;p&gt;add(2) returns a closure that remembers a = 2&lt;br&gt;
That returned function takes b and adds it to a.&lt;/p&gt;

&lt;p&gt;Now if we think the above examples are quite commom. but what about infinite curring? Below is the example of it-&lt;/p&gt;

&lt;p&gt;Can we write a function like add(1)(2)(3)...(n) that returns the sum when we call .value() or even when coerced?&lt;/p&gt;

&lt;p&gt;🧩 Infinite Currying:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You need to return a function every time, so chaining like add(1)(2)(3)... works.&lt;/li&gt;
&lt;li&gt;To get the final result, you’ll use:
.valueOf() or .toString() for coercion (console.log(add(1)(2)(3)))
OR an explicit .value() method.&lt;/li&gt;
&lt;li&gt;Use a closure to keep the running sum.
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function add(a) {
  let sum = a;

  function inner(b) {
    if (b !== undefined) {
      sum += b;
      return inner; // keep returning the function for chaining
    }
    return sum; // fallback, if no argument is passed
  }

  inner.valueOf = function () {
    return sum;
  };

  inner.toString = function () {
    return sum.toString();
  };

  return inner;
}

console.log(+add(1)(2)(3));     // 6
console.log(add(5)(10)(15) + 0); // 30

inner.value = () =&amp;gt; sum;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;📜 1.Another example by arbitrary argument counts in each call? Like:&lt;br&gt;
add(1, 2)(3, 4)(5)(6) // → 21&lt;/p&gt;

&lt;p&gt;Solution-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function sum(...initialArgs) {
  let storage = [...initialArgs];

  function inner(...nextArgs) {
    storage.push(...nextArgs);
    return inner;
  }

  inner.valueOf = function () {
    return storage.reduce((a, b) =&amp;gt; a + b, 0);
  };

  inner.toString = function () {
    return this.valueOf().toString();
  };

  inner.value = function () {
    return this.valueOf();
  };

  return inner;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;📜 2. Add History Tracking (Bonus Closure Feature)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function sumWithHistory(...initialArgs) {
  let storage = [...initialArgs];

  function inner(...nextArgs) {
    if (nextArgs.length === 0) {
      return storage.reduce((a, b) =&amp;gt; a + b, 0);
    }
    storage.push(...nextArgs);
    return inner;
  }

  inner.valueOf = function () {
    return storage.reduce((a, b) =&amp;gt; a + b, 0);
  };

  inner.toString = function () {
    return this.valueOf().toString();
  };

  inner.value = function () {
    return this.valueOf();
  };

  inner.history = function () {
    return [...storage];
  };

  return inner;
}

const s = sumWithHistory(1)(2, 3)(4);
console.log(s.value());       // 10
console.log(s.history());     // [1, 2, 3, 4]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;we can combine these into a reusable curry utility that can handle any reducer function (e.g., sum, product, max, etc.)!&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>interview</category>
      <category>closures</category>
      <category>currying</category>
    </item>
    <item>
      <title>Create a simple Virtualized List/ Sliding Window</title>
      <dc:creator>gunjangidwani</dc:creator>
      <pubDate>Wed, 21 May 2025 19:46:07 +0000</pubDate>
      <link>https://forem.com/gunjangidwani/create-a-simple-virtualized-list-sliding-window-akp</link>
      <guid>https://forem.com/gunjangidwani/create-a-simple-virtualized-list-sliding-window-akp</guid>
      <description>&lt;h2&gt;
  
  
  &lt;strong&gt;Create a simple Virtualized List&lt;/strong&gt;
&lt;/h2&gt;




&lt;p&gt;While many of us have some or the other way have come across the UI performance issues in react which on digging take us to same old simplifying heavy DOM. It can be rendering large list items in list, lazy loading, image optimization, etc.&lt;/p&gt;

&lt;p&gt;With time as the application scales up the simplifying DOM rendering becomes a complex process. Here we are looking into list rendering but in virtual manner. typically we developers use map function to render the list in rows. with this approach rendering thousands of rows browser will create same no. of DOM elements. The DOM in background is using CPU/GPU of users system. This is not it, the CPU consumption increase with user events such as scroll or performing CRUD operations which results reduced framerate, lag on UI, and screen freeze.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;## What is the solution??&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;So how can we display thousands of rows in an efficient way?&lt;br&gt;
Well there are several Libraries such as (react-virtualized) you can find but i want to explain what happens in the bacground of these libraries.&lt;/p&gt;

&lt;p&gt;There is one rule to solve the problem i.e. Render only what is visible!!!&lt;/p&gt;

&lt;p&gt;for example the ui can show only 20 rows at a time then we can write a logic where on user scroll event we cut those 20 rows (slice the array) and render only 20 rows. these rows change on the basis of user scroll.&lt;/p&gt;

&lt;p&gt;we are changing the portion of "Window" or sliding it. this brings us to Sliding Window technique. Sliding Window is very important&lt;br&gt;
approach that involves iterating over a collection of items with a fixed-size window, where the window slides over the collection.&lt;/p&gt;
&lt;h2&gt;
  
  
  *&lt;em&gt;What we need in Sliding Window for virtual List *&lt;/em&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;starting pointer&lt;/li&gt;
&lt;li&gt;end Pointer&lt;/li&gt;
&lt;li&gt;length of the window&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Lets start with the Example - &lt;/p&gt;

&lt;p&gt;We have 100000 rows to display, creating an array -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const LIST = Array.from({ length: 100000 }, (_, index) =&amp;gt; index + 1);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Create a VirtualizedList Component, which will accept the LIST, Div Height, Div Width and item Height. your app.js will look like-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import VirtualizedList from "./Components/VirtualizedList";
import "./styles.css";

const LIST = Array.from({ length: 100000 }, (_, index) =&amp;gt; index + 1);

export default function App() {
  return (
    &amp;lt;div className="App"&amp;gt;
      &amp;lt;VirtualizedList List={LIST} height={400} width={300} itemHeight={35} /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first thing would be get start and end pointer for sliding for our window on list array. We will also calculate the window based on height and itemHeight passed props.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState } from "react";

const VirtualizedList = ({ List, height, width, itemHeight }) =&amp;gt; {
  const [indices, setIndices] = useState([0, Math.floor(height / itemHeight)]);
  const visibleList = List.slice(indices[0], indices[1] + 1);

  return (
    &amp;lt;&amp;gt;
      &amp;lt;div
        style={{ height, width, backgroundColor: "orchid", overflow: "auto" }}
      &amp;gt;
          {visibleList.map((item, index) =&amp;gt; {
            return (
              &amp;lt;div
                key={`item is ${item}`}
                style={{
                  height: itemHeight,
                  backgroundColor: "greenyellow",
                  border: "2px solid grey"
                }}
              &amp;gt;
                item is {item}
              &amp;lt;/div&amp;gt;
            );
          })}
      &amp;lt;/div&amp;gt;
    &amp;lt;/&amp;gt;
  );
};
export default VirtualizedList;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At first the &lt;br&gt;
start index = 0, end index = Math.floor(height / itemHeight);&lt;br&gt;
for initially the visible list is sliced on start and end index.&lt;br&gt;
providing some color abd border to understand the items&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const visibleList = List.slice(indices[0], indices[1] + 1);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we add scroll event but we need to wrap the list div as shown below and add scroll event to parent div. The need to wrap the div is because we need to provide height to scroll with.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;height: List.length * itemHeight
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState } from "react";

const VirtualizedList = ({ List, height, width, itemHeight }) =&amp;gt; {
  const [indices, setIndices] = useState([0, Math.floor(height / itemHeight)]);
  const visibleList = List.slice(indices[0], indices[1] + 1);

  const handleScroll = (e) =&amp;gt; {
    const { scrollTop } = e.target;
    const newStartIndex = Math.floor(scrollTop / itemHeight);
    const newEndIndex = Math.floor(
      newStartIndex + Math.floor(height / itemHeight)
    );
    setIndices([newStartIndex, newEndIndex]);
  };
  return (
    &amp;lt;&amp;gt;
      &amp;lt;div
        onScroll={(e) =&amp;gt; handleScroll(e)}
        style={{ height, width, backgroundColor: "orchid", overflow: "auto" }}
      &amp;gt;
        &amp;lt;div style={{ height: List.length * itemHeight }}&amp;gt;
          {visibleList.map((item, index) =&amp;gt; {
            return (
              &amp;lt;div
                key={`item is ${item}`}
                style={{
                  height: itemHeight,
                  backgroundColor: "greenyellow",
                  border: "2px solid grey",
                }}
              &amp;gt;
                item is {item}
              &amp;lt;/div&amp;gt;
            );
          })}
        &amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/&amp;gt;
  );
};
export default VirtualizedList;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But this won't run as expected because the list changes but the position of item is not visible on ui, to overcome that we will use absolute position with top sum of indices[0] and current index multiple by itemHeight.&lt;/p&gt;

&lt;p&gt;the final code -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState } from "react";

const VirtualizedList = ({ List, height, width, itemHeight }) =&amp;gt; {
  const [indices, setIndices] = useState([0, Math.floor(height / itemHeight)]);
  const visibleList = List.slice(indices[0], indices[1] + 1);

  const handleScroll = (e) =&amp;gt; {
    const { scrollTop } = e.target;
    console.log(scrollTop);
    const newStartIndex = Math.floor(scrollTop / itemHeight);
    const newEndIndex = Math.floor(
      newStartIndex + Math.floor(height / itemHeight)
    );
    setIndices([newStartIndex, newEndIndex]);
  };
  return (
    &amp;lt;&amp;gt;
      &amp;lt;div
        onScroll={(e) =&amp;gt; handleScroll(e)}
        style={{ height, width, backgroundColor: "orchid", overflow: "auto" }}
      &amp;gt;
        &amp;lt;div style={{ height: List.length * itemHeight, position: "relative" }}&amp;gt;
          {visibleList.map((item, index) =&amp;gt; {
            return (
              &amp;lt;div
                key={`item is ${item}`}
                style={{
                  height: itemHeight,
                  backgroundColor: "greenyellow",
                  border: "2px solid grey",
                  textAlign: "center",
                  position: "absolute",
                  width: "100%",
                  top: (indices[0] + index) * itemHeight,
                }}
              &amp;gt;
                item is {item}
              &amp;lt;/div&amp;gt;
            );
          })}
        &amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/&amp;gt;
  );
};
export default VirtualizedList;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For Demo - &lt;a href="https://codesandbox.io/p/github/gunjangidwani/Virtual-List/main?file=%2Fsrc%2FComponents%2FVirtualizedList.jsx%3A1%2C1-47%2C1&amp;amp;workspaceId=ws_DtQDPVrsyYo2ErvRfW2xrK" rel="noopener noreferrer"&gt;https://codesandbox.io/p/github/gunjangidwani/Virtual-List/main?file=%2Fsrc%2FComponents%2FVirtualizedList.jsx%3A1%2C1-47%2C1&amp;amp;workspaceId=ws_DtQDPVrsyYo2ErvRfW2xrK&lt;/a&gt;&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>react</category>
      <category>performance</category>
      <category>webperf</category>
    </item>
  </channel>
</rss>
