<?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 Prakash Subedi on Medium]]></title>
        <description><![CDATA[Stories by Prakash Subedi on Medium]]></description>
        <link>https://medium.com/@prakashsubedi_88421?source=rss-c5a1a9a7c45------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*w526uDNRsAsvBjv8.</url>
            <title>Stories by Prakash Subedi on Medium</title>
            <link>https://medium.com/@prakashsubedi_88421?source=rss-c5a1a9a7c45------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 16:38:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prakashsubedi_88421/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[# Mastering Closures in JavaScript: A Complete Guide]]></title>
            <link>https://medium.com/@prakashsubedi_88421/mastering-closures-in-javascript-a-complete-guide-be27d4b9d59a?source=rss-c5a1a9a7c45------2</link>
            <guid isPermaLink="false">https://medium.com/p/be27d4b9d59a</guid>
            <dc:creator><![CDATA[Prakash Subedi]]></dc:creator>
            <pubDate>Thu, 30 May 2024 20:12:53 GMT</pubDate>
            <atom:updated>2024-05-30T20:12:53.947Z</atom:updated>
            <content:encoded><![CDATA[<p># Mastering Closures in JavaScript: A Complete Guide</p><p>Closures are one of the most powerful and often misunderstood features in JavaScript. Understanding closures is key to mastering JavaScript, as they form the backbone of many advanced patterns and functionalities. In this blog post, we’ll break down what closures are, how they work, and how you can use them to write more effective and efficient JavaScript code.</p><p>## What is a Closure?</p><p>A closure is a function that retains access to its lexical scope, even when that function is executed outside its lexical environment. In simpler terms, a closure allows a function to “remember” the variables from the place where it was originally defined, regardless of where it is invoked later.</p><p>## Understanding the Basics</p><p>To understand closures, let’s start with a basic example:</p><p>```javascript<br>function outerFunction() {<br> let outerVariable = ‘I am outside!’;</p><p>function innerFunction() {<br> console.log(outerVariable);<br> }</p><p>return innerFunction;<br>}</p><p>const myClosure = outerFunction();<br>myClosure(); // Logs: “I am outside!”<br>```</p><p>In this example:<br>- `outerFunction` defines a variable `outerVariable` and a function `innerFunction`.<br>- `innerFunction` has access to `outerVariable` because it is defined within the same lexical scope.<br>- `outerFunction` returns `innerFunction`, which is then assigned to the variable `myClosure`.<br>- When `myClosure` is called, it still has access to `outerVariable`, demonstrating a closure.</p><p>## Practical Uses of Closures</p><p>Closures are not just theoretical concepts; they have many practical applications in everyday JavaScript coding. Here are some common use cases:</p><p>### 1. Data Privacy</p><p>Closures can be used to create private variables that are not accessible from the outside scope.</p><p>```javascript<br>function createCounter() {<br> let count = 0;</p><p>return {<br> increment: function() {<br> count++;<br> console.log(count);<br> },<br> decrement: function() {<br> count — ;<br> console.log(count);<br> }<br> };<br>}</p><p>const counter = createCounter();<br>counter.increment(); // 1<br>counter.increment(); // 2<br>counter.decrement(); // 1<br>```</p><p>In this example, the variable `count` is private to the `createCounter` function and can only be modified by the `increment` and `decrement` methods.</p><p>### 2. Function Factories</p><p>Closures can be used to create factory functions that generate other functions with specific behaviors.</p><p>```javascript<br>function createGreeting(greeting) {<br> return function(name) {<br> console.log(`${greeting}, ${name}!`);<br> };<br>}</p><p>const sayHello = createGreeting(‘Hello’);<br>const sayHi = createGreeting(‘Hi’);</p><p>sayHello(‘Alice’); // “Hello, Alice!”<br>sayHi(‘Bob’); // “Hi, Bob!”<br>```</p><p>Here, `createGreeting` creates a personalized greeting function by capturing the `greeting` variable within its closure.</p><p>### 3. Maintaining State</p><p>Closures are ideal for maintaining state in asynchronous operations or event handlers.</p><p>```javascript<br>function setup() {<br> let count = 0;</p><p>document.getElementById(‘myButton’).addEventListener(‘click’, function() {<br> count++;<br> console.log(`Button clicked ${count} times`);<br> });<br>}</p><p>setup();<br>```</p><p>In this scenario, the `count` variable maintains its state across multiple button clicks due to the closure created by the event handler function.</p><p>## Closures in Loops</p><p>One common pitfall when working with closures in loops is unexpected behavior due to the loop’s variable scope. Consider the following example:</p><p>```javascript<br>for (var i = 1; i &lt;= 3; i++) {<br> setTimeout(function() {<br> console.log(i);<br> }, 1000);<br>}<br>// Logs: 4, 4, 4<br>```</p><p>Here, each `setTimeout` callback captures the same `i` variable, which results in all callbacks logging the final value of `i` after the loop ends. To fix this, you can create a closure for each iteration:</p><p>```javascript<br>for (var i = 1; i &lt;= 3; i++) {<br> (function(i) {<br> setTimeout(function() {<br> console.log(i);<br> }, 1000);<br> })(i);<br>}<br>// Logs: 1, 2, 3<br>```</p><p>Alternatively, using `let` (which has block scope) instead of `var` can also solve this issue:</p><p>```javascript<br>for (let i = 1; i &lt;= 3; i++) {<br> setTimeout(function() {<br> console.log(i);<br> }, 1000);<br>}<br>// Logs: 1, 2, 3<br>```</p><p>## Conclusion</p><p>Closures are a fundamental concept in JavaScript that allow for powerful and flexible code patterns. By capturing and retaining access to variables in their lexical scope, closures enable data privacy, function factories, state maintenance, and more.</p><p>Understanding and utilizing closures can greatly enhance your JavaScript programming skills. With practice, you’ll find them to be an indispensable tool in your coding toolkit, allowing you to write cleaner, more modular, and maintainable code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be27d4b9d59a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[# Understanding Promises in JavaScript: A Comprehensive Guide]]></title>
            <link>https://medium.com/@prakashsubedi_88421/understanding-promises-in-javascript-a-comprehensive-guide-3d42814415a6?source=rss-c5a1a9a7c45------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d42814415a6</guid>
            <dc:creator><![CDATA[Prakash Subedi]]></dc:creator>
            <pubDate>Thu, 30 May 2024 20:09:42 GMT</pubDate>
            <atom:updated>2024-05-30T20:09:42.414Z</atom:updated>
            <content:encoded><![CDATA[<p># Understanding Promises in JavaScript: A Comprehensive Guide</p><p>JavaScript is a versatile and powerful language, often praised for its ability to handle asynchronous operations smoothly. One of the key features enabling this is the concept of **promises**. In this blog post, we’ll delve into what promises are, how they work, and how you can leverage them to write cleaner, more manageable asynchronous code.</p><p>## What is a Promise?</p><p>A **promise** in JavaScript is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value. It allows you to associate handlers with an asynchronous action’s eventual success value or failure reason.</p><p>In essence, a promise can be in one of three states:</p><p>1. **Pending**: Initial state, neither fulfilled nor rejected.<br>2. **Fulfilled**: The operation completed successfully.<br>3. **Rejected**: The operation failed.</p><p>## Creating a Promise</p><p>To create a promise, you use the `Promise` constructor, which takes a function called the executor. The executor function has two parameters: `resolve` and `reject`. These are themselves functions that change the state of the promise.</p><p>```javascript<br>const myPromise = new Promise((resolve, reject) =&gt; {<br> let success = true;</p><p>if (success) {<br> resolve(‘The operation was successful!’);<br> } else {<br> reject(‘The operation failed.’);<br> }<br>});<br>```</p><p>In the example above, `myPromise` will be resolved with the message “The operation was successful!” if `success` is `true`. Otherwise, it will be rejected with the message “The operation failed.”</p><p>## Handling Promises</p><p>Once you have a promise, you can handle its outcome using `.then()` for a fulfilled promise and `.catch()` for a rejected promise.</p><p>```javascript<br>myPromise<br> .then((message) =&gt; {<br> console.log(message); // “The operation was successful!”<br> })<br> .catch((error) =&gt; {<br> console.error(error); // “The operation failed.”<br> });<br>```</p><p>The `.then()` method takes up to two arguments: callback functions for the fulfilled and rejected cases, respectively. The `.catch()` method is a shorthand for `.then(null, rejectionCallback)`.</p><p>## Chaining Promises</p><p>One of the powerful features of promises is chaining. You can return another promise or value from a `.then()` handler, creating a chain of asynchronous operations.</p><p>```javascript<br>myPromise<br> .then((message) =&gt; {<br> console.log(message);<br> return new Promise((resolve, reject) =&gt; {<br> resolve(‘Chaining another promise!’);<br> });<br> })<br> .then((newMessage) =&gt; {<br> console.log(newMessage); // “Chaining another promise!”<br> })<br> .catch((error) =&gt; {<br> console.error(error);<br> });<br>```</p><p>Each `.then()` returns a new promise, which can be handled by the next `.then()` in the chain. This allows for more complex asynchronous sequences to be handled in a readable, linear fashion.</p><p>## Promise.all and Promise.race</p><p>JavaScript also provides utility methods like `Promise.all` and `Promise.race` for working with multiple promises.</p><p>- **`Promise.all`**: Waits for all promises to be resolved or for any to be rejected. It returns a single promise that resolves when all of the promises in the iterable have resolved, or rejects with the reason of the first promise that rejects.</p><p>```javascript<br> const promise1 = Promise.resolve(3);<br> const promise2 = 42;<br> const promise3 = new Promise((resolve, reject) =&gt; {<br> setTimeout(resolve, 100, ‘foo’);<br> });</p><p>Promise.all([promise1, promise2, promise3]).then((values) =&gt; {<br> console.log(values); // [3, 42, “foo”]<br> });<br> ```</p><p>- **`Promise.race`**: Returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects.</p><p>```javascript<br> const promise1 = new Promise((resolve, reject) =&gt; {<br> setTimeout(resolve, 500, ‘one’);<br> });</p><p>const promise2 = new Promise((resolve, reject) =&gt; {<br> setTimeout(resolve, 100, ‘two’);<br> });</p><p>Promise.race([promise1, promise2]).then((value) =&gt; {<br> console.log(value); // “two”<br> });<br> ```</p><p>## Conclusion</p><p>Promises have revolutionized how we handle asynchronous operations in JavaScript, providing a robust and flexible way to manage complex workflows. By understanding and utilizing promises, you can write more maintainable, readable, and efficient code.</p><p>Whether you are handling a single asynchronous operation or orchestrating multiple ones, promises offer a consistent and powerful solution. Keep exploring their capabilities, and soon you’ll find them indispensable in your JavaScript toolkit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d42814415a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>