<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sadanand Gadwal on Medium]]></title>
        <description><![CDATA[Stories by Sadanand Gadwal on Medium]]></description>
        <link>https://medium.com/@sadanandgadwal?source=rss-7f0303df041e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DhVS9SWIotJH-jPVYkGSvQ.png</url>
            <title>Stories by Sadanand Gadwal on Medium</title>
            <link>https://medium.com/@sadanandgadwal?source=rss-7f0303df041e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 15:56:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sadanandgadwal/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[DOM Manipulation in JavaScript: A Comprehensive Guide]]></title>
            <link>https://medium.com/@sadanandgadwal/dom-manipulation-in-javascript-a-comprehensive-guide-63674dd35772?source=rss-7f0303df041e------2</link>
            <guid isPermaLink="false">https://medium.com/p/63674dd35772</guid>
            <category><![CDATA[dom-manipulation]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[sadanandgadwal]]></category>
            <dc:creator><![CDATA[Sadanand Gadwal]]></dc:creator>
            <pubDate>Fri, 15 May 2026 05:19:47 GMT</pubDate>
            <atom:updated>2026-05-15T07:02:25.726Z</atom:updated>
            <content:encoded><![CDATA[<h4>Mastering Element Selection, Dynamic HTML/CSS Updates, and Event Handling</h4><p>The <strong>Document Object Model (DOM)</strong> is what allows JavaScript to interact with web pages. With DOM manipulation, you can dynamically change content, styles, and behavior — making your websites interactive and powerful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MsFDpKUE9Tw9B6tMhinMaw.png" /></figure><p>This guide follows a structured approach :</p><ul><li>Selecting elements</li><li>Modifying HTML &amp; CSS</li><li>Event handling</li><li>Complete example with explanation</li></ul><h3>1. Selecting Elements</h3><p>To manipulate elements, you first need to select them from the DOM.<br> While some browsers expose elements with id values as global variables, using DOM selection methods is the recommended and more reliable approach.</p><pre>// Select by ID<br>const title = document.getElementById(&quot;title&quot;);<br><br>// Select by class<br>const items = document.getElementsByClassName(&quot;item&quot;);<br><br>// Select using querySelector (first matching element)<br>const button = document.querySelector(&quot;.btn&quot;);<br><br>// Select all matching elements<br>const allItems = document.querySelectorAll(&quot;.item&quot;);</pre><h3>Explanation</h3><ul><li>getElementById() → Selects a single element by its id</li><li>getElementsByClassName() → Returns an HTMLCollection of matching elements</li><li>querySelector() → Selects the first matching element using CSS selectors</li><li>querySelectorAll() → Returns a NodeList of all matching elements, which can be easily looped through</li></ul><h3>2. Modifying HTML Content</h3><p>You can change text or HTML inside elements.</p><pre><br>// Change text<br>heading.textContent = &quot;Welcome to JavaScript!&quot;;<br><br>// Change HTML<br>heading.innerHTML = &quot;&lt;span style=&#39;color:blue&#39;&gt;Welcome!&lt;/span&gt;&quot;;</pre><h3>Explanation:</h3><ul><li>textContent → safe, only text</li><li>innerHTML → allows HTML (be careful with user input)</li></ul><h3>3. Modifying CSS Styles</h3><p>You can directly update styles using JavaScript.</p><pre>const box = document.querySelector(&quot;.box&quot;);<br><br>// Change styles<br>box.style.backgroundColor = &quot;yellow&quot;;<br>box.style.padding = &quot;20px&quot;;<br>box.style.borderRadius = &quot;10px&quot;;const box = document.querySelector(&quot;.box&quot;);</pre><h3>Explanation:</h3><ul><li>Use camelCase (backgroundColor) instead of CSS (background-color)</li><li>Direct styling is useful, but for large apps prefer CSS classes</li></ul><h3>4. Adding &amp; Removing Classes</h3><p>Better way to manage styles dynamically:</p><pre>const card = document.querySelector(&quot;.card&quot;);<br><br>// Add class<br>card.classList.add(&quot;active&quot;);<br><br>// Remove class<br>card.classList.remove(&quot;active&quot;);<br><br>// Toggle class<br>card.classList.toggle(&quot;dark-mode&quot;);</pre><h3>5. Event Handling</h3><p>Events allow interaction (click, hover, input, etc.)</p><pre>const btn = document.querySelector(&quot;#clickBtn&quot;);<br><br>btn.addEventListener(&quot;click&quot;, function() {<br>    alert(&quot;Button clicked!&quot;);<br>});</pre><h3>Arrow Function Version:</h3><pre>btn.addEventListener(&quot;click&quot;, () =&gt; {<br>    console.log(&quot;Clicked using arrow function&quot;);<br>});</pre><h3>Explanation:</h3><ul><li>addEventListener attaches an event</li><li>Common events: click, mouseover, keydown, submit</li></ul><h3>Complete Example :</h3><pre>&lt;h1 id=&quot;title&quot;&gt;Hello World&lt;/h1&gt;<br>&lt;button id=&quot;changeBtn&quot;&gt;Change Text&lt;/button&gt;<br>&lt;div class=&quot;box&quot;&gt;I am a box&lt;/div&gt;</pre><p>Javascript</p><pre>// Selecting elements<br>const title = document.getElementById(&quot;title&quot;);<br>const button = document.getElementById(&quot;changeBtn&quot;);<br>const box = document.querySelector(&quot;.box&quot;);<br><br>// Event handling<br>button.addEventListener(&quot;click&quot;, () =&gt; {<br>    // Modify text<br>    title.textContent = &quot;Text Changed Successfully!&quot;;<br><br>    // Modify style<br>    box.style.backgroundColor = &quot;lightgreen&quot;;<br>    box.style.color = &quot;black&quot;;<br><br>    // Add class<br>    box.classList.toggle(&quot;active&quot;);<br><br>    console.log(&quot;DOM updated!&quot;);<br>});</pre><h3>7. Output Explanation</h3><p>When the button is clicked:</p><ol><li>The heading text changes</li><li>The box color updates</li><li>A class is toggled</li><li>A message is logged in the console</li></ol><h3>8. Console Logs for Debugging</h3><pre>console.log(title);<br>console.log(button);<br>console.log(box)</pre><p>These help verify:</p><ul><li>Elements are selected correctly</li><li>Events are firing</li><li>Changes are applied</li></ul><h3>Conclusion</h3><p>DOM manipulation is the <strong>core of frontend development</strong>. Once you master:</p><ul><li>Selecting elements</li><li>Updating content</li><li>Styling dynamically</li><li>Handling events</li></ul><p>You can build:</p><ul><li>Interactive UIs</li><li>Forms</li><li>Games</li><li>Dashboards</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63674dd35772" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding HTTP Status Codes: A Complete Developer’s Guide]]></title>
            <link>https://medium.com/@sadanandgadwal/understanding-http-status-codes-a-complete-developers-guide-f60bffc34a77?source=rss-7f0303df041e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f60bffc34a77</guid>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[guides-and-tutorials]]></category>
            <category><![CDATA[http-status-code]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[beginner]]></category>
            <dc:creator><![CDATA[Sadanand Gadwal]]></dc:creator>
            <pubDate>Tue, 15 Jul 2025 10:59:59 GMT</pubDate>
            <atom:updated>2025-07-15T10:59:59.648Z</atom:updated>
            <content:encoded><![CDATA[<p>Every time you visit a website, submit a form, or call an API, there’s an invisible conversation taking place between your browser (or client) and a server. That conversation uses <strong>HTTP status codes</strong> to communicate success, failure, or redirection of the request. These three-digit numbers are foundational to understanding how the web works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A94lxluV5sA0BUM9e-6I_Q.png" /></figure><p>This guide will break down HTTP status codes by category, explain what they mean, and show how they impact both users and developers.</p><h3>1xx — Informational Responses</h3><p><strong>1xx codes</strong> are provisional responses. They indicate that the request was received and understood, and that the server is continuing the process.</p><ul><li><strong>100 Continue</strong><br> The initial part of a request has been received and the client should continue sending the rest. Often used with large payloads where the client waits for an acknowledgment before proceeding.</li><li><strong>101 Switching Protocols</strong><br> The client asked the server to switch protocols, and the server has agreed. This is commonly used in upgrading from HTTP to WebSocket connections.</li><li><strong>103 Early Hints</strong><br> Allows the server to preload certain resources before sending the final response. This is a performance optimization used in modern web applications.</li></ul><p><strong>Use case:</strong> These codes are rarely used directly in application logic but are essential for protocol negotiations and improving loading speed.</p><h3>2xx — Successful Responses</h3><p><strong>2xx codes</strong> indicate that the client’s request was successfully received, understood, and accepted.</p><ul><li><strong>200 OK</strong><br> The standard response for successful HTTP requests. The result depends on the request method (GET returns data, POST might return status only).</li><li><strong>201 Created</strong><br> The request was successful and a new resource was created. Commonly used in REST APIs after POST requests.</li><li><strong>202 Accepted</strong><br> The request has been accepted for processing, but the processing is not yet complete. Often used in async job processing.</li><li><strong>204 No Content</strong><br> The server successfully processed the request, but there’s no content to return. This is useful when updating or deleting data without requiring a response body.</li></ul><p><strong>Use case:</strong> These are the most desirable responses for developers. They confirm the expected outcome of an interaction.</p><h3>3xx — Redirection</h3><p><strong>3xx codes</strong> inform the client that further action is needed to complete the request. Usually, this involves following a new URL.</p><ul><li><strong>301 Moved Permanently</strong><br> The requested resource has been permanently moved to a new URL. This is the preferred method for redirecting content without SEO penalties.</li><li><strong>302 Found</strong><br> Temporary redirection. The resource exists at a different URI, but the client should continue to use the original URI for future requests.</li><li><strong>304 Not Modified</strong><br> Indicates that the resource hasn’t changed since the last request. This helps reduce bandwidth by leveraging browser caching.</li></ul><p><strong>Use case:</strong> Redirection codes are vital for maintaining usability, search engine optimization, and performance via caching.</p><h3>4xx — Client Errors</h3><p><strong>4xx codes</strong> indicate that there was an error in the request from the client. The server cannot or will not process the request.</p><ul><li><strong>400 Bad Request</strong><br> The server couldn’t understand the request due to invalid syntax. Often caused by malformed JSON, missing parameters, or incorrect query strings.</li><li><strong>401 Unauthorized</strong><br> The request requires authentication. This often means the client didn’t provide valid credentials (like a token or session).</li><li><strong>403 Forbidden</strong><br> The client is authenticated but does not have permission to access the resource. Different from 401, which is about authentication.</li><li><strong>404 Not Found</strong><br> The requested resource doesn’t exist on the server. This is the most common client error encountered on the web.</li><li><strong>405 Method Not Allowed</strong><br> The request method is not supported for the resource. For example, using a POST method on a resource that only supports GET.</li><li><strong>408 Request Timeout</strong><br> The server didn’t receive a complete request in time. This usually means the client took too long to send the request.</li><li><strong>429 Too Many Requests</strong><br> The user has sent too many requests in a short time. This typically relates to rate limiting in APIs to prevent abuse.</li></ul><p><strong>Use case:</strong> These errors should be handled gracefully in applications with clear user messages. Developers should implement appropriate checks to prevent them.</p><h3>5xx — Server Errors</h3><p><strong>5xx codes</strong> indicate that the request was valid, but the server failed to fulfill it. These are errors on the server side.</p><ul><li><strong>500 Internal Server Error</strong><br> A generic error when the server encounters an unexpected condition. The root cause often lies in server misconfiguration or application bugs.</li><li><strong>501 Not Implemented</strong><br> The server does not support the functionality required to fulfill the request. This may be due to an unsupported HTTP method.</li><li><strong>502 Bad Gateway</strong><br> The server was acting as a gateway or proxy and received an invalid response from the upstream server.</li><li><strong>503 Service Unavailable</strong><br> The server is currently unable to handle the request due to temporary overload or maintenance. Retry may be appropriate.</li><li><strong>504 Gateway Timeout</strong><br> The server, while acting as a gateway or proxy, didn’t receive a timely response from an upstream server.</li></ul><p><strong>Use case:</strong> These errors usually require server-side investigation and should be logged for diagnosis. Users should be shown generic error messages while the issue is addressed.</p><h3>Why These Codes Matter</h3><p>Understanding HTTP status codes isn’t just for backend developers. Here’s why they matter:</p><ul><li><strong>Frontend developers</strong> need them to show the right UI based on the API response.</li><li><strong>API consumers</strong> use them to handle success, retries, and error scenarios efficiently.</li><li><strong>SEO specialists</strong> rely on proper status codes (like 301 vs. 302) to optimize indexing.</li><li><strong>DevOps teams</strong> monitor them to detect outages and scale infrastructure.</li><li><strong>Users</strong> benefit from meaningful feedback and improved experience when errors are handled gracefully.</li></ul><h3>Conclusion</h3><p>HTTP status codes are more than just numbers. They’re a powerful communication tool between client and server, forming the backbone of how the web operates. By understanding and properly using these codes, developers can build more resilient, user-friendly, and maintainable systems.</p><p>Whether you’re designing APIs, debugging client requests, or analyzing traffic logs, a solid grasp of HTTP status codes is essential to mastering web development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f60bffc34a77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering JavaScript: Comprehensive Error Handling Techniques]]></title>
            <link>https://medium.com/@sadanandgadwal/mastering-javascript-comprehensive-error-handling-techniques-99de269a4821?source=rss-7f0303df041e------2</link>
            <guid isPermaLink="false">https://medium.com/p/99de269a4821</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[sadanandgadwal]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[error]]></category>
            <dc:creator><![CDATA[Sadanand Gadwal]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 05:42:01 GMT</pubDate>
            <atom:updated>2025-06-30T06:03:09.535Z</atom:updated>
            <content:encoded><![CDATA[<h3>Errors are inevitable. Good code doesn’t just work when everything goes right — it stays predictable and safe when things go wrong.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uXifC2q5FbMi0xgKqMzrQQ.png" /></figure><p>In JavaScript, error handling is mainly done with three tools:</p><ul><li>try...catch blocks - to catch and handle exceptions</li><li>throw - to create and raise your own errors when something is invalid</li><li>Patterns to handle async errors, because JavaScript is heavily asynchronous</li></ul><p>This article goes beyond the basics. We’ll cover:</p><ul><li>Why JavaScript errors happen</li><li>How try...catch really works under the hood</li><li>The purpose of throw and when to use it</li><li>How to handle errors in promises and async/await</li><li>Real-world design patterns: input validation, fallback values, logging, and user feedback</li></ul><h3>1. What is an error in JavaScript?</h3><pre>// Uncaught ReferenceError<br>console.log(user.name);<br>// ReferenceError: user is not defined</pre><p>When the JavaScript engine encounters a problem it cannot resolve — like trying to access an undefined variable, calling a function that does not exist, or failing to parse data — it throws an error. If this error is not handled, it bubbles up and can crash your script.</p><p>The program stops here if you don’t catch this problem.</p><h3>2. The try-catch mechanism</h3><p><strong>Purpose:</strong> try...catch lets you safely run code that might fail, and handle the failure in a controlled way.</p><p>Basic Syntax</p><pre>try {<br>  // code that might fail<br>} catch (error) {<br>  // code to handle the failure<br>}</pre><p><strong>How it works:</strong></p><ul><li>Code inside the try block runs normally.</li><li>If an error is thrown inside try, JavaScript stops running the rest of try immediately.</li><li>Control jumps to the catch block.</li><li>The catch block gets the error object with information about what went wrong.</li></ul><p>If no error occurs in try, the catch block is skipped entirely.</p><p><strong>Example:</strong> Parsing JSON that might be malformed</p><pre>try {<br>  const jsonString = &#39;{&quot;name&quot;:&quot;Alice&quot;}&#39;;<br>  const user = JSON.parse(jsonString);<br>  console.log(user.name); // Alice<br><br>  // This JSON is invalid: missing quote<br>  const badJson = &#39;{&quot;name&quot;: Alice}&#39;;<br>  JSON.parse(badJson);<br>} catch (err) {<br>  console.error(&quot;JSON parsing failed:&quot;, err.message);<br>}</pre><p>Use try...catch only around risky operations: user input parsing, network requests, file operations.</p><h3>3. The throw statement - creating your own errors</h3><p>Sometimes, your program detects a problem that the JavaScript engine itself would not consider an error. For example, maybe a number is negative when it should not be.</p><p>Basic Syntax</p><pre>throw new Error(&quot;Something went wrong&quot;);</pre><p>To handle this, you can throw your own errors.</p><p>When you throw:</p><ul><li>Execution immediately stops at the throw.</li><li>Control looks for the nearest catch block up the call stack.</li><li>If no catch exists, the program crashes.</li></ul><p><strong>Example:</strong> Validating a function argument</p><pre>function calculateArea(radius) {<br>  if (radius &lt;= 0) {<br>    throw new Error(&quot;Radius must be positive&quot;);<br>  }<br>  return Math.PI * radius * radius;<br>}<br><br>try {<br>  console.log(calculateArea(5)); // Works fine<br>  console.log(calculateArea(-2)); // Throws<br>} catch (err) {<br>  console.error(&quot;Calculation failed:&quot;, err.message);<br>}</pre><p>Use throw when you hit a state that should never happen in correct usage. It enforces contracts: &quot;This function must not get bad input.&quot;</p><h3>4. The finally block - guaranteed cleanup</h3><p>finally always runs, whether the code in try succeeds, fails, or even if you return from try.</p><p>Example</p><pre>try {<br>  console.log(&quot;Opening connection&quot;);<br>  throw new Error(&quot;Connection failed&quot;);<br>} catch (err) {<br>  console.error(&quot;Error:&quot;, err.message);<br>} finally {<br>  console.log(&quot;Closing connection&quot;);<br>}<br><br>// Output:<br>// Opening connection<br>// Error: Connection failed<br>// Closing connection</pre><p>Use finally for closing files or database connections, stopping loaders/spinners, or resetting states.</p><h3>5. Asynchronous code: the common trap</h3><p>JavaScript runs lots of code asynchronously — setTimeout, fetch, promises. try...catch does not automatically catch errors that happen inside callbacks or promises.</p><p>Example</p><pre>try {<br>  setTimeout(() =&gt; {<br>    throw new Error(&quot;Oops&quot;);<br>  }, 1000);<br>} catch (err) {<br>  console.log(&quot;Caught:&quot;, err.message); // Never runs<br>}</pre><h3>How to handle async errors properly</h3><p><strong>A. Wrap inside the async function</strong></p><pre>setTimeout(() =&gt; {<br>  try {<br>    throw new Error(&quot;Oops inside timeout&quot;);<br>  } catch (err) {<br>    console.error(&quot;Caught:&quot;, err.message);<br>  }<br>}, 1000);</pre><p>B. Promises: use .catch</p><pre>fetch(&quot;https://bad.url&quot;)<br>  .then(res =&gt; res.json())<br>  .catch(err =&gt; console.error(&quot;Network or parsing failed:&quot;, err.message));</pre><p>C. Async/await: wrap with try-catch</p><pre>async function fetchUser() {<br>  try {<br>    const response = await fetch(&quot;https://bad.url&quot;);<br>    const data = await response.json();<br>    console.log(data);<br>  } catch (err) {<br>    console.error(&quot;Async/await failed:&quot;, err.message);<br>  }<br>}<br>fetchUser();</pre><h3>6. Real-world example: form validation</h3><p>Putting it together with a user registration check.</p><pre>function registerUser(user) {<br>  if (!user.username) {<br>    throw new Error(&quot;Username is required&quot;);<br>  }<br>  if (user.password.length &lt; 8) {<br>    throw new Error(&quot;Password must be at least 8 characters&quot;);<br>  }<br><br>  return &quot;User registered!&quot;;<br>}<br><br>try {<br>  const user = { username: &quot;John&quot;, password: &quot;123&quot; };<br>  const result = registerUser(user);<br>  console.log(result);<br>} catch (err) {<br>  console.error(&quot;Registration failed:&quot;, err.message);<br>}</pre><h3>7. Logging and rethrowing</h3><p>Catch an error just to log it, then rethrow so a higher-level handler can deal with it.</p><pre>function processData(data) {<br>  try {<br>    if (!data) {<br>      throw new Error(&quot;No data&quot;);<br>    }<br>    // process...<br>  } catch (err) {<br>    console.error(&quot;Log:&quot;, err.message);<br>    throw err; // propagate further<br>  }<br>}<br><br>try {<br>  processData(null);<br>} catch (err) {<br>  console.log(&quot;Final catch:&quot;, err.message);<br>}</pre><h3>8. Best practices</h3><ul><li>Never ignore errors silently.</li><li>Add meaningful, precise messages.</li><li>Use custom error classes for clarity if needed.</li><li>Catch only what you can handle. Don’t catch and swallow everything.</li><li>For async operations, always .catch() promises or use try-catch with await.</li><li>Always log unexpected errors somewhere.</li></ul><h3>Conclusion</h3><p>Bad things happen in software — it’s how you prepare for them that separates a robust application from a fragile one. Handle predictable failures, fail loudly on developer errors, and never let unexpected problems silently break your user’s trust.</p><p>If you understand how try...catch, throw, and async error handling fit together, you have a safety net for whatever the real world throws at your code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99de269a4821" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Scope and Closures in JavaScript: A Deep Dive]]></title>
            <link>https://medium.com/@sadanandgadwal/mastering-scope-and-closures-in-javascript-a-deep-dive-45c9b45203a9?source=rss-7f0303df041e------2</link>
            <guid isPermaLink="false">https://medium.com/p/45c9b45203a9</guid>
            <category><![CDATA[closures-functions]]></category>
            <category><![CDATA[sadanandgadwal]]></category>
            <category><![CDATA[scopes]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sadanand Gadwal]]></dc:creator>
            <pubDate>Fri, 27 Jun 2025 11:25:23 GMT</pubDate>
            <atom:updated>2025-06-28T12:29:33.670Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the most powerful yet confusing concepts in JavaScript is <strong>scope</strong> — and closely tied to it is the concept of <strong>closures</strong>. Understanding scope and closures is essential for writing bug-free, maintainable, and efficient code, especially in complex web applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GllSyZOE1snMgI4MmkMNHg.png" /></figure><h3>1. What Is Scope?</h3><p><strong>Scope</strong> determines <strong>where variables and functions can be accessed</strong> in your code.</p><p>JavaScript has:</p><ol><li><strong>Global Scope</strong></li></ol><p>2.<strong> Local Scope</strong></p><ul><li>Function Scope</li><li>Block Scope (via let and const)</li></ul><p><strong>3. Lexical Scope</strong></p><p>4. <strong>Module Scope</strong></p><h3>1. Global Scope</h3><p>Variables declared <strong>outside any function or block</strong> have <strong>global scope</strong> and can be accessed from anywhere in the code.</p><pre>let siteName = &quot;Sadanand&quot;; // Global scope<br><br>function showSite() {<br>  console.log(siteName); // Accessible here<br>}<br><br>showSite(); // Output: Sadanand</pre><p><strong>Real-world analogy</strong>: Think of a global variable like a public announcement board — anyone (any function) can read from it.</p><h3>2. Local Scope</h3><ol><li>Function Scope</li></ol><p>Variables declared inside a function are <strong>local to that function</strong>.</p><pre>function greet() {<br>  let message = &quot;Hello!&quot;;<br>  console.log(message);<br>}<br><br>greet(); // Output: Hello!<br>console.log(message); // ❌ ReferenceError: message is not defined</pre><p>2. Block Scope (let and const)</p><p>var is <strong>function-scoped</strong>, while let and const are <strong>block-scoped</strong>.</p><pre>{<br>  let x = 10;<br>  const y = 20;<br>  var z = 30;<br>}<br><br>console.log(z); // ✅ 30 (function-scoped)<br>console.log(x); // ❌ ReferenceError<br>console.log(y); // ❌ ReferenceError</pre><p>Avoid using var in modern JS unless necessary. Stick to let and const for safer block-level scoping.</p><h3>3. Lexical Scope</h3><p>Lexical scope means <strong>a function’s scope is defined by its physical placement in the code</strong>. Inner functions have access to variables in their outer (parent) functions.</p><pre>function outer() {<br>  let outerVar = &quot;I&#39;m outside!&quot;;<br><br>  function inner() {<br>    console.log(outerVar); // Has access due to lexical scope<br>  }<br><br>  inner();<br>}<br><br>outer(); // Output: I&#39;m outside!</pre><p>Functions “carry” the scope of where they were defined, not where they are called from.</p><h3>4. Module Scope</h3><p>In modern JavaScript, especially when using ES6 modules (import / export), each module file has its <strong>own scope</strong>.<br> Variables, functions, or classes declared at the top level of a module are <em>module-scoped</em> — they are not added to the global scope.</p><pre>// utils.js<br>export const siteName = &quot;Sadanand&quot;;<br><br>export function greet() {<br>  console.log(&quot;Hello from the module!&quot;);<br>}</pre><pre>// main.js<br>import { siteName, greet } from &quot;./utils.js&quot;;<br><br>console.log(siteName); // &quot;Sadanand&quot;<br>greet(); // &quot;Hello from the module!&quot;</pre><ul><li><strong>Encapsulation:</strong> Code inside a module is <em>private</em> by default. Only exports are accessible outside.</li><li><strong>No global pollution:</strong> Unlike scripts that leak variables into the window object, modules keep top-level declarations isolated.</li></ul><h3>Closures</h3><p>A closure is the combination of a function and the lexical environment (scope) within which that function was declared. This mechanism allows the function to access variables from its outer scope, even after that outer scope has finished executing.</p><pre>function counter() {<br>  let count = 0;<br>  <br>  return function() {<br>    count++;<br>    console.log(count);<br>  };<br>}<br><br>const increment = counter();<br>increment(); // 1<br>increment(); // 2<br>increment(); // 3</pre><h3>Explanation:</h3><ul><li>counter() returns an <strong>inner function</strong>.</li><li>That inner function <strong>closes over</strong> the variable count.</li><li>Even though counter() has already returned, count is still accessible and maintained.</li></ul><h3>Real-World Use Case: Private Variables</h3><p>Closures are widely used to create <strong>private variables</strong> in JavaScript.</p><pre>function BankAccount(initialBalance) {<br>  let balance = initialBalance;<br><br>  return {<br>    deposit(amount) {<br>      balance += amount;<br>      console.log(`Deposited: ${amount}. New Balance: ${balance}`);<br>    },<br>    withdraw(amount) {<br>      if (amount &lt;= balance) {<br>        balance -= amount;<br>        console.log(`Withdrew: ${amount}. New Balance: ${balance}`);<br>      } else {<br>        console.log(&quot;Insufficient funds&quot;);<br>      }<br>    },<br>    checkBalance() {<br>      console.log(`Current Balance: ${balance}`);<br>    }<br>  };<br>}<br><br>const myAccount = BankAccount(1000);<br>myAccount.deposit(500);      // 1500<br>myAccount.withdraw(200);     // 1300<br>myAccount.checkBalance();    // 1300<br>console.log(myAccount.balance); // ❌ undefined (private!)</pre><h3>Key Takeaways</h3><ul><li><strong>Scope</strong> defines <strong>visibility</strong> and <strong>lifetime</strong> of variables.</li><li>Use <strong>let/</strong><strong>const</strong> for <strong>block scoping</strong> and safer code.</li><li><strong>Closures</strong> allow <strong>persistent access</strong> to outer variables.</li><li>Use closures for <strong>data privacy</strong>, <strong>encapsulation</strong>, and <strong>state management</strong>.</li></ul><h3>Bonus: Interview Tip</h3><blockquote><strong><em>Question</em></strong><em>: What is the output?</em></blockquote><p>for (var i = 0; i &lt; 3; i++) {<br> setTimeout(() =&gt; console.log(i), 1000);<br>}</p><p>Why? Because var is function scoped, so by the time the setTimeout runs, the loop is done and i is 3.</p><h3>Conclusion</h3><p>Understanding <strong>scope and closures</strong> is crucial for writing clean, optimized, and bug-free JavaScript. Whether you’re managing state, creating modules, or writing callback functions, closures give you power to <strong>retain context</strong> and <strong>protect data</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45c9b45203a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Objects in  JavaScript : A Comprehensive Guide]]></title>
            <link>https://medium.com/@sadanandgadwal/objects-in-javascript-a-comprehensive-guide-1d625238465c?source=rss-7f0303df041e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d625238465c</guid>
            <category><![CDATA[objects]]></category>
            <category><![CDATA[destructuring]]></category>
            <category><![CDATA[sadanandgadwal]]></category>
            <category><![CDATA[sadanand]]></category>
            <category><![CDATA[objects-in-javascript]]></category>
            <dc:creator><![CDATA[Sadanand Gadwal]]></dc:creator>
            <pubDate>Wed, 17 Jul 2024 06:36:45 GMT</pubDate>
            <atom:updated>2024-07-17T06:36:45.398Z</atom:updated>
            <content:encoded><![CDATA[<h3>Objects in JavaScript : A Comprehensive Guide</h3><blockquote><em>Exploring Object Literals, Properties, Methods, and Object Destructuring, Custom constructors, Mechanism for inheritance and object, and Built-in Objects</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vEe98YJRKYeJ9d17392ghg.png" /></figure><p>JavaScript objects are fundamental to the language, serving as versatile containers for data and functionality. In this article, we’ll explore the various aspects of objects, from their creation using object literals to more advanced topics like methods and destructuring.</p><h4>Object Literals: Creating Objects Simply</h4><p>Object literals are the most straight forward way to create objects in JavaScript. They allow you to define an object and its properties in a concise manner using curly braces {}.</p><pre>// Example of an object literal<br>let person = {<br>    firstName: &#39;Sadanand&#39;,<br>    lastName: &#39;Gadwal&#39;,<br>    age: 30,<br>    greet: function() {<br>        return `Hello, my name is ${this.firstName} ${this.lastName}.`;<br>    }<br>};<br></pre><p>In this example:</p><ul><li><strong>firstName</strong>, <strong>lastName</strong>, and <strong>age</strong> are properties of the object person.</li><li><strong>greet</strong> is a method defined within the object, using a function expression.</li></ul><h4>Accessing Object Properties</h4><p>You can access object properties using dot notation (object.property) or bracket notation (object[&#39;property&#39;]).</p><pre>console.log(person.firstName); // Output: Sadanand<br>console.log(person[&#39;age&#39;]);    // Output: 30<br>console.log(person.greet());  // Output: Hello, my name is Sadanand.</pre><h4>Adding and Modifying Properties</h4><p>Objects in JavaScript are mutable, so you can add new properties or modify existing ones after the object is created.</p><pre>person.email = &#39;sadanand.gadwal@example.com&#39;;<br>person.age = 23; // Modifying existing property</pre><pre>console.log(person.email); // Output: sadanand.gadwal@example.com<br>console.log(person.age);   // Output: 23</pre><h4>Object Methods: Adding Functionality</h4><p>Methods are functions defined within objects, allowing them to perform actions related to the object’s data.</p><pre>let car = {<br>    brand: &#39;Mahindra&#39;,<br>    model: &#39;Thar&#39;,<br>    year: 2024,<br>    displayInfo: function() {<br>        return `${this.year} ${this.brand} ${this.model}`;<br>    }<br>};</pre><pre>console.log(car.displayInfo()); // Output: 2024 Mahindra Thar</pre><h4>Object Destructuring: Simplifying Access</h4><p>Object destructuring provides a concise way to extract properties from objects and bind them to variables.</p><pre>let { firstName, lastName } = person;<br>console.log(firstName); // Output: Sadanand<br>console.log(lastName);  // Output: Gadwal</pre><h4>Real-World Example: Managing Products</h4><p>Imagine you’re building an e-commerce website where you need to manage products. Each product can have various attributes like name, price, and category. You can use objects to represent these products:</p><pre>let product1 = {<br>    name: &#39;Laptop&#39;,<br>    price: 105000,<br>    category: &#39;Electronics&#39;,<br>    getDescription: function() {<br>        return `${this.name} - Rs ${this.price}`;<br>    }<br>};<br>let product2 = {<br>    name: &#39;Smartphone&#39;,<br>    price: 60000,<br>    category: &#39;Electronics&#39;,<br>    getDescription: function() {<br>        return `${this.name} - Rs ${this.price}`;<br>    }<br>};<br>console.log(product1.getDescription()); // Output: Laptop - Rs 105000<br>console.log(product2.getDescription()); // Output: Smartphone - Rs 60000</pre><h3>Custom Constructors: Objects created using constructor functions with new keyword.</h3><p>Custom constructors are functions used to create objects with specific properties and methods. They are invoked using the new keyword.</p><pre>// Example of a constructor function<br>function Car(brand, model, year) {<br>    this.brand = brand;<br>    this.model = model;<br>    this.year = year;<br>    this.displayInfo = function() {<br>        return `${this.year} ${this.brand} ${this.model}`;<br>    };<br>}</pre><pre>// Creating objects using the constructor<br>let myCar = new Car(&#39;Tata&#39;, &#39;harrier&#39;, 2024);<br>let anotherCar = new Car(&#39;Mahindra&#39;, &#39;Thar&#39;, 2024);</pre><pre>console.log(myCar.displayInfo());      // Output: 2024 Tata Harrier<br>console.log(anotherCar.displayInfo()); // Output: 2024 Mahindra Thar</pre><p>In this example:</p><ul><li>Car is a constructor function that defines how a Car object should be created.</li><li>Properties (brand, model, year) are assigned using this.</li><li>displayInfo method is defined within the constructor function to display car information.</li></ul><p>Custom constructors allow for creating multiple objects of the same type with shared properties and methods.</p><h3>Prototypes: Mechanism for inheritance and object extension.</h3><p>Prototypes in JavaScript enable object inheritance and extension. Every JavaScript object has a prototype property, which allows properties and methods to be inherited from another object.</p><pre>// Example of using prototypes<br>function Person(firstName, lastName) {<br>    this.firstName = firstName;<br>    this.lastName = lastName;<br>}</pre><pre>Person.prototype.greet = function() {<br>    return `Hello, my name is ${this.firstName} ${this.lastName}.`;<br>};</pre><pre>let person1 = new Person(&#39;Sadanand&#39;, &#39;Gadwal&#39;);<br>let person2 = new Person(&#39;Tushar&#39;, &#39;Chavan&#39;);</pre><pre>console.log(person1.greet()); // Output: Hello, my name is Sadanand Gadwal.<br>console.log(person2.greet()); // Output: Hello, my name is Tushar Chavan.</pre><p>In this example:</p><ul><li>Person is a constructor function defining a Person object with firstName and lastName properties.</li><li>greet method is added to Person.prototype, allowing all Person instances to access it.</li><li>person1 and person2 are instances of Person that inherit the greet method from Person.prototype.</li></ul><p>Prototypes facilitate efficient memory usage and promote code reusability through inheritance.</p><h3>Built-in Objects: Standard objects like Array, Date, RegExp, etc., provided by JavaScript.</h3><p>JavaScript provides built-in objects that serve common programming needs, such as working with arrays, dates, regular expressions, and more.</p><pre>// Example of using built-in objects<br>let numbers = [1, 2, 3, 4, 5]; // Array object<br>let today = new Date();        // Date object<br>let pattern = /[a-zA-Z]+/;     // RegExp object</pre><pre>console.log(numbers.length);         // Output: 5<br>console.log(today.getFullYear());   // Output: current year<br>console.log(pattern.test(&#39;Hello&#39;)); // Output: true</pre><p>In this example:</p><ul><li>numbers is an instance of the Array object used to store a list of numbers.</li><li>today is an instance of the Date object representing the current date and time.</li><li>pattern is an instance of the RegExp object used to match alphabetical characters in strings.</li></ul><p>Built-in objects provide robust functionality for common tasks in JavaScript programming.</p><h3>Conclusion</h3><p>JavaScript objects are powerful constructs that allow you to encapsulate data and behavior into cohesive units. Whether you’re creating simple data containers or modeling complex real-world entities, understanding objects is crucial for mastering JavaScript.</p><p>In this article, we’ve covered object literals for object creation, accessing properties and methods, modifying objects, object destructuring for convenient property extraction, and provided a practical example of using objects in a real-world scenario.</p><p>By mastering these concepts, you’ll be well-equipped to leverage JavaScript’s object-oriented capabilities effectively in your projects.</p><p>Playground for JavaScript</p><p><a href="https://playcode.io/javascript">Playcode.io</a> is an online code editor and playground that allows users to write, edit, and execute HTML, CSS, and JavaScript code.</p><p>🌟 Stay Connected! 🌟</p><p>Hey there, awesome reader! 👋 Want to stay updated with my latest insights,Follow me on social media!</p><p><a href="https://twitter.com/sadanandgadwal">🐦</a> <a href="https://www.instagram.com/sadanand_gadwal/">📸</a> <a href="https://www.facebook.com/sadanandgadwal7">📘</a> <a href="https://github.com/Sadanandgadwal">💻</a> <a href="https://sadanandgadwal.me/">🌐</a></p><p><a href="https://medium.com/u/7f0303df041e">Sadanand Gadwal</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d625238465c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arrays in JavaScript: A Comprehensive Guide]]></title>
            <link>https://medium.com/@sadanandgadwal/arrays-in-javascript-a-comprehensive-guide-b010c00cc61a?source=rss-7f0303df041e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b010c00cc61a</guid>
            <category><![CDATA[array-methods]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[sadanandgadwal]]></category>
            <category><![CDATA[arrays]]></category>
            <dc:creator><![CDATA[Sadanand Gadwal]]></dc:creator>
            <pubDate>Wed, 19 Jun 2024 06:55:51 GMT</pubDate>
            <atom:updated>2024-06-19T06:55:51.393Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Understanding Array Declaration and Accessing Elements, Array Methods: Adding and Removing Elements and Other Useful Array Methods, Iterating Over Arrays</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T8CDAnDsUE3s48x922rSow.png" /></figure><p>Arrays are fundamental data structures in JavaScript, allowing us to store multiple values in a single variable. They are versatile and come with a variety of methods that make manipulating data efficient and straightforward. In this guide, we’ll explore array basics, methods for adding and removing elements, and best practices for utilizing arrays effectively in your JavaScript code.</p><h4>Declaration and Accessing Elements</h4><p>In JavaScript, you can declare an array using square brackets [] and populate it with elements separated by commas. Arrays can hold any type of data, including numbers, strings, objects, and even other arrays.</p><pre>// Declaration of an array<br>let names = [&#39;Raj&#39;, &#39;Shiva&#39;, &#39;Anand&#39;, &#39;Kumar&#39;];<br><br>// Accessing elements using index<br>console.log(names[0]); // Output: &#39;Raj&#39;<br>console.log(names[2]); // Output: &#39;Anand&#39;</pre><p>Arrays in JavaScript are zero-indexed, meaning the first element is accessed using index 0, the second with index 1, and so on.</p><h4>Array Methods: Adding and Removing Elements</h4><p>JavaScript arrays provide powerful methods for dynamically manipulating their contents:</p><p><strong>push</strong>: Adds one or more elements to the end of an array and returns the new length of the array.</p><pre>names.push(&#39;Ajay&#39;);<br>console.log(names); // Output: [&#39;Raj&#39;, &#39;Shiva&#39;, &#39;Anand&#39;, &#39;Kumar&#39;, &#39;Ajay&#39;]</pre><p><strong>pop</strong>: Removes the last element from an array and returns that element.</p><pre>let lastName = names.pop();<br>console.log(lastName); // Output: &#39;Ajay&#39;<br>console.log(names); // Output: [&#39;Raj&#39;, &#39;Shiva&#39;, &#39;Anand&#39;, &#39;Kumar&#39;]</pre><p><strong>shift</strong>: Removes the first element from an array and returns that element, shifting all other elements one position to the left.</p><pre>let firstName = names.shift();<br>console.log(firstName); // Output: &#39;Raj&#39;</pre><p><strong>unshift</strong>: Adds one or more elements to the beginning of an array and returns the new length of the array.</p><pre>names.unshift(&#39;Vivek&#39;);<br>console.log(names); // Output: [&#39;Vivek&#39;, &#39;Shiva&#39;, &#39;Anand&#39;, &#39;Kumar&#39;]</pre><h4>Useful Array Methods</h4><ul><li><strong>splice</strong>: Changes the contents of an array by removing or replacing existing elements and/or adding new elements.</li></ul><pre>names.splice(2, 0, &#39;Rahul&#39;); // Insert &#39;Rahul&#39; at index 2<br>console.log(names); // Output: [&#39;Vivek&#39;, &#39;Shiva&#39;, &#39;Rahul&#39;, &#39;Anand&#39;, &#39;Kumar&#39;]</pre><ul><li><strong>slice</strong>: Returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included).</li></ul><pre>let selectedNames = names.slice(1, 4); // Returns elements at index 1, 2, and 3<br>console.log(selectedNames); // Output: [&#39;Shiva&#39;, &#39;Rahul&#39;, &#39;Anand&#39;]</pre><ul><li><strong>concat</strong>: Combines two or more arrays and returns a new array.</li></ul><pre>let moreNames = [&#39;Suresh&#39;, &#39;Deepak&#39;];<br>let allNames = names.concat(moreNames);<br>console.log(allNames);</pre><h4>Iterating Over Arrays</h4><p>You can iterate over arrays using loops or array methods like forEach, map, filter, and reduce. Here’s an example using forEach:</p><pre>names.forEach(function(name, index) {<br>    console.log(`Name at index ${index}: ${name}`);<br>});</pre><blockquote><strong>Certainly! coding problems, along with their solutions in JavaScript.</strong></blockquote><h3>Problem 1: Find the Largest Number in an Array</h3><p><strong>Problem Statement:</strong> Write a function that takes an array of numbers as input and returns the largest number in the array.</p><p><strong>Example:</strong> Input: [3, 9, 1, 25, 6] Output: 25</p><p><strong>Solution:</strong></p><pre>function findLargestNumber(arr) {<br>    if (arr.length === 0) {<br>        return null; // Return null for empty array or handle accordingly<br>    }<br>let max = arr[0]; // Assume the first element is the largest initially<br>    for (let i = 1; i &lt; arr.length; i++) {<br>        if (arr[i] &gt; max) {<br>            max = arr[i]; // Update max if current element is larger<br>        }<br>    }<br>    return max;<br>}<br>// Example usage:<br>let numbers = [3, 9, 1, 25, 6];<br>console.log(&quot;Largest number:&quot;, findLargestNumber(numbers)); // Output: 25<br><br>or <br><br>//one-liner version<br>let findLargestNumberOneliner = arr =&gt; arr.length === 0 ? null : arr.reduce((max, current) =&gt; current &gt;= max ? current : max, arr[0]);<br>let numbers1 = [3, 9, 1, 25, 6];<br>console.log(&quot;Largest number:&quot;, findLargestNumberOneliner(numbers1));</pre><p>This one-liner version achieves the same functionality as the original function:</p><ul><li>It uses Array.prototype.reduce to iterate over the array and find the maximum number.</li><li>The initial value of max is set to arr[0], assuming the array is not empty (handled by the ternary operator arr.length === 0 ? null : ...).</li><li>It compares each element current with max and updates max if current is larger.</li></ul><h3>Problem 2: Reverse a String</h3><p><strong>Problem Statement:</strong> Write a function that takes a string as input and returns the string reversed.</p><p><strong>Example:</strong> Input: &quot;hello&quot; Output: &quot;olleh&quot;</p><p><strong>Solution:</strong></p><pre>function reverseString(str) {<br>    return str.split(&#39;&#39;).reverse().join(&#39;&#39;);<br>}<br><br>// Example<br>let str = &quot;hello&quot;;<br>console.log(&quot;Reversed string:&quot;, reverseString(str)); <br>// Output: &quot;olleh&quot;</pre><h3>Explanation:</h3><ul><li><strong>split(&#39;&#39;) : </strong>The split(&#39;&#39;) method splits the string str into an array of characters. If you pass an empty string &#39;&#39; as the delimiter, each character of the string becomes an element in the array.</li><li>For str = &quot;hello&quot;, str.split(&#39;&#39;) returns [&#39;h&#39;, &#39;e&#39;, &#39;l&#39;, &#39;l&#39;, &#39;o&#39;].</li><li><strong>reverse()</strong>: The reverse() method reverses the elements of the array.</li><li>After [&#39;h&#39;, &#39;e&#39;, &#39;l&#39;, &#39;l&#39;, &#39;o&#39;].reverse(), the array becomes [&#39;o&#39;, &#39;l&#39;, &#39;l&#39;, &#39;e&#39;, &#39;h&#39;].</li><li><strong>join(&#39;&#39;)</strong>: The join(&#39;&#39;) method joins all elements of the array into a string.</li><li>[&#39;o&#39;, &#39;l&#39;, &#39;l&#39;, &#39;e&#39;, &#39;h&#39;].join(&#39;&#39;) returns &quot;olleh&quot;.</li><li><strong>Return Statement</strong>: Finally, return str.split(&#39;&#39;).reverse().join(&#39;&#39;); returns the reversed string &quot;olleh&quot;.</li></ul><h3>Problem 3: Remove Duplicates from an Array</h3><p><strong>Problem Statement:</strong> Write a function that takes an array of numbers or strings and returns a new array with duplicates removed.</p><p><strong>Example:</strong> Input: [1, 3, 5, 3, 7, 1, 9, 5] Output: [1, 3, 5, 7, 9]</p><p><strong>Solution:</strong></p><pre>function removeDuplicates(arr) {<br>    let uniqueArray = [];<br><br>for (let i = 0; i &lt; arr.length; i++) {<br>        if (uniqueArray.indexOf(arr[i]) === -1) {<br>            uniqueArray.push(arr[i]);<br>        }<br>    }<br>    return uniqueArray;<br>}<br><br>// Example usage:<br>let numbersWithDuplicates = [1, 3, 5, 3, 7, 1, 9, 5];<br>let uniqueNumbers = removeDuplicates(numbersWithDuplicates);<br>console.log(&quot;Array with duplicates removed:&quot;, uniqueNumbers); // Output: [1, 3, 5, 7, 9]<br><br>or <br><br>//one-liner version<br>let removeDuplicatesOneliner = arr =&gt; [...new Set(arr)];<br>let numbersWithDuplicatesOneliner = [1, 3, 5, 3, 7, 1, 9, 5];<br>let uniqueNumbersOneliner = removeDuplicatesOneliner(numbersWithDuplicatesOneliner);<br>console.log(&quot;Array with duplicates removed:&quot;, uniqueNumbersOneliner);</pre><p>This one-liner version achieves the same functionality as the original function:</p><ul><li><strong>Arrow Function</strong>: removeDuplicates is now written as an arrow function, which simplifies its syntax.</li><li><strong>Set Object</strong>: [...new Set(arr)] utilizes the Set object in JavaScript, which automatically removes duplicate values from an array.</li><li>new Set(arr): Creates a Set object from the array arr, removing duplicates.</li><li>[...new Set(arr)]: Converts the Set object back to an array.</li><li><strong>Example Usage</strong>: The function removeDuplicates is applied to numbersWithDuplicates, resulting in uniqueNumbers, which contains only the unique values from numbersWithDuplicates.</li></ul><h3>Explanation for above questions:</h3><ol><li><strong>Find the Largest Number in an Array:</strong> Iterate through the array, keeping track of the maximum number encountered.</li><li><strong>Reverse a String:</strong> Convert the string to an array of characters, reverse the array, and then join the characters back into a string.</li><li><strong>Remove Duplicates from an Array:</strong> Use an auxiliary array (uniqueArray) to keep track of unique elements encountered so far. Check each element against uniqueArray and add it if it doesn&#39;t already exist.</li></ol><p>These problems are common in interviews because they test basic understanding of algorithms (like searching and sorting) and manipulation of data structures (like arrays and strings). Practice these types of problems to improve your problem-solving skills and familiarity with JavaScript syntax and built-in functions.</p><h4>Conclusion</h4><p>Arrays in JavaScript are powerful and flexible, offering a wide range of methods for manipulating data efficiently. Understanding how to declare, access, and use array methods effectively will enhance your ability to work with collections of data in your JavaScript applications. Experiment with these methods and incorporate them into your projects to become proficient in handling arrays. Happy coding!</p><p>Playground for JavaScript</p><p><a href="https://playcode.io/javascript">Playcode.io</a> is an online code editor and playground that allows users to write, edit, and execute HTML, CSS, and JavaScript code.</p><p>🌟 Stay Connected! 🌟</p><p>Hey there, awesome reader! 👋 Want to stay updated with my latest insights,Follow me on social media!</p><p><a href="https://twitter.com/sadanandgadwal">🐦</a> <a href="https://www.instagram.com/sadanand_gadwal/">📸</a> <a href="https://www.facebook.com/sadanandgadwal7">📘</a> <a href="https://github.com/Sadanandgadwal">💻</a> <a href="https://sadanandgadwal.me/">🌐</a></p><p><a href="https://medium.com/u/7f0303df041e">Sadanand Gadwal</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b010c00cc61a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functions in JavaScript: A Comprehensive Guide]]></title>
            <link>https://medium.com/@sadanandgadwal/functions-in-javascript-a-comprehensive-guide-8973cc7af20c?source=rss-7f0303df041e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8973cc7af20c</guid>
            <category><![CDATA[sadanandgadwal]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[arrow-functions]]></category>
            <category><![CDATA[js]]></category>
            <dc:creator><![CDATA[Sadanand Gadwal]]></dc:creator>
            <pubDate>Sat, 27 Apr 2024 12:31:57 GMT</pubDate>
            <atom:updated>2024-04-27T12:31:57.012Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding Declaration, Parameters, Return Statements, Function Expressions, Arrow Functions, and More</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DfroO02lJMUW0VGjZqASwg.png" /></figure><p>Functions are a fundamental concept in JavaScript, allowing developers to encapsulate code for reuse, organization, and abstraction. In this guide, we’ll explore various aspects of functions in JavaScript, including their declaration, parameters, return statements, function expressions, and arrow functions.</p><h4>1. Declaration of Functions</h4><p>In JavaScript, functions can be declared using the function keyword followed by the function name and a pair of parentheses () containing optional parameters.</p><p>Here&#39;s a basic example:</p><pre>function greet(name) {<br>    return `Hello, ${name}!`;<br>}<br><br>console.log(greet(&#39;sadanand gadwal&#39;)); // Output: Hello, sadanand gadwal!</pre><ul><li>The greet function is declared using the function keyword. It takes a parameter name and returns a greeting message using string interpolation.</li></ul><h4>2. Parameters</h4><p>Functions can accept parameters, which are variables that hold the values passed to the function when it is called. Parameters are declared within the parentheses following the function name.</p><p>Here’s an example:</p><pre>function add(a, b) {<br>    return a + b;<br>}<br><br>console.log(add(5, 3)); // Output: 8</pre><ul><li>The add function takes two parameters a and b and returns their sum.</li><li>The subtract function takes two parameters a and b and returns the result of a - b.</li></ul><h4>3. Return Statements</h4><p>Functions can use the return statement to send a value back to the code that called the function. If a function doesn&#39;t explicitly return a value, it implicitly returns undefined.</p><p>Here&#39;s an example:</p><pre>function subtract(a, b) {<br> return a - b;<br>}<br><br>console.log(subtract(10, 4)); // Output: 6</pre><ul><li>Both add and subtract functions use the return statement to return the result of the arithmetic operation.</li></ul><h4>4. Function Expressions</h4><p>Function expressions define functions as part of an expression, rather than as a declaration. They can be named or anonymous and are often used to assign functions to variables.</p><p>Here’s an example of a named function expression:</p><pre>const multiply = function multiply(a, b) {<br>    return a * b;<br>};<br><br>console.log(multiply(7, 8)); // Output: 56</pre><p>And here’s an example of an anonymous function expression:</p><pre>const divide = function(a, b) {<br>    return a / b;<br>};<br><br>console.log(divide(100, 5)); // Output: 20</pre><ul><li>The multiply function is defined using a named function expression. The function is assigned to the variable multiply.</li><li>The divide function is defined using an anonymous function expression. The function is assigned to the variable divide.</li></ul><h4>5. Arrow Functions</h4><p>Arrow functions are a more concise way to write functions in JavaScript, introduced in ES6. They have a more compact syntax and automatically bind this to the surrounding code&#39;s context. Here&#39;s an example:</p><pre>const square = (x) =&gt; {<br>    return x * x;<br>};<br><br>console.log(square(4)); // Output: 16</pre><p>For simple functions that have only one expression in the body, the curly braces and return keyword can be omitted:</p><pre>const cube = (x) =&gt; x * x * x;<br><br>console.log(cube(3)); // Output: 27</pre><ul><li>The square function is defined using an arrow function. It takes a parameter x and returns the square of x.</li><li>The cube function is also defined using an arrow function, but with a more concise syntax since it has only one expression in its body.</li></ul><h4>6. Example: Using Functions</h4><pre>function calculate(operation, a, b) {<br>    switch (operation) {<br>        case &#39;add&#39;:<br>            return add(a, b);<br>        case &#39;subtract&#39;:<br>            return subtract(a, b);<br>        case &#39;multiply&#39;:<br>            return multiply(a, b);<br>        case &#39;divide&#39;:<br>            return divide(a, b);<br>        default:<br>            return &#39;Invalid operation&#39;;<br>    }<br>}<br><br>console.log(calculate(&#39;add&#39;, 5, 3)); // Output: 8<br>console.log(calculate(&#39;multiply&#39;, 4, 6)); // Output: 24<br>console.log(calculate(&#39;divide&#39;, 10, 2)); // Output: 5<br>console.log(calculate(&#39;power&#39;, 2, 3)); // Output: Invalid operation</pre><ul><li>The calculate function takes three parameters: operation, a, and b. It uses a switch statement to determine which operation to perform (add, subtract, multiply, divide) and calls the corresponding function with the given arguments.</li><li>The switch statement also handles the case when an invalid operation is provided, returning an error message.</li></ul><h3>Conclusion</h3><p>Functions are a powerful feature in JavaScript, allowing developers to write modular and reusable code. Understanding the different ways to declare and use functions is essential for any JavaScript developer.</p><p>Bonus : Complete code :-</p><pre>// Declaration of Functions<br>function greet(name) {<br>    return `Hello, ${name}!`;<br>}<br><br>// Parameters<br>function add(a, b) {<br>    return a + b;<br>}<br><br>// Return Statements<br>function subtract(a, b) {<br>    return a - b;<br>}<br><br>// Function Expressions<br>const multiply = function multiply(a, b) {<br>    return a * b;<br>};<br><br>const divide = function(a, b) {<br>    return a / b;<br>};<br><br>// Arrow Functions<br>const square = (x) =&gt; {<br>    return x * x;<br>};<br><br>const cube = (x) =&gt; x * x * x;<br><br>// Example: Using Functions<br>function calculate(operation, a, b) {<br>    switch (operation) {<br>        case &#39;add&#39;:<br>            return add(a, b);<br>        case &#39;subtract&#39;:<br>            return subtract(a, b);<br>        case &#39;multiply&#39;:<br>            return multiply(a, b);<br>        case &#39;divide&#39;:<br>            return divide(a, b);<br>        default:<br>            return &#39;Invalid operation&#39;;<br>    }<br>}<br><br>console.log(greet(&#39;sadanand gadwal&#39;)); // Output: Hello, sadanand gadwal!<br>console.log(add(5, 3)); // Output: 8<br>console.log(subtract(10, 4)); // Output: 6<br>console.log(multiply(7, 8)); // Output: 56<br>console.log(divide(100, 5)); // Output: 20<br>console.log(square(4)); // Output: 16<br>console.log(cube(3)); // Output: 27<br>console.log(calculate(&#39;add&#39;, 5, 3)); // Output: 8<br>console.log(calculate(&#39;multiply&#39;, 4, 6)); // Output: 24<br>console.log(calculate(&#39;divide&#39;, 10, 2)); // Output: 5<br>console.log(calculate(&#39;power&#39;, 2, 3)); // Output: Invalid operation</pre><p>Playground for JavaScript</p><p><a href="https://playcode.io/javascript">Playcode.io</a> is an online code editor and playground that allows users to write, edit, and execute HTML, CSS, and JavaScript code.</p><p>🌟 Stay Connected! 🌟</p><p>Hey there, awesome reader! 👋 Want to stay updated with my latest insights,Follow me on social media!</p><p><a href="https://twitter.com/sadanandgadwal">🐦</a> <a href="https://www.instagram.com/sadanand_gadwal/">📸</a> <a href="https://www.facebook.com/sadanandgadwal7">📘</a> <a href="https://github.com/Sadanandgadwal">💻</a> <a href="https://sadanandgadwal.me/">🌐</a></p><p><a href="https://medium.com/u/7f0303df041e">Sadanand Gadwal</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8973cc7af20c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering TypeScript: A Comprehensive Guide]]></title>
            <link>https://medium.com/@sadanandgadwal/mastering-typescript-a-comprehensive-guide-eced94781256?source=rss-7f0303df041e------2</link>
            <guid isPermaLink="false">https://medium.com/p/eced94781256</guid>
            <category><![CDATA[sadanandgadwal]]></category>
            <category><![CDATA[type]]></category>
            <category><![CDATA[guides-and-tutorials]]></category>
            <category><![CDATA[script]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Sadanand Gadwal]]></dc:creator>
            <pubDate>Thu, 18 Apr 2024 12:08:54 GMT</pubDate>
            <atom:updated>2024-04-20T06:09:07.665Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>From Fundamentals to Intermediate Techniques for Effective Development</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ewtrvyogNAT2fYI2tr0_jQ.png" /></figure><p>TypeScript is an open-source programming language developed by Microsoft that builds upon JavaScript by adding optional static typing, interfaces, classes, and other features to help developers write robust and scalable code. It compiles to plain JavaScript, making it compatible with existing JavaScript frameworks and libraries, while providing additional tooling and language features to improve developer productivity and code quality.</p><h3>Beginner Level:</h3><h4>Understand JavaScript Fundamentals:</h4><p>JavaScript fundamentals include knowledge of variables, data types, functions, objects, arrays, and control flow.</p><pre>// Variables<br>let x = 5;<br>const y = &quot;Hello&quot;;<br><br>// Data Types<br>let num = 10; // Number<br>let str = &quot;Hello&quot;; // String<br>let bool = true; // Boolean<br>let arr = [1, 2, 3]; // Array<br>let obj = { name: &quot;sadanandgadwal&quot;, age: 23 }; // Object<br><br>// Functions<br>function greet(name) {<br>  return &quot;Hello, &quot; + name + &quot;!&quot;;<br>}<br>console.log(greet(&quot;sadanandgadwal&quot;)); // Output: Hello, sadanandgadwal!<br><br>// Objects<br>let person = {<br>  name: &quot;sadanandgadwal&quot;,<br>  age: 23,<br>  greet: function() {<br>    return &quot;Hello, &quot; + this.name + &quot;!&quot;;<br>  }<br>};<br>console.log(person.greet()); // Output: Hello, sadanandgadwal!</pre><h4>1) Introduction to TypeScript:</h4><p>TypeScript is a superset of JavaScript that adds optional static typing, interfaces, classes, and modules among other features.</p><pre><br>function greet(name: string): string {<br>  return &quot;Hello, &quot; + name + &quot;!&quot;;<br>}<br>console.log(greet(&quot;sadanandgadwal&quot;)); // Output: Hello, sadanandgadwal!<br><br>interface Person {<br>  name: string;<br>  age: number;<br>}<br>function greetPerson(person: Person): string {<br>  return &quot;Hello, &quot; + person.name + &quot;!&quot;;<br>}<br><br>console.log(greetPerson({ name: &quot;sadanandgadwal&quot;, age: 23 })); // Output: Hello, sadanandgadwal!</pre><ol><li>The greet function is defined, which takes a name parameter of type string and returns a string greeting.</li><li>The greet function is called with the argument &quot;sadanandgadwal&quot; and the returned value is logged to the console.</li><li>An interface named Person is defined, specifying that any object implementing it must have a name property of type string and an age property of type number.</li><li>The greetPerson function is defined, which takes a person parameter of type Person interface and returns a string greeting.</li><li>The greetPerson function is called with an object that satisfies the Person interface, and the returned value is logged to the console.</li></ol><h4>Setting Up Development Environment:</h4><p>Setting up the development environment involves installing Node.js and npm and configuring a TypeScript compiler like tsc.</p><pre># Install Node.js and npm<br># Download and install from https://nodejs.org/<br><br># Install TypeScript globally<br>npm install -g typescript<br><br># Create a TypeScript file (example.ts)<br># Run the TypeScript compiler to generate JavaScript<br>tsc example.ts</pre><h4>2) Basic TypeScript Syntax:</h4><p>Basic TypeScript syntax includes declaring variables with types, understanding type inference, and using basic type annotations and assertions.</p><pre>// Variable Declaration<br>let x: number = 5; <br>const y: string = &quot;Hello&quot;;<br><br>// Type Inference<br>let num = 10; <br>let str = &quot;Hello&quot;;<br><br>// Basic Type Annotations and Assertions<br>let z: boolean; <br>z = true; <br><br>// Type Assertion<br>let someValue: any = &quot;this is a string&quot;; <br>let strLength: number = (someValue as string).length; <br>// Alternatively, you could use angle bracket syntax: let strLength: number = (&lt;string&gt;someValue).length;<br><br>console.log(x); // Output: 5<br>console.log(y); // Output: Hello<br>console.log(num); // Output: 10<br>console.log(str); // Output: Hello<br>console.log(z); // Output: true<br>console.log(strLength); // Output: 16</pre><ol><li>The variable x is declared as a number and assigned the value 5.</li><li>The constant y is declared as a string and assigned the value &quot;Hello&quot;.</li><li>TypeScript infers the types of variables num and str based on their initial values.</li><li>The variable z is declared as a boolean and assigned the value true.</li><li>Type assertion is used to treat someValue as a string in order to access its length property, and the result is stored in strLength.</li><li>All variables are logged to the console to demonstrate their values.</li></ol><h4>3) Functions and Interfaces:</h4><p>In TypeScript, you can define function types and use interfaces to define object shapes and enforce contracts.</p><pre>// Function Types<br>type GreetFunction = (name: string) =&gt; string;<br><br>// Declare a variable<br>let greet: GreetFunction = function(name: string) {<br>  return &quot;Hello, &quot; + name + &quot;!&quot;;<br>};<br>console.log(greet(&quot;sadanandgadwal&quot;)); // Output: Hello, sadanandgadwal!<br><br>// Interface<br>interface Person {<br>  name: string;<br>  age: number;<br>}<br><br>function greetPerson(person: Person): string {<br>  return &quot;Hello, &quot; + person.name + &quot;!&quot;;<br>}<br><br>console.log(greetPerson({ name: &quot;sadanandgadwal&quot;, age: 23 })); // Output: Hello, sadanandgadwal!</pre><ol><li>A type alias GreetFunction is defined for a function that takes a name parameter of type string and returns a string.</li><li>A variable greet of type GreetFunction is declared and assigned a function expression that matches the defined function type.</li><li>The greet function is called with the argument &quot;sadanandgadwal&quot; and the returned value is logged to the console.</li><li>An interface Person is defined with properties name of type string and age of type number.</li><li>The greetPerson function is defined, which takes a parameter person of type Person interface and returns a string greeting.</li><li>The greetPerson function is called with an object that satisfies the Person interface, and the returned value is logged to the console.</li></ol><h4>4) Working with Classes:</h4><p>Classes and inheritance in TypeScript allow you to create blueprints for objects with methods and properties.</p><pre>// Class<br>class Person {<br>  name: string;<br>  age: number;<br><br>  // Define a constructor<br>  constructor(name: string, age: number) {<br>    this.name = name;<br>    this.age = age;<br>  }<br><br>  greet(): string {<br>    return &quot;Hello, &quot; + this.name + &quot;!&quot;;<br>  }<br>}<br><br>let person = new Person(&quot;sadanandgadwal&quot;, 23);<br>console.log(person.greet()); // Output: Hello, sadanandgadwal!</pre><ol><li>A class Person is defined with properties name and age, and a constructor function that initializes these properties when a new object is created.</li><li>The class Person has a method named greet that returns a greeting message using the name property.</li><li>A new instance of the Person class is created with the name &quot;sadanandgadwal&quot; and age 23.</li><li>The greet method of the person object is called and the returned value is logged to the console.</li></ol><h3>Intermediate Level :</h3><h4>1) Advanced Types:</h4><p>Advanced types in TypeScript include union types, intersection types, type aliases, conditional types, etc.</p><pre>// Union Types<br>let val: number | string;<br>val = 10; <br>val = &quot;Hello&quot;; <br><br>// Intersection Types<br>interface A {<br>  propA: number;<br>}<br>interface B {<br>  propB: string;<br>}<br>type C = A &amp; B;<br>let obj: C = { propA: 10, propB: &quot;Hello&quot; };<br><br>// Conditional Types<br>type TypeName&lt;T&gt; = T extends string ? &quot;string&quot; :<br>                   T extends number ? &quot;number&quot; :<br>                   T extends boolean ? &quot;boolean&quot; :<br>                   &quot;unknown&quot;;<br>let a: TypeName&lt;string&gt; = &quot;string&quot;; // Output: &quot;string&quot;<br>let b: TypeName&lt;number&gt; = &quot;number&quot;; // Output: &quot;number&quot;<br>let c: TypeName&lt;boolean&gt; = &quot;boolean&quot;; // Output: &quot;boolean&quot;<br>let d: TypeName&lt;object&gt; = &quot;unknown&quot;; // Output: &quot;unknown&quot;<br><br>console.log(val); // Output: Hello<br>console.log(obj); // Output: { propA: 10, propB: &quot;Hello&quot; }<br>console.log(a);   // Output: string<br>console.log(b);   // Output: number<br>console.log(c);   // Output: boolean<br>console.log(d);   // Output: unknown</pre><ol><li>A variable val is declared that can hold values of type number or string.</li><li>An object obj is declared with properties from both interfaces A and B, which are then assigned to a variable of type C, an intersection of A and B.</li><li>Conditional types are used to define a type TypeName&lt;T&gt; that returns different strings based on the type of T.</li><li>Variables a, b, c, and d are declared with different type arguments for TypeName and assigned values accordingly.</li><li>All variables are logged to the console to demonstrate their values.</li></ol><h4>2) Generics:</h4><p>Generics allow you to write reusable, type-safe functions, interfaces, and classes.</p><pre>// Generic Function<br>function identity&lt;T&gt;(arg: T): T {<br>  return arg;<br>}<br>let num: number = identity(10); // Output: 10<br>let str: string = identity(&quot;Hello&quot;); // Output: &quot;Hello&quot;<br><br>// Generic Interface<br>interface Box&lt;T&gt; {<br>  value: T;<br>}<br>let box: Box&lt;number&gt; = { value: 10 };<br><br>// Generic Class<br>class Pair&lt;T, U&gt; {<br>  constructor(public first: T, public second: U) {}<br>}<br><br>let pair: Pair&lt;number, string&gt; = new Pair(10, &quot;Hello&quot;);<br>console.log(num); // Output: 10<br>console.log(str); // Output: Hello<br>console.log(box); // Output: { value: 10 }<br>console.log(pair); // Output: Pair { first: 10, second: &quot;Hello&quot; }</pre><ol><li>A generic function identity is defined that takes an argument arg of type T and returns the same type T.</li><li>The identity function is called with a number and a string, and the returned values are assigned to variables num and str respectively.</li><li>A generic interface Box&lt;T&gt; is defined with a single property value of type T.</li><li>A variable box of type Box&lt;number&gt; is created with a value property of type number.</li><li>A generic class Pair&lt;T, U&gt; is defined with two properties first of type T and second of type U.</li><li>An instance pair of the Pair&lt;number, string&gt; class is created with values 10 and &quot;Hello&quot;.</li><li>All variables are logged to the console to demonstrate their values.</li></ol><h4>3) Modules and Namespaces:</h4><p>Modules in TypeScript allow you to organize code into reusable units. Namespaces provide a way to logically group related code.</p><pre>// math.ts<br>export function sum(a: number, b: number): number {<br>  return a + b;<br>}<br><br>// app.ts<br>import { sum } from &quot;./math&quot;;<br>console.log(sum(2, 3)); // Output: 5<br><br>// namespace<br>namespace Math {<br>  export function sum(a: number, b: number): number {<br>    return a + b;<br>  }<br>}<br><br>// app.ts<br>/// &lt;reference path=&quot;math.ts&quot; /&gt;<br>console.log(Math.sum(2, 3)); // Output: 5</pre><ol><li>The math.ts file defines a function sum in the module math that takes two numbers and returns their sum.</li><li>In app.ts, the sum function is imported from the math module using the import statement, and the result of sum(2, 3) is logged to the console.</li><li>A namespace Math is defined in math.ts containing a function sum that calculates the sum of two numbers.</li><li>In app.ts, the sum function from the Math namespace is used by referencing the math.ts file using /// &lt;reference path=&quot;math.ts&quot; /&gt;, and the result of Math.sum(2, 3) is logged to the console.</li></ol><h4>4) Decorators:</h4><p>Decorators are a feature of TypeScript that allow you to attach metadata to classes, methods, and properties.</p><pre>// Class Decorator<br>function Logged(target: Function) {<br>  console.log(&quot;Class logged:&quot;, target);<br>}<br><br>//&#39;MyClass&#39; class.<br>@Logged<br>class MyClass {}<br><br>// Method Decorator<br>function Log(target: any, key: string, descriptor: PropertyDescriptor) {<br>  console.log(&quot;Method logged:&quot;, key);<br>}<br><br>// Define a class &#39;MyService&#39;.<br>class MyService {<br>  @Log<br>  getData() {}<br>}<br><br>// Property Decorator<br>function Configurable(value: boolean) {<br>  return function(target: any, propertyKey: string) {<br>    Object.defineProperty(target, propertyKey, {<br>      configurable: value<br>    });<br>  };<br>}<br><br>// Define a class &#39;MyComponent&#39;.<br>class MyComponent {<br>  @Configurable(false)<br>  apiUrl = &quot;https://example.com&quot;;<br>}<br><br>// Console output<br>console.log(MyClass);<br>new MyService().getData();<br>console.log(Object.getOwnPropertyDescriptor(MyComponent.prototype, &quot;apiUrl&quot;));</pre><ol><li>A class decorator Logged is defined that logs a message when applied to a class.</li><li>The Logged decorator is applied to the MyClass class, resulting in a log message when the class is defined.</li><li>A method decorator Log is defined that logs a message when applied to a method.</li><li>The Log decorator is applied to the getData method of the MyService class, resulting in a log message when the method is accessed.</li><li>A property decorator factory Configurable is defined that returns a property decorator function.</li><li>The Configurable decorator is applied to the apiUrl property of the MyComponent class, setting its configurable property to false.</li><li>Console output shows the log messages and the property descriptor for the apiUrl property.</li></ol><h4>5) Error Handling:</h4><p>Understanding how TypeScript handles errors and exceptions, including synchronous and asynchronous error handling strategies.</p><pre>// Synchronous Error Handling<br>function divide(x: number, y: number): number {<br>  if (y === 0) {<br>    throw new Error(&quot;Division by zero&quot;);<br>  }<br>  return x / y;<br>}<br><br>//try-catch block<br>try {<br>  console.log(divide(10, 0)); // Output: Error: Division by zero<br>} catch (error) {<br>  console.error(error.message);<br>}<br><br>// Asynchronous Error Handling<br>async function fetchData() {<br>  try {<br>    let response = await fetch(&quot;https://example.com/data&quot;);<br>    if (!response.ok) {<br>      throw new Error(&quot;Failed to fetch data&quot;);<br>    }<br>    let data = await response.json();<br>    console.log(data);<br>  } catch (error) {<br>    console.error(error.message);<br>  }<br>}<br>fetchData();</pre><ol><li>The divide function is defined to divide two numbers and throw an error if the second number is zero.</li><li>A try-catch block is used to handle errors that may occur during the execution of the divide function.</li><li>An asynchronous function fetchData is defined to fetch data from a remote URL using fetch.</li><li>The fetchData function uses a try-catch block to handle errors that may occur during the fetch operation or parsing of the response.</li><li>The fetchData function is called to initiate the asynchronous data fetching process. Any errors that occur are logged to the console.</li></ol><h3>Conclusion</h3><p>This guide covered TypeScript essentials, from syntax to advanced features like generics and decorators. Error handling strategies and integration with frameworks were explored. Mastering TypeScript empowers developers to create scalable, organized codebases, contributing effectively to modern web development projects.</p><p>Playground for Typescript</p><p><a href="https://playcode.io/typescript">Playcode.io</a> is an online code editor and playground that allows users to write, edit, and execute HTML, CSS, and JavaScript code and even Typescript.</p><p>🌟 Stay Connected! 🌟</p><p>Hey there, awesome reader! 👋 Want to stay updated with my latest insights,Follow me on social media!</p><p><a href="https://twitter.com/sadanandgadwal">🐦</a> <a href="https://www.instagram.com/sadanand_gadwal/">📸</a> <a href="https://www.facebook.com/sadanandgadwal7">📘</a> <a href="https://github.com/Sadanandgadwal">💻</a> <a href="https://sadanandgadwal.me/">🌐</a></p><p><a href="https://medium.com/u/7f0303df041e?source=post_page-----ed947b45461d--------------------------------">Sadanand Gadwal</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eced94781256" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Control Structures in JavaScript : A Comprehensive Guide — MERN STACK Series]]></title>
            <link>https://medium.com/@sadanandgadwal/understanding-control-structures-in-javascript-a-comprehensive-guide-mern-stack-series-ed947b45461d?source=rss-7f0303df041e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed947b45461d</guid>
            <category><![CDATA[sadanandgadwal]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[control-statements]]></category>
            <dc:creator><![CDATA[Sadanand Gadwal]]></dc:creator>
            <pubDate>Fri, 12 Apr 2024 11:10:11 GMT</pubDate>
            <atom:updated>2024-04-12T11:10:11.126Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding <strong>Control Structures in JavaScript</strong> : A Comprehensive Guide — MERN STACK Series</h3><blockquote><strong>A Deep Dive into If Statements, Switch Statements, and Loops</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LIX-pYJacAP2Ku-r2JpQ-A.png" /></figure><h3><strong>Introduction:</strong></h3><p>Control structures are fundamental building blocks in programming that allow developers to control the flow of execution in their code. In JavaScript, control structures such as if statements, switch statements, and loops (for, while, do-while) play a crucial role in determining the behavior of a program. In this blog post, we’ll explore these control structures in depth, providing clear explanations, code examples, and real-world scenarios to help you master them.</p><h4>1) If Statement:</h4><p>The if statement is a fundamental control structure in JavaScript used to execute a block of code if a specified condition evaluates to true.</p><pre>let num = 10;<br>if (num &gt; 0) {<br>    console.log(&quot;Number is positive&quot;);<br>}<br></pre><ul><li>In the above example, if the variable num is greater than 0, the message &quot;Number is positive&quot; will be logged to the console.</li><li>If the condition inside the if statement evaluates to false, the code block will not be executed.</li></ul><p><strong>Real-World Example:</strong></p><ul><li>Consider a shopping website where you want to apply a discount based on the total purchase amount. You can use if statements to check different conditions and apply discounts accordingly.</li></ul><h4>2) If-Else Statement:</h4><p>The if-else statement allows us to execute one block of code if the condition is true and another block if the condition is false.</p><pre>let num = -5;<br>if (num &gt; 0) {<br>    console.log(&quot;Number is positive&quot;);<br>} else {<br>    console.log(&quot;Number is not positive&quot;);<br>}</pre><ul><li>The if statement checks if num is greater than 0.</li><li>If the condition is true, it executes the code block inside the curly braces.</li><li>If the condition is false, it moves to the next else if statement or the else block if provided.</li></ul><p><strong>Real-World Example:</strong></p><ul><li>Consider a shopping website where you want to apply a discount based on the total purchase amount. You can use if statements to check different conditions and apply discounts accordingly.</li></ul><h4><strong>3) Switch Statements:</strong></h4><p>Switch statements provide an efficient way to handle multiple conditions by evaluating an expression and executing the corresponding case.</p><pre>let day = &quot;Monday&quot;;<br>switch (day) {<br>    case &quot;Monday&quot;:<br>        console.log(&quot;Today is Monday&quot;);<br>        break;<br>    case &quot;Tuesday&quot;:<br>        console.log(&quot;Today is Tuesday&quot;);<br>        break;<br>    default:<br>        console.log(&quot;Unknown day&quot;);<br>}</pre><ul><li>The switch statement evaluates the value of day and compares it against each case label.</li><li>If a match is found, the corresponding block of code is executed.</li><li>The break statement is used to exit the switch statement after a match is found.</li></ul><p><strong>Real-World Example:</strong></p><ul><li>A grading system where you want to assign grades based on the student’s score. Switch statements can be used to evaluate different score ranges and assign grades accordingly.</li></ul><h4>4) Ternary Operator (Conditional Operator):</h4><p>The ternary operator is a concise way to write if-else statements in a single line</p><p><strong>Syntax:</strong> The ternary operator has the following syntax:</p><pre>condition ? expression1 : expression2</pre><ul><li>If the condition evaluates to true, expression1 is executed.</li><li>If the condition evaluates to false, expression2 is executed.</li></ul><p>Let’s consider a simple example of using the ternary operator to determine whether a number is even or odd:</p><pre>const num = 7;<br>const result = num % 2 === 0 ? &quot;Even&quot; : &quot;Odd&quot;;<br>console.log(result); // Output: &quot;Odd&quot;</pre><ul><li>In this example, the condition num % 2 === 0 checks if num is divisible by 2 without a remainder.</li><li>If the condition is true, &quot;Even&quot; is assigned to result.</li><li>If the condition is false, &quot;Odd&quot; is assigned to result.</li></ul><p><strong>Real-World Example:</strong> Consider a scenario where you want to display a message based on whether a user is logged in:</p><pre>const isLoggedIn = true;<br>const message = isLoggedIn ? &quot;Welcome, User!&quot; : &quot;Please log in to continue.&quot;;<br>console.log(message);</pre><ul><li>If isLoggedIn is true, the message &quot;Welcome, User!&quot; will be displayed.</li><li>If isLoggedIn is false, the message &quot;Please log in to continue.&quot; will be displayed.</li></ul><h4><strong>5) Loops:</strong></h4><p>Loops are used to execute a block of code repeatedly as long as a specified condition is true. JavaScript provides several types of loops: for, while, and do-while.</p><p><strong>i) For Loop:</strong></p><p>The for loop is used to iterate over a block of code a specified number of times.</p><pre>for (let i = 0; i &lt; 5; i++) {<br>    console.log(&quot;Iteration: &quot; + i);<br>}</pre><ul><li>The for loop consists of three parts: initialization, condition, and increment/decrement.</li><li>It initializes a variable i to 0, checks if i is less than 5, and increments i by 1 in each iteration.</li></ul><p><strong>Real-World Example:</strong></p><ul><li>Displaying a list of products on an e-commerce website. You can use a for loop to iterate over the products array and display each product on the webpage.</li></ul><p><strong>ii) While Loop:</strong> The while loop is used to execute a block of code as long as a specified condition is true.</p><pre>let count = 0;<br>while (count &lt; 5) {<br>    console.log(&quot;Count: &quot; + count);<br>    count++;<br>}</pre><ul><li>The while loop checks the condition before executing the code block.</li><li>It continues to execute the code block as long as the condition (count &lt; 5) remains true.</li></ul><p><strong>Real-World Example:</strong></p><ul><li>Implementing a countdown timer on a website. You can use a while loop to decrement the timer value until it reaches zero.</li></ul><p><strong>iii) Do-While Loop:</strong> The do-while loop is similar to the while loop, but it executes the code block at least once before checking the condition.</p><pre>let x = 1;<br>do {<br>    console.log(&quot;Number: &quot; + x);<br>    x++;<br>} while (x &lt;= 5);</pre><ul><li>The do-while loop executes the code block first and then checks the condition (x &lt;= 5).</li><li>It continues to execute the code block as long as the condition remains true.</li></ul><p><strong>Real-World Example:</strong></p><ul><li>Prompting the user to enter a valid password. You can use a do-while loop to repeatedly ask for input until the user enters a valid password.</li></ul><h3><strong>Conclusion</strong></h3><p>Mastering control structures such as if statements, switch statements, and loops is essential for becoming proficient in JavaScript programming. By understanding how these control structures work and practicing with real-world examples, you’ll be able to write more efficient and organized code. Experiment with different scenarios and explore additional features and functionalities to enhance your coding skills.</p><p>Playground for JavaScript</p><p><a href="https://playcode.io/javascript">Playcode.io</a> is an online code editor and playground that allows users to write, edit, and execute HTML, CSS, and JavaScript code.</p><p>🌟 Stay Connected! 🌟</p><p>Hey there, awesome reader! 👋 Want to stay updated with my latest insights,Follow me on social media!</p><p><a href="https://twitter.com/sadanandgadwal">🐦</a> <a href="https://www.instagram.com/sadanand_gadwal/">📸</a> <a href="https://www.facebook.com/sadanandgadwal7">📘</a> <a href="https://github.com/Sadanandgadwal">💻</a> <a href="https://sadanandgadwal.me/">🌐</a></p><p><a href="https://medium.com/u/7f0303df041e">Sadanand Gadwal</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed947b45461d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding JavaScript Operators : A Comprehensive Guide — MERN STACK Series]]></title>
            <link>https://medium.com/@sadanandgadwal/understanding-javascript-operators-a-comprehensive-guide-mern-stack-series-b29e8be761f1?source=rss-7f0303df041e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b29e8be761f1</guid>
            <category><![CDATA[js]]></category>
            <category><![CDATA[operators]]></category>
            <category><![CDATA[sadanandgadwal]]></category>
            <category><![CDATA[mern-stack]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sadanand Gadwal]]></dc:creator>
            <pubDate>Mon, 01 Apr 2024 06:10:05 GMT</pubDate>
            <atom:updated>2024-04-01T06:10:05.354Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding JavaScript Operators : A Comprehensive Guide — MERN STACK Series</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5fSxEu6JBQDLH5LQEbNVrw.png" /></figure><p>JavaScript operators are fundamental components of the language, enabling developers to perform various actions on data. From basic arithmetic calculations to complex logical operations, operators play a crucial role in programming. In this blog, we’ll explore the different types of operators in JavaScript, along with code examples and real-world use cases.</p><p><strong>Arithmetic Operators:</strong></p><ol><li>Addition (+): Adds two operands.</li><li>Subtraction (-): Subtracts the right operand from the left operand.</li><li>Multiplication (*): Multiplies two operands.</li><li>Division (/): Divides the left operand by the right operand.</li><li>Modulus (%): Returns the remainder of the division of the left operand by the right operand.</li><li>Exponentiation (**): Raises the left operand to the power of the right operand.</li></ol><pre>// Declare two variables<br>let num1 = 10;<br>let num2 = 3;<br><br>// Addition<br>let addition = num1 + num2; // 10 + 3 = 13<br><br>// Subtraction<br>let subtraction = num1 - num2; // 10 - 3 = 7<br><br>// Multiplication<br>let multiplication = num1 * num2; // 10 * 3 = 30<br><br>// Division<br>let division = num1 / num2; // 10 / 3 = 3.333...<br><br>// Modulus<br>let modulus = num1 % num2; // 10 % 3 = 1 (remainder of 10 divided by 3)<br><br>// Exponentiation<br>let exponentiation = num1 ** num2; // 10 ** 3 = 1000 (10 raised to the power of 3)<br><br>// Output the results<br>console.log(&quot;Addition:&quot;, addition);<br>console.log(&quot;Subtraction:&quot;, subtraction);<br>console.log(&quot;Multiplication:&quot;, multiplication);<br>console.log(&quot;Division:&quot;, division);<br>console.log(&quot;Modulus:&quot;, modulus);<br>console.log(&quot;Exponentiation:&quot;, exponentiation);</pre><p>Real-world example: Calculating the total price of items in a shopping cart.</p><p><strong>Assignment Operators:</strong></p><ol><li>Assignment (=): Assigns a value to a variable.</li><li>Addition assignment (+=): Adds the value of the right operand to the value of the left operand and assigns the result to the left operand.</li><li>Subtraction assignment (-=): Subtracts the value of the right operand from the value of the left operand and assigns the result to the left operand.</li><li>Multiplication assignment (*=): Multiplies the value of the left operand by the value of the right operand and assigns the result to the left operand.</li><li>Division assignment (/=): Divides the value of the left operand by the value of the right operand and assigns the result to the left operand.</li><li>Modulus assignment (%=): Computes the remainder of dividing the value of the left operand by the value of the right operand and assigns the result to the left operand.</li><li>Exponentiation assignment (**=): Raises the value of the left operand to the power of the value of the right operand and assigns the result to the left operand.</li></ol><pre>let num = 10;<br><br>// Assignment<br>let result1 = num; // result1 = 10<br><br>// Addition assignment<br>result1 += 5; // result1 = result1 + 5 = 10 + 5 = 15<br><br>// Subtraction assignment<br>result1 -= 3; // result1 = result1 - 3 = 15 - 3 = 12<br><br>// Multiplication assignment<br>result1 *= 2; // result1 = result1 * 2 = 12 * 2 = 24<br><br>// Division assignment<br>result1 /= 4; // result1 = result1 / 4 = 24 / 4 = 6<br><br>// Modulus assignment<br>result1 %= 5; // result1 = result1 % 5 = 6 % 5 = 1<br><br>// Exponentiation assignment<br>result1 **= 3; // result1 = result1 ** 3 = 1 ** 3 = 1<br><br>console.log(&quot;Result after all assignments:&quot;, result1);</pre><p>Real-world example: Updating user scores in a gaming application.</p><p><strong>Comparison Operators:</strong></p><ol><li>Equality (==): Returns true if the operands are equal.</li><li>Strict equality (===): Returns true if the operands are equal and of the same type.</li><li>Inequality (!=): Returns true if the operands are not equal.</li><li>Strict inequality (!==): Returns true if the operands are not equal or not of the same type.</li><li>Greater than (&gt;): Returns true if the left operand is greater than the right operand.</li><li>Less than (&lt;): Returns true if the left operand is less than the right operand.</li><li>Greater than or equal to (&gt;=): Returns true if the left operand is greater than or equal to the right operand.</li><li>Less than or equal to (&lt;=): Returns true if the left operand is less than or equal to the right operand.</li></ol><pre>let x = 10;<br>let y = 5;<br><br>// Equality<br>console.log(&quot;Equality:&quot;, x == y); // false<br><br>// Strict equality<br>console.log(&quot;Strict equality:&quot;, x === &quot;10&quot;); // false (type conversion is not done)<br><br>// Inequality<br>console.log(&quot;Inequality:&quot;, x != y); // true<br><br>// Strict inequality<br>console.log(&quot;Strict inequality:&quot;, x !== &quot;10&quot;); // true (type conversion is not done)<br><br>// Greater than<br>console.log(&quot;Greater than:&quot;, x &gt; y); // true<br><br>// Less than<br>console.log(&quot;Less than:&quot;, x &lt; y); // false<br><br>// Greater than or equal to<br>console.log(&quot;Greater than or equal to:&quot;, x &gt;= y); // true<br><br>// Less than or equal to<br>console.log(&quot;Less than or equal to:&quot;, x &lt;= y); // false</pre><p>Real-world example: Validating user input in a form.</p><p><strong>Logical Operators:</strong></p><ol><li>Logical AND (&amp;&amp;): Returns true if both operands are true.</li><li>Logical OR (||): Returns true if at least one of the operands is true.</li><li>Logical NOT (!): Returns the opposite boolean value of the operand.</li></ol><pre>let isAdult = true;<br>let hasLicense = false;<br>let age = null;<br><br>// Logical AND<br>let canDrive = isAdult &amp;&amp; hasLicense; // true &amp;&amp; false = false<br><br>// Logical OR<br>let canVote = isAdult || hasLicense; // true || false = true<br><br>// Logical NOT<br>let isNotAdult = !isAdult; // !true = false<br><br>// Nullish Coalescing Operator<br>let userAge = age ?? 18; // If age is null or undefined, userAge will be assigned 18<br><br>// Conditional (Ternary) Operator<br>let canDrive1 = isAdult &amp;&amp; hasLicense ? &quot;Yes&quot; : &quot;No&quot;; // If both conditions are true, canDrive is &quot;Yes&quot;; otherwise, it&#39;s &quot;No&quot;<br><br>console.log(&quot;Can Drive:&quot;, canDrive);<br>console.log(&quot;Can Vote:&quot;, canVote);<br>console.log(&quot;Is Not Adult:&quot;, isNotAdult);<br>console.log(&quot;User Age:&quot;, userAge);<br>console.log(&quot;Can Drive:&quot;, canDrive1); //yes or no</pre><p>Real-world example: Implementing access control in an application.</p><p><strong>Conclusion:</strong></p><p>Understanding JavaScript operators is essential for any developer working with the language. Whether you’re performing basic arithmetic operations or implementing complex logical conditions, operators empower you to manipulate data effectively. By mastering these operators and their applications, you’ll enhance your ability to write efficient and concise JavaScript code.</p><p>Playground for Javascript</p><p><a href="https://playcode.io/javascript">Playcode.io</a> is an online code editor and playground that allows users to write, edit, and execute HTML, CSS, and JavaScript code.</p><p>🌟 Stay Connected! 🌟</p><p>Hey there, awesome reader! 👋 Want to stay updated with my latest insights,Follow me on social media!</p><p><a href="https://twitter.com/sadanandgadwal">🐦</a> <a href="https://www.instagram.com/sadanand_gadwal/">📸</a> <a href="https://www.facebook.com/sadanandgadwal7">📘</a> <a href="https://github.com/Sadanandgadwal">💻</a> <a href="https://sadanandgadwal.me/">🌐</a></p><p><a href="https://medium.com/u/7f0303df041e">Sadanand Gadwal</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b29e8be761f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>