<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: RakibRahman</title>
    <description>The latest articles on DEV Community by RakibRahman (@rakibrahman).</description>
    <link>https://dev.to/rakibrahman</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F493860%2F9285aa78-7307-41c3-86e0-cfbf93900cff.png</url>
      <title>DEV Community: RakibRahman</title>
      <link>https://dev.to/rakibrahman</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/rakibrahman"/>
    <language>en</language>
    <item>
      <title>Understanding the Single Responsibility Principle in S.O.L.I.D</title>
      <dc:creator>RakibRahman</dc:creator>
      <pubDate>Sat, 29 Mar 2025 17:23:54 +0000</pubDate>
      <link>https://dev.to/rakibrahman/understanding-the-single-responsibility-principle-in-solid-57b8</link>
      <guid>https://dev.to/rakibrahman/understanding-the-single-responsibility-principle-in-solid-57b8</guid>
      <description>&lt;h1&gt;
  
  
  Table of Contents
&lt;/h1&gt;

&lt;ol&gt;
&lt;li&gt;Intro&lt;/li&gt;
&lt;li&gt;What is the S.O.L.I.D Principle?&lt;/li&gt;
&lt;li&gt;What is SRP?&lt;/li&gt;
&lt;li&gt;Real-World Analogy of SRP&lt;/li&gt;
&lt;li&gt;
Code Example

&lt;ul&gt;
&lt;li&gt;Violation of SRP&lt;/li&gt;
&lt;li&gt;Adhering to SRP&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
What breaks SRP

&lt;ul&gt;
&lt;li&gt;1. Not adhering to DRY principle&lt;/li&gt;
&lt;li&gt;2. Missing KISS principle&lt;/li&gt;
&lt;li&gt;3. Tight Coupling&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
How to achieve SRP

&lt;ul&gt;
&lt;li&gt;1. Adhere to the DRY Principle&lt;/li&gt;
&lt;li&gt;2. Follow the KISS Principle&lt;/li&gt;
&lt;li&gt;3. Avoid Tight Coupling&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Benefits of SRP&lt;/li&gt;
&lt;li&gt;References&lt;/li&gt;
&lt;li&gt;Conclusion&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Intro
&lt;/h2&gt;

&lt;p&gt;Writing flexible and scalable code is hard, but the &lt;strong&gt;S.O.L.I.D&lt;/strong&gt; principles help us achieve that. At first glance, &lt;strong&gt;S.O.L.I.D&lt;/strong&gt; may seem daunting, and applying it correctly takes time and practice. However, with proper theoretical knowledge and hands-on experience, mastering these principles becomes achievable.&lt;/p&gt;

&lt;p&gt;I’m writing this blog to:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Document my learning journey&lt;/strong&gt; – so I (and others) can revisit and refresh our understanding.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Improve over time&lt;/strong&gt; – As I gain more insights, I’ll update and refine my explanations.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This will be a &lt;strong&gt;5-part series&lt;/strong&gt;, where each blog dives deep into one principle. Let’s begin with the first one: &lt;strong&gt;Single Responsibility Principle (SRP)&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What is the S.O.L.I.D Principle?
&lt;/h2&gt;

&lt;p&gt;SOLID is an acronym for the &lt;strong&gt;first five object-oriented design (OOD)&lt;/strong&gt; principles, introduced by &lt;strong&gt;Robert C. Martin (Uncle Bob)&lt;/strong&gt; in the early 2000s. These principles help developers create software that is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Maintainable&lt;/strong&gt; -&amp;gt; Easy to modify and extend.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Understandable&lt;/strong&gt; –&amp;gt; Clear and readable structure.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Flexible&lt;/strong&gt; –&amp;gt; Adapts to changes without breaking.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Scalable&lt;/strong&gt; –&amp;gt; Reduces complexity as the application grows.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The five principles are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;S&lt;/strong&gt;ingle Responsibility&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;O&lt;/strong&gt;pen/Closed&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;L&lt;/strong&gt;iskov Substitution&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;I&lt;/strong&gt;nterface Segregation&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;D&lt;/strong&gt;ependency Inversion&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  What is SRP?
&lt;/h2&gt;

&lt;p&gt;The &lt;strong&gt;Single Responsibility Principle (SRP)&lt;/strong&gt; states that:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;A class or module should have only one reason to change, meaning it should have only one job or responsibility.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;In simpler terms:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;One class = One primary job or responsibility.&lt;/li&gt;
&lt;li&gt;If a class does too much, it becomes harder to maintain.&lt;/li&gt;
&lt;li&gt;Changes in one functionality shouldn’t risk breaking unrelated features.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Violating &lt;strong&gt;SRP&lt;/strong&gt; often leads to tight coupling, which makes code hard to test and maintain.&lt;/p&gt;

&lt;h2&gt;
  
  
  Real-World Analogy of SRP
&lt;/h2&gt;

&lt;p&gt;Let’s try to understand SRP with a real-world scenario. Think of a supershop where: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The cashier only deals with cash (doesn’t help customers find products).&lt;/li&gt;
&lt;li&gt;The salesman only helps customers locate desired products (doesn’t manage cash).&lt;/li&gt;
&lt;li&gt;The cleaner only cleans (doesn’t assist with product searches or cash handling).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The supershop works efficiently because each expert focuses on their responsiblity. Changes to one role do not disrupt others.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Code Should Work the Same Way!&lt;/strong&gt; &lt;br&gt;
Just as you wouldn't expect a cleaner to handle billing, a class or module shouldn't mix unrelated responsibilities.&lt;/p&gt;
&lt;h2&gt;
  
  
  Code Example
&lt;/h2&gt;

&lt;p&gt;Enough theoretical knowledge. Let's see &lt;strong&gt;SRP&lt;/strong&gt; in action. I'll use Go(Golang) to demonstrate the &lt;strong&gt;SRP&lt;/strong&gt;, but the following example should also apply to other languages.&lt;/p&gt;
&lt;h3&gt;
  
  
  Violation of SRP
&lt;/h3&gt;

&lt;p&gt;Let’s look at a common scenario where SRP is violated. In this example, the &lt;code&gt;User&lt;/code&gt; struct handles both saving data to the database and sending emails.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type User struct {
    name  string
    email string
}

// Violation of SRP. It handles both database operations and email sending.
func (u *User) Save() error {
    // Logic to save user to the database
    fmt.Printf("Saving user %s to database\n", u.name)

    // Logic to send email
    u.SendEmail(u.email, "Welcome to our community")
    return nil
}

func (u *User) SendEmail(email, message string) {
    // Email sending logic
    fmt.Println(message, email)
}

func main() {
    user := User{name: "Rakib", email: "rakib@gmail.com"}
    user.Save()
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;Save&lt;/code&gt; method handles both database and email operations, which violates &lt;strong&gt;SRP&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Additionally, we can’t reuse database/email-related logic because it’s tightly coupled to the &lt;code&gt;Save&lt;/code&gt; method.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Adhering to SRP
&lt;/h3&gt;

&lt;p&gt;Now, let’s refactor the code to adhere to &lt;strong&gt;SRP&lt;/strong&gt;. We’ll separate the responsibilities into dedicated methods.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type User struct {
    name  string
    email string
}

// DatabaseService handles database operations - single responsibility
type DatabaseService struct{}

func (db *DatabaseService) SaveUser(user *User) {
    // Logic to save user to the database
    fmt.Println("Saving user to database", user.name)
}

// EmailService handles email-related operations - single responsibility
type EmailService struct{}

func (es *EmailService) SendEmail(user *User, message string) {
    // Logic to send an email
    fmt.Println(message, user.email)
}

func main() {
    user := User{name: "Rakib", email: "rakib@gmail.com"}

    dbService := &amp;amp;DatabaseService{}
    emailService := &amp;amp;EmailService{}

    dbService.SaveUser(&amp;amp;user)
    emailService.SendEmail(&amp;amp;user, "Welcome to our community")
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Now, we’ve assigned each responsibility to a separate module:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;DatabaseService&lt;/code&gt; handles database operations.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;EmailService&lt;/code&gt; handles email-related operations.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;&lt;p&gt;The &lt;code&gt;SaveUser&lt;/code&gt; and &lt;code&gt;SendEmail&lt;/code&gt; methods are not tightly coupled, can be reused, and changing one’s logic does not disrupt the other.&lt;/p&gt;&lt;/li&gt;

&lt;/ul&gt;

&lt;h2&gt;
  
  
  What breaks SRP
&lt;/h2&gt;

&lt;p&gt;Here are some common scenarios where &lt;strong&gt;SRP&lt;/strong&gt; is broken:&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Not adhering to &lt;strong&gt;DRY&lt;/strong&gt; principle.
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Duplicate functionality in your code violates &lt;strong&gt;SRP&lt;/strong&gt;. If you copy-paste the same logic into multiple places, it often indicates scattered responsibilities and a lack of a single source of truth.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   // Duplicate validation logic in two places  
func CreateUser(name string, email string) error {
    if len(name) == 0 {
        return errors.New("name cannot be empty")
    }
    // ... rest of the function  
}

func UpdateUser(name string, email string) error {
    if len(name) == 0 {
        return errors.New("name cannot be empty")
    }
    // ... rest of the function  
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;In the above example, the &lt;code&gt;CreateUser&lt;/code&gt; and &lt;code&gt;UpdateUser&lt;/code&gt; methods use the same logic for validating the name. If we need to update the logic, we have to do it manually in each method.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  2. Missing &lt;strong&gt;KISS&lt;/strong&gt; principle.
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;When a class tries to do too much, it becomes overly complex and difficult to understand. The level of abstraction is missing.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  type Report struct {}

func (r *Report) Generate() string { /* ... */ }
func (r *Report) SaveToFile() error { /* ... */ }
func (r *Report) SendEmail() error { /* ... */ }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Here, the &lt;code&gt;Report&lt;/code&gt; struct handles generating reports, saving them to files, and sending emails—all in one place.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  3. Tight Coupling
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;When a class is tightly coupled with other classes or modules, it becomes harder to modify one without affecting others. This coupling often arises when a class takes on responsibilities that don't belong to it.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type Order struct {
    DB *sql.DB
}

func (o *Order) Process() error {
    // Business logic + direct database access  
    _, err := o.DB.Exec("INSERT INTO orders...")
    return err
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;Order&lt;/code&gt; struct is directly responsible for both business logic and database operations, making it tightly coupled with the database.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  How to achieve SRP
&lt;/h2&gt;

&lt;p&gt;To adhere to the &lt;strong&gt;Single Responsibility Principle&lt;/strong&gt;, address the issues outlined above with these strategies:&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Adhere to the DRY Principle
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Centralize shared functionality into a single module or function. For example, extract the validation logic into a dedicated function to avoid duplication.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func ValidateName(name string) error {
    if len(name) == 0 {
        return errors.New("name cannot be empty")
    }
    return nil
}

func CreateUser(name string, email string) error {
    if err := ValidateName(name); err != nil {
        return err
    }
    // ... rest of the function  
}

func UpdateUser(name string, email string) error {
    if err := ValidateName(name); err != nil {
        return err
    }
    // ... rest of the function  
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  2. Follow the KISS Principle
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Keep classes simple and focused. Each class should have &lt;strong&gt;one clear responsibility&lt;/strong&gt;. Split the &lt;code&gt;Report&lt;/code&gt; struct into smaller, focused structs.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type ReportGenerator struct{}

func (r *ReportGenerator) Generate() string {
    // Logic for generating report
    return "Generated Report"
}

type FileSaver struct{}

func (f *FileSaver) SaveToFile(content string) error {
    // Logic for saving to file
    return nil
}

type EmailSender struct{}

func (e *EmailSender) SendEmail(content string) error {
    // Logic for sending email
    return nil
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Each struct now has a single responsibility: generating reports, saving files, or sending emails. &lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  3. Avoid Tight Coupling
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Use composition to delegate responsibilities to other classes. For instance, separate the business logic from database operations by injecting a repository or service.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  type OrderRepository struct {
    DB *sql.DB
}

func (r *OrderRepository) Save(orderData map[string]interface{}) error {
    // Database-specific logic
    _, err := r.DB.Exec("INSERT INTO orders...", orderData)
    return err
}

type Order struct {
    Repository *OrderRepository
}

func (o *Order) Process(orderData map[string]interface{}) error {
    // Business logic only
    return o.Repository.Save(orderData)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Here, the &lt;code&gt;Order&lt;/code&gt; struct delegates database operations to the &lt;code&gt;OrderRepository&lt;/code&gt;, reducing coupling and adhering to SRP.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Benefits of SRP
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Reusability&lt;/strong&gt; -&amp;gt; The &lt;code&gt;DatabaseService&lt;/code&gt; and &lt;code&gt;EmailService&lt;/code&gt; can be reused across different parts of the application, reducing duplication.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Easier debugging&lt;/strong&gt; -&amp;gt; Responsibilities are isolated, so it’s easier to pinpoint issues.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Simpler testing&lt;/strong&gt; -&amp;gt; Each class or module has a clear purpose and can be tested independently. It allows for &lt;strong&gt;unit testing&lt;/strong&gt; without mocking unrelated logic.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Better organization&lt;/strong&gt; -&amp;gt; The code is modular, providing greater readability.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Maintainability&lt;/strong&gt; -&amp;gt; Changing one module does not cause unintended side effects in other modules. For example, if the email-sending logic changes (e.g., switching from SMTP to an external service), only the &lt;code&gt;EmailService&lt;/code&gt; needs modification, leaving the &lt;code&gt;DatabaseService&lt;/code&gt; unaffected.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Abstraction&lt;/strong&gt; -&amp;gt; &lt;strong&gt;SRP&lt;/strong&gt; often leads to better abstraction, which is a key concept in good software design.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  References
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.digitalocean.com/community/conceptual-articles/s-o-l-i-d-the-first-five-principles-of-object-oriented-design" rel="noopener noreferrer"&gt;SOLID Principles&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.geeksforgeeks.org/dont-repeat-yourselfdry-in-software-development/" rel="noopener noreferrer"&gt;DRY Principle&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.geeksforgeeks.org/kiss-principle-in-software-development/" rel="noopener noreferrer"&gt;KISS Principle&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://stackify.com/oop-concepts-composition/" rel="noopener noreferrer"&gt;Composition&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.digitalocean.com/community/tutorials/what-is-abstraction-in-oops" rel="noopener noreferrer"&gt;Abstraction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/RakibRahman/Go/tree/main/OOP/S-O-L-I-D/single-responsibility-principle" rel="noopener noreferrer"&gt;Code Example Repo&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Simply put, implementing &lt;strong&gt;SRP&lt;/strong&gt; greatly improves code quality. It makes the code easier to maintain, test, and scale. Always try to implement &lt;strong&gt;SRP&lt;/strong&gt; in your projects to improve code quality. Stay tuned for the next blog in the series, which will cover the &lt;strong&gt;Open/Closed Principle (OCP)&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;That’s all for today! Thank you for reading, and don’t forget to connect with me on &lt;a href="https://www.linkedin.com/in/md-rakibur-rahman-talukder-04666519a/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt; to get updates.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;If you have any questions or feedback, please leave a comment below!&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>programming</category>
      <category>softwaredevelopment</category>
      <category>go</category>
      <category>beginners</category>
    </item>
    <item>
      <title>web worker</title>
      <dc:creator>RakibRahman</dc:creator>
      <pubDate>Wed, 19 Feb 2025 01:34:38 +0000</pubDate>
      <link>https://dev.to/rakibrahman/web-worker-14no</link>
      <guid>https://dev.to/rakibrahman/web-worker-14no</guid>
      <description></description>
    </item>
    <item>
      <title>Simplifying React with EventEmitter: Reduce Prop Drilling &amp; Unnecessary Re-renders</title>
      <dc:creator>RakibRahman</dc:creator>
      <pubDate>Fri, 14 Feb 2025 18:13:17 +0000</pubDate>
      <link>https://dev.to/rakibrahman/simplifying-react-with-eventemitter-reduce-prop-drilling-unnecessary-re-renders-3mnk</link>
      <guid>https://dev.to/rakibrahman/simplifying-react-with-eventemitter-reduce-prop-drilling-unnecessary-re-renders-3mnk</guid>
      <description>&lt;h2&gt;
  
  
  Intro
&lt;/h2&gt;

&lt;p&gt;In React applications, state management tools like Redux, Zustand, or React Context help manage shared data across components. However, when it comes to event-driven communication, &lt;strong&gt;EventEmitter&lt;/strong&gt; can be a lightweight and efficient alternative. It enables components to interact without deep prop drilling or unnecessary re-renders. In this blog, we'll explore how EventEmitter works, how to implement it in React, and when it’s the right tool for the job.&lt;/p&gt;

&lt;h2&gt;
  
  
  What's an Event Emitter?
&lt;/h2&gt;

&lt;p&gt;In browsers, we handle user interactions using &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Event" rel="noopener noreferrer"&gt;events&lt;/a&gt;. An event can be triggered by a user's action, such as a mouse click or a keyboard key press. For example, when we copy and paste text or media files into our app, it’s handled by the &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/ClipboardEvent" rel="noopener noreferrer"&gt;ClipboardEvent&lt;/a&gt; to achieve the desired outcome. Different frameworks and libraries provide various implementations of this concept. In Node.js, the &lt;a href="https://nodejs.org/en/learn/asynchronous-work/the-nodejs-event-emitter" rel="noopener noreferrer"&gt;EventEmitter&lt;/a&gt; class offers a simple and flexible way to handle events. Simply put, it emits (or triggers) an event that anyone can listen to and perform tasks based on the emitted data.&lt;/p&gt;

&lt;h2&gt;
  
  
  Basic Example of EventEmitter in JavaScript
&lt;/h2&gt;

&lt;p&gt;Here’s a basic implementation of &lt;code&gt;EventEmitter&lt;/code&gt; in JavaScript using Node.js' built-in &lt;code&gt;EventEmitter&lt;/code&gt; class.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc744nfg32w2i887ns6zl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc744nfg32w2i887ns6zl.png" alt="event emitter node js" width="800" height="394"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;emit&lt;/code&gt; &lt;strong&gt;method&lt;/strong&gt;  is used to trigger an event. In this example, it triggers the &lt;code&gt;login&lt;/code&gt; event and passes the phone number ('01829546') as data.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;on&lt;/code&gt; &lt;strong&gt;method&lt;/strong&gt;  is used to listen for an event and execute a callback function when the event is triggered. Here, it invokes the &lt;code&gt;sendOTP&lt;/code&gt; function with the provided phone number.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Implementing EventEmitter in React
&lt;/h2&gt;

&lt;p&gt;React doesn’t have a built-in &lt;code&gt;EventEmitter&lt;/code&gt;, so we’ll use the &lt;code&gt;eventemitter3&lt;/code&gt; package from npm. This approach allows us to manage app-wide events without tightly coupling components.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 1: Setting Up EventEmitter
&lt;/h3&gt;

&lt;p&gt;Let’s create a file (&lt;code&gt;eventEmitter.ts&lt;/code&gt;) to define and export a single instance of &lt;code&gt;EventEmitter&lt;/code&gt;. This ensures that the same instance is shared across the entire application.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcnllxlog5290npecc8ct.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcnllxlog5290npecc8ct.png" alt="event emitter 3 react" width="800" height="392"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 2: Emitting an Event from Any Component
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;LoginButton&lt;/code&gt; component &lt;strong&gt;emits&lt;/strong&gt; an event named &lt;code&gt;login&lt;/code&gt; with a phone number as data.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmpt6f1991lw6vuf41ppv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmpt6f1991lw6vuf41ppv.png" alt="event emit" width="800" height="526"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 3: Subscribing to the Event from Any Component
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftrxyttnzyxvs1cg0bvvd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftrxyttnzyxvs1cg0bvvd.png" alt="event on" width="800" height="511"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;OTPHandler&lt;/code&gt; component &lt;strong&gt;listens&lt;/strong&gt; for the &lt;code&gt;login&lt;/code&gt; event and performs an action.&lt;/li&gt;
&lt;li&gt;Components can listen for events even if they are not directly related to the emitter component. This eliminates the need for deep prop drilling, as the data is available app-wide.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://github.com/RakibRahman/react-practice-arena/tree/main/src/event-emitter" rel="noopener noreferrer"&gt;Code Example Repo&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Benefits of Using EventEmitter
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Decoupling Logic:&lt;/strong&gt; The &lt;code&gt;LoginButton&lt;/code&gt; and &lt;code&gt;OTPHandler&lt;/code&gt; components are completely independent. They communicate via the shared AppEmitter instance.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Preventing Deep Prop Passing:&lt;/strong&gt; You don’t need to pass props through deeply nested components, as the event data is globally accessible.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Avoiding Re-renders:&lt;/strong&gt; Since events are handled outside of React's state management, unrelated components won’t re-render unnecessarily.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;App-Wide Notifications:&lt;/strong&gt; EventEmitter is useful for broadcasting notifications, logging, or analytics across the app.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Drawbacks of EventEmitter
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Hard to Debug:&lt;/strong&gt; Events are &lt;strong&gt;decoupled&lt;/strong&gt;, making it difficult to trace where an event was emitted or which listeners handle it, especially as the application grows.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Memory Leaks:&lt;/strong&gt; If listeners are not cleaned up (e.g., using &lt;code&gt;.off()&lt;/code&gt;), they can persist after components are unmounted, leading to memory leaks and unexpected behaviour.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;No Built-in Error Handling:&lt;/strong&gt; Errors in listeners can crash the application since &lt;code&gt;EventEmitter&lt;/code&gt; does not provide robust error-handling mechanisms.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Not for Complex State Management:&lt;/strong&gt; &lt;code&gt;EventEmitter&lt;/code&gt; is unsuitable for managing complex state or workflows. It’s designed for simple event-driven communication, not for maintaining synchronized application state&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  EventEmitter, React Context, Redux/Zustand: Which Tool Fits Your Use Case?
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;EventEmitter:&lt;/strong&gt; Best for &lt;strong&gt;event-driven workflows&lt;/strong&gt;  (e.g., logging, analytics). Avoids re-renders but requires manual cleanup and lacks built-in error handling. &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;React Context:&lt;/strong&gt; Ideal for &lt;strong&gt;shared UI state&lt;/strong&gt;  (e.g., themes, auth). Easy to use but triggers frequent re-renders, making it less efficient for high-frequency updates. &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Redux/Zustand:&lt;/strong&gt; Perfect for &lt;strong&gt;complex global state&lt;/strong&gt; (e.g., complex business logic) in large apps. Offers scalability and middleware support.&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Feature&lt;/th&gt;
&lt;th&gt;EventEmitter&lt;/th&gt;
&lt;th&gt;React Context&lt;/th&gt;
&lt;th&gt;Redux/Zustand&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Decoupling&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;High&lt;/td&gt;
&lt;td&gt;Low&lt;/td&gt;
&lt;td&gt;Medium&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Re-render Optimization&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Yes (operates outside React lifecycle)&lt;/td&gt;
&lt;td&gt;No (triggers re-renders for listeners)&lt;/td&gt;
&lt;td&gt;Depends on setup&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Use Case&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Event-driven workflows (e.g., logging, analytics, WebSocket events)&lt;/td&gt;
&lt;td&gt;Shared UI state (e.g., themes, user auth)&lt;/td&gt;
&lt;td&gt;Complex app state (e.g., large-scale apps)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Memory Management&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Requires manual cleanup (&lt;code&gt;.off()&lt;/code&gt;)&lt;/td&gt;
&lt;td&gt;Automatically managed by React&lt;/td&gt;
&lt;td&gt;Automatically managed by library&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Error Handling&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Manual (no built-in mechanisms)&lt;/td&gt;
&lt;td&gt;Manual&lt;/td&gt;
&lt;td&gt;Built-in middleware support&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Scalability&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Good for small-to-medium apps&lt;/td&gt;
&lt;td&gt;Good for medium apps&lt;/td&gt;
&lt;td&gt;Excellent for large-scale apps&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Performance Overhead&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Minimal&lt;/td&gt;
&lt;td&gt;Moderate (re-renders can be costly)&lt;/td&gt;
&lt;td&gt;Moderate to High (depends on usage)&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;EventEmitter&lt;/strong&gt; is a powerful tool for &lt;strong&gt;event-driven workflows&lt;/strong&gt;, allowing React components to communicate without deep prop drilling or excessive state management. While it helps optimize performance by preventing unnecessary re-renders, it comes with trade-offs like manual cleanup and lack of built-in error handling. When used correctly, &lt;strong&gt;EventEmitter&lt;/strong&gt; can be a lightweight and efficient alternative for handling app-wide notifications, logging, and one-time interactions. However, for managing complex application states, React Context or state management libraries like Redux and Zustand remain more suitable options.&lt;/p&gt;

&lt;p&gt;That wraps up our deep dive into EventEmitter!. Thank you for reading, and don't forget to connect on &lt;a href="https://www.linkedin.com/in/md-rakibur-rahman-talukder-04666519a/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt; or &lt;a href="https://twitter.com/RakibRahman06" rel="noopener noreferrer"&gt;X&lt;/a&gt; to get more content.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;If you have any questions or feedback, please leave a comment.&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>react</category>
      <category>webdev</category>
      <category>frontend</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Promise.all(), Promise.any(), and More: Handling Multiple Promises in JavaScript</title>
      <dc:creator>RakibRahman</dc:creator>
      <pubDate>Wed, 05 Feb 2025 04:09:56 +0000</pubDate>
      <link>https://dev.to/rakibrahman/promiseall-promiseany-and-more-handling-multiple-promises-in-javascript-32m5</link>
      <guid>https://dev.to/rakibrahman/promiseall-promiseany-and-more-handling-multiple-promises-in-javascript-32m5</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;In Asynchronous JavaScript, &lt;code&gt;Promise&lt;/code&gt; plays a vital role. If you're unfamiliar with asynchronous programming in JavaScript, you can &lt;a href="https://medium.com/@vivianyim/synchronous-vs-asynchronous-javascript-de4918e8ad62" rel="noopener noreferrer"&gt;Read about it here&lt;/a&gt;. In this article, I'll talk about &lt;code&gt;Promise&lt;/code&gt;, handling multiple promises, and, more specifically, various &lt;code&gt;Promise Methods&lt;/code&gt; and how and when to use them.&lt;/p&gt;

&lt;p&gt;Table of Contents:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;What is Promise&lt;/li&gt;
&lt;li&gt;Promise Methods&lt;/li&gt;
&lt;li&gt;Conclusion&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Promise
&lt;/h2&gt;

&lt;p&gt;Let's have an overview of &lt;code&gt;Promise&lt;/code&gt; first. In JavaScript, &lt;code&gt;Promise&lt;/code&gt; is used to perform asynchronous operations. It's an &lt;strong&gt;object&lt;/strong&gt; that contains a status &amp;amp; represents the eventual completion (or failure) of an asynchronous operation and its resulting value.&lt;/p&gt;

&lt;p&gt;For example, uploading an image to the server is an asynchronous operation. When the image upload process is done, it can return a value or throw an exception error.&lt;br&gt;
The following code is an example of using a &lt;code&gt;Promise&lt;/code&gt; based function.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F439dbrwb8axs2roorrky.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F439dbrwb8axs2roorrky.png" alt="promise" width="800" height="516"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A &lt;code&gt;Promise&lt;/code&gt; has three states:

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Pending&lt;/strong&gt;(⏳): The initial state, where the promise is neither resolved nor rejected&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Fulfilled&lt;/strong&gt;(✔): The state when the promise is successfully resolved with a value.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Rejected&lt;/strong&gt;(❌): The state when the promise fails due to an error or exception.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;h3&gt;
  
  
  Understanding &lt;code&gt;.then()&lt;/code&gt;, &lt;code&gt;.catch()&lt;/code&gt;, and &lt;code&gt;.finally()&lt;/code&gt; in Promises
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;.then(&lt;/code&gt;) method is used to handle the result of a fulfilled promise. It executes only when the promise is successfully resolved.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;.catch()&lt;/code&gt; method handles errors when a promise is rejected. It executes if the promise is rejected or if an error occurs in the preceding &lt;code&gt;.then()&lt;/code&gt; block.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Both &lt;code&gt;.then()&lt;/code&gt; and &lt;code&gt;.catch()&lt;/code&gt; always return promises, allowing us to chain promise methods unconditionally to fulfil our requirements.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;.finally()&lt;/code&gt; method is always executed, regardless of whether the promise is fulfilled or rejected. It is commonly used for cleanup tasks, such as hiding a loading spinner or logging completion.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For a more detailed explanation of &lt;code&gt;Promise&lt;/code&gt; &lt;a href="https://dev.to/lydiahallie/javascript-visualized-promises-async-await-5gke"&gt;Read this awesome article&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  How to handle multiple promises.
&lt;/h2&gt;

&lt;p&gt;When working with multiple promises, we can use the following methods to handle them as per our requirements.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Promise.all()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Promise.any()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Promise.race()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Promise.allSettled()&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;All of these methods take zero or more promises (you can say Arrays of Promises) and iterate over them to produce a single Promise. However, each method has its own characteristics.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Let's see how these methods work.&lt;/strong&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Promise.all()
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Fulfilled if all the promises are resolved.

&lt;ul&gt;
&lt;li&gt;returns an array of fulfilled values of Promises.&lt;/li&gt;
&lt;li&gt;Example Code:
&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fogce6co8ajtar400gehu.png" alt="promiseAll" width="800" height="489"&gt;
&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;Rejected if at least one Promise is rejected.

&lt;ul&gt;
&lt;li&gt;returns the value of the rejected Promise&lt;/li&gt;
&lt;li&gt;Example Code:
&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fid375zpkcmp9ed5li5yz.png" alt="promiseAll" width="800" height="489"&gt;
&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;Diagram:
&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2hq2idrg6jf1va5fgcgm.png" alt="promise all diagram" width="800" height="635"&gt;
&lt;/li&gt;

&lt;li&gt;

&lt;strong&gt;Use case&lt;/strong&gt;: When you need all promises to succeed before proceeding (e.g., fetching multiple resources).&lt;/li&gt;

&lt;/ul&gt;

&lt;h3&gt;
  
  
  Promise.allSettled()
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Fulfills when all promises settle. Does not stop even if there are failed promises.

&lt;ul&gt;
&lt;li&gt;returns returns each fulfilled promise as an object.&lt;/li&gt;
&lt;li&gt;if the promise is resolved, it will return the promise value with status.
&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  {
    status: 'fulfilled',
    value:'result'
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;if the promise is rejected, it will return the promise rejection reason with status.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  {
    status: 'rejected',
    reason: 'Something went wrong'
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Example code:
&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fu7cfcjd40hj8ar5m2706.png" alt="all settled" width="800" height="548"&gt;
&lt;/li&gt;
&lt;li&gt;Diagram:
&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvzdhysudb29raadx047f.png" alt="diagram all settled" width="800" height="511"&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Use case&lt;/strong&gt;: When you want to handle both successes and failures without stopping the process (e.g., uploading multiple files).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Promise.any()
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Fulfills when the first promise is resolved.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;returns the value of the first fulfilled promise.&lt;/li&gt;
&lt;li&gt;Example Code:
&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffi82b60f6dwumgi4acdo.png" alt="promiseAny" width="800" height="523"&gt;
&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;p&gt;If all promises are rejected, then it will return the rejected Promise with an instance of &lt;code&gt;AggregateError&lt;/code&gt; which contains all rejection values.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Example Code:
&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhxrm4y497mykq7zq4pyb.png" alt="promise any diagram" width="800" height="416"&gt;
&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;&lt;p&gt;Diagram:&lt;br&gt;&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fewjeu02wz0nneun4lcmg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fewjeu02wz0nneun4lcmg.png" alt="promise any" width="800" height="540"&gt;&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;

&lt;li&gt;&lt;p&gt;&lt;strong&gt;Use case&lt;/strong&gt;: When you need the first successful outcome among multiple options (e.g., using redundant APIs or payment gateways, ignoring failures as only need one to succeed).&lt;/p&gt;&lt;/li&gt;

&lt;/ul&gt;

&lt;h3&gt;
  
  
  Promise.race()
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Fulfills if any of the promises are resolved or rejected. It does not matter if the settled promise is resolved or rejected, it returns the promise value of the very first settled Promise.&lt;/li&gt;
&lt;li&gt;Example Code:
&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjjazfad90zmqpvx64w9o.png" alt="promiseRace" width="800" height="489"&gt;
&lt;/li&gt;
&lt;li&gt;Diagram:
&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4fxc1cjdl5ws4krehbfc.png" alt="promiseRace description" width="800" height="503"&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Use case&lt;/strong&gt;: When you need to act on the first settled promise, regardless of success or failure (e.g., implementing timeouts).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Promises are a cornerstone of modern JavaScript, enabling efficient handling of asynchronous operations. By mastering methods like Promise.all(), Promise.allSettled(), Promise.any(), and Promise.race(), you can tackle complex workflows with ease. From fetching multiple resources to implementing timeouts, these tools empower you to build robust and scalable applications.&lt;/p&gt;

&lt;p&gt;That's all for today. Thank you for reading, and don't forget to connect on &lt;a href="https://www.linkedin.com/in/md-rakibur-rahman-talukder-04666519a/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt; or &lt;a href="https://twitter.com/RakibRahman06" rel="noopener noreferrer"&gt;X&lt;/a&gt; to get more contents.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;If you have any questions or feedback, please leave a comment.&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>frontend</category>
      <category>beginners</category>
      <category>learning</category>
    </item>
    <item>
      <title>JavaScript Essentials: Handling Null, Undefined, and Safely Accessing Data with ?? and ?.</title>
      <dc:creator>RakibRahman</dc:creator>
      <pubDate>Sat, 01 Feb 2025 05:51:52 +0000</pubDate>
      <link>https://dev.to/rakibrahman/javascript-essentials-handling-null-undefined-and-safely-accessing-data-with-and--5c6b</link>
      <guid>https://dev.to/rakibrahman/javascript-essentials-handling-null-undefined-and-safely-accessing-data-with-and--5c6b</guid>
      <description>&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;strong&gt;Table of contents&lt;/strong&gt;&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt; Introduction&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Null&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Undefined&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt; Checking for null &amp;amp; undefined value&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;The Nullish coalescing operator(??) &lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Difference between nullish coalescing operator and logical Or operator &lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Optional chaining (?.) &lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Interview questions&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;References &lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Conclusion &lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;There are two types of values in JavaScript. One is &lt;em&gt;Primitive values&lt;/em&gt;, and another is &lt;em&gt;objects&lt;/em&gt;. &lt;code&gt;null&lt;/code&gt; and &lt;code&gt;undefined&lt;/code&gt; are primitive data types and behave similarly. Both are treated as falsy values and often used interchangeably. Which sometimes leads to unexpected results due to not being able to distinguish between them. &lt;code&gt;null&lt;/code&gt; and &lt;code&gt;undefined&lt;/code&gt; are only two JS values that give us exception (TypeError) messages when trying to read property.&lt;/p&gt;

&lt;p&gt;Hopefully, this post will help you firm your knowledge of these data types and how to use &lt;code&gt;nullish coalescing operator&lt;/code&gt; &amp;amp; &lt;code&gt;optional chaining&lt;/code&gt; when dealing with &lt;code&gt;null&lt;/code&gt; and &lt;code&gt;undefined&lt;/code&gt; values.&lt;/p&gt;

&lt;h2&gt;
  
  
  Null
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;In JavaScript &lt;code&gt;null&lt;/code&gt; means &lt;strong&gt;intentional absence of value&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;null&lt;/code&gt; is a primitive datatype but treated as an object. Variables with object type are initialized with null.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;null&lt;/code&gt; will be treated as &lt;strong&gt;0&lt;/strong&gt; if any primitive operation is applied.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;null&lt;/code&gt; is treated as &lt;strong&gt;falsy&lt;/strong&gt; value for boolean operations.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;JSON&lt;/strong&gt; data format does &lt;strong&gt;not support&lt;/strong&gt; &lt;code&gt;undefined&lt;/code&gt;, only &lt;code&gt;null&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3nozwx9pl7ejrpqkmiu7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3nozwx9pl7ejrpqkmiu7.png" alt="null" width="800" height="419"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Undefined
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;In JavaScript &lt;code&gt;undefined&lt;/code&gt; means &lt;strong&gt;not initialized&lt;/strong&gt; or &lt;strong&gt;does not exist&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;undefined&lt;/code&gt; datatype indicates that variable is declared but &lt;strong&gt;it does not exist in the memory(no value assigned)&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Declared variable is always treated as undefined if &lt;strong&gt;no value&lt;/strong&gt; is assigned.&lt;/li&gt;
&lt;li&gt;If a function does &lt;strong&gt;not return&lt;/strong&gt; anything ,it will always return &lt;code&gt;undefined&lt;/code&gt; by default.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;undefined&lt;/code&gt; datatype occurs when variable is uninitialized, specific function parameter is not provided.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fswwun3b9qtbkrv56t59h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fswwun3b9qtbkrv56t59h.png" alt="undefined" width="800" height="567"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Checking for null and undefined value
&lt;/h2&gt;

&lt;p&gt;JavaScript provides different ways to check for null and undefined. Here’s an example demonstrating how to handle them safely.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcaz6lklz2d8b8xcbkcl9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcaz6lklz2d8b8xcbkcl9.png" alt="checking" width="800" height="1052"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  The Nullish coalescing operator(??)
&lt;/h2&gt;

&lt;p&gt;The nullish coalescing operator(??) was introduced in ECMAScript 2020. It returns left hand side value if the value is not either &lt;code&gt;undefined&lt;/code&gt; or &lt;code&gt;null&lt;/code&gt;.If the value is either &lt;code&gt;undefined&lt;/code&gt; or &lt;code&gt;null&lt;/code&gt; it will return the right hand side value.&lt;/p&gt;

&lt;p&gt;For example, when fetching data from the server, if the value is not either &lt;code&gt;null&lt;/code&gt; or &lt;code&gt;undefined&lt;/code&gt; we can show the received value otherwise it will show the default value as a fallback.The syntax of `nullish coalescing operator is &lt;strong&gt;??&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fb5vjflm463anb164g7nn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fb5vjflm463anb164g7nn.png" alt="nullish coalescing operator" width="800" height="510"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Difference between nullish coalescing operator and logical Or operator
&lt;/h2&gt;

&lt;p&gt;At first glance, nullish coalescing operator feels similar to the logical Or (||) operator.The main difference is that nullish coalescing operator only returns default value when left hand side value is either &lt;code&gt;undefined&lt;/code&gt; or &lt;code&gt;null&lt;/code&gt;. Logical Or (||) operator returns the default value for all other falsy values such &lt;code&gt;false&lt;/code&gt;,&lt;code&gt;0&lt;/code&gt;,&lt;code&gt;string&lt;/code&gt; etc.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbattc880eongytj4i2u0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbattc880eongytj4i2u0.png" alt="or operator" width="800" height="635"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Optional chaining (?.)
&lt;/h2&gt;

&lt;p&gt;Optional chaining (?.) operator is used to access properties and methods calls of an object. If the object value is either &lt;code&gt;null&lt;/code&gt; or &lt;code&gt;undefined&lt;/code&gt; it will return &lt;code&gt;undefined&lt;/code&gt; instead of throwing an error, otherwise it will perform the operation.&lt;/p&gt;

&lt;p&gt;Optional Chaining is useful when fetching data from the server, as it wont crash the app if any object property is &lt;code&gt;null&lt;/code&gt; or &lt;code&gt;undefined&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6cwfos6i186pgfvgzypg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6cwfos6i186pgfvgzypg.png" alt="optional chaining" width="800" height="483"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Interview questions
&lt;/h2&gt;

&lt;p&gt;Let's look at some interview questions related to &lt;code&gt;null&lt;/code&gt;,&lt;code&gt;undefined&lt;/code&gt;,&lt;code&gt;nullish coalescing operator&lt;/code&gt; and &lt;code&gt;optional chaining&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;what is the difference between null and undefined?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Ans: undefined means a variable that has no value. null means the variable was intentionally set to have no value.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt; What is the type of null?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Ans: &lt;code&gt;object&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt; What is output of following code?&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    let a = 5;
    let b;
    console.log(a+b);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;Ans: &lt;code&gt;NaN&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What does the nullish coalescing operator do?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Ans: It returns the right-hand side operand when the left hand operand is &lt;code&gt;null&lt;/code&gt; or &lt;code&gt;undefined&lt;/code&gt;. Otherwise, the left hand operand is returned. The syntax is &lt;code&gt;??&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;If a function has no return value specified, what value does it return?&lt;br&gt;
&lt;/strong&gt;&lt;br&gt;
Ans: &lt;code&gt;undefined&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is change can be made that can prevent this code from throwing an error?&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; const person = {
    name: 'Mehedi',
    age: 21,
    address: {
        city: 'Dhaka',
        }
            }
console.log(person.address.houseNumber)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;Ans: error can be avoided by using Optional chaining(?.), change &lt;code&gt;console.log(person.address.houseNumber);&lt;/code&gt; to &lt;code&gt;console.log(person.address?.houseNumber)&lt;/code&gt;;&lt;/p&gt;

&lt;h2&gt;
  
  
  References
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Glossary/Primitive" rel="noopener noreferrer"&gt;Primitive datatype&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" rel="noopener noreferrer"&gt;Object datatype&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://developer.mozilla.org/en-US/docs/Glossary/Falsy" rel="noopener noreferrer"&gt;Falsy values&lt;/a&gt; &amp;amp; &lt;a href="https://developer.mozilla.org/en-US/docs/Glossary/Truthy" rel="noopener noreferrer"&gt;Truthy values&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR" rel="noopener noreferrer"&gt;Logical OR (||) operator&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError" rel="noopener noreferrer"&gt;TypeError&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this short post, we've looked at &lt;code&gt;null&lt;/code&gt; and &lt;code&gt;undefined&lt;/code&gt; data types. We also talked about &lt;code&gt;Nullish Coalescing&lt;/code&gt; and &lt;code&gt;Optional Chaining&lt;/code&gt; operators and when and how to use them. Go through the interviews question to solidify your learning. Hopefully, you learned something new today.&lt;/p&gt;

&lt;p&gt;That's all for today. Thank you for reading, and don't forget to connect on &lt;a href="https://www.linkedin.com/in/md-rakibur-rahman-talukder-04666519a/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt; or &lt;a href="https://twitter.com/RakibRahman06" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt; to get more contents.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;If you have any questions or feedback, please leave a comment&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Memoization in JavaScript? And how to apply it to get better code performance.</title>
      <dc:creator>RakibRahman</dc:creator>
      <pubDate>Sun, 20 Feb 2022 17:01:35 +0000</pubDate>
      <link>https://dev.to/rakibrahman/memoization-in-javascript-and-how-to-apply-it-to-get-better-code-performance-5d8k</link>
      <guid>https://dev.to/rakibrahman/memoization-in-javascript-and-how-to-apply-it-to-get-better-code-performance-5d8k</guid>
      <description>&lt;p&gt;As a programmer, we always want to write code that is robust and gives us better performance. But sometimes we face performance issues due to not applying good optimization techniques. One such technique is &lt;strong&gt;Memoization&lt;/strong&gt;. Memoization offers notable performance benefits when dealing with a function that has &lt;strong&gt;repeated&lt;/strong&gt; parameters.&lt;br&gt;
In this article, I'm going to talk about Memoization, how you can implement it and when it should be used.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;strong&gt;Table of contents&lt;/strong&gt;&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt; Prerequisites&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;What is Memoization&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt; Implementing Memoization&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;How memoization works &lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Normal function vs Memoized Function &lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Use Cases &lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Libraries for Memoization&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Tradeoffs &lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;References &lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Conclusion &lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h1&gt;
  
  
  Prerequisites
&lt;/h1&gt;

&lt;p&gt;Before you begin reading, it will be great to know the followings:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;JavaScript Fundamentals&lt;/li&gt;
&lt;li&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures" rel="noopener noreferrer"&gt;Closure&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.freecodecamp.org/news/what-is-a-pure-function-in-javascript-acb887375dfe/" rel="noopener noreferrer"&gt;Pure Function&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.codecademy.com/learn/game-dev-learn-javascript-higher-order-functions-and-iterators/modules/game-dev-learn-javascript-iterators/cheatsheet" rel="noopener noreferrer"&gt;Higher-Order Function&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So let's get started!!!&lt;/p&gt;

&lt;h1&gt;
  
  
  What is memoization?
&lt;/h1&gt;

&lt;p&gt;From Wikipedia:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In computing, memoization or memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;So, Memoization is an optimization technique that can be used to &lt;strong&gt;reduce extensive&lt;/strong&gt;(time-consuming) calculations by saving previous input to something called &lt;code&gt;cache&lt;/code&gt; and returning the &lt;strong&gt;result&lt;/strong&gt; from it. When a memoized function is given the same input again, it will return the cached result without calculating from the start. Thus saving code execution time and memory.&lt;/p&gt;

&lt;p&gt;As you can guess, Memoization is not only &lt;strong&gt;limited&lt;/strong&gt; to JavaScript but is also widely supported by many other languages. It's a common concept in the programming world.&lt;/p&gt;

&lt;h1&gt;
  
  
  Implementing Memoization
&lt;/h1&gt;

&lt;p&gt;Before seeing how Memoization works, let's look at a simple example that will demonstrate how Memoization can help us to get better performance. &lt;br&gt;
 Consider the following function which returns the square of a number.&lt;/p&gt;

&lt;h4&gt;
  
  
  Normal Function
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhcsl7cj2060gpjcfh5yi.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhcsl7cj2060gpjcfh5yi.png" alt=" " width="738" height="672"&gt;&lt;/a&gt;&lt;br&gt;
In case if you are not familiar with &lt;code&gt;console.time()&lt;/code&gt; and &lt;code&gt;console.timeEnd&lt;/code&gt; , they are used to &lt;strong&gt;track&lt;/strong&gt; how long an operation takes. Read more about them on &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/console/time" rel="noopener noreferrer"&gt;MDN&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Here, I've invoked the function with the same input &lt;em&gt;four&lt;/em&gt; times. Here is its completion time:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fn0qy2pt0jafwhze2exwu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fn0qy2pt0jafwhze2exwu.png" alt="time" width="426" height="374"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Invocations&lt;/th&gt;
&lt;th&gt;Time Taken&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;First&lt;/td&gt;
&lt;td&gt;9.331ms&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Second&lt;/td&gt;
&lt;td&gt;2.336ms&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Third&lt;/td&gt;
&lt;td&gt;1.397ms&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Fourth&lt;/td&gt;
&lt;td&gt;0.137ms&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Later we'll compare this result against the memoized result.&lt;/p&gt;

&lt;h4&gt;
  
  
  Memoized Function
&lt;/h4&gt;

&lt;p&gt;Now we are going to implement Memoization in the &lt;code&gt;getSquare&lt;/code&gt; function. Remember that to memoize a function, it should be &lt;strong&gt;pure&lt;/strong&gt; so that return values are the same for the same inputs every time.&lt;/p&gt;

&lt;p&gt;Take a look at the following function:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe6rznf3sa6219hl933ok.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe6rznf3sa6219hl933ok.png" alt="normal function" width="620" height="541"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h6&gt;
  
  
  Demo Output:
&lt;/h6&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmlfhjrfmzix3irewm7ab.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmlfhjrfmzix3irewm7ab.png" alt="demo output" width="516" height="504"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  How Memoization works?
&lt;/h1&gt;

&lt;p&gt;The principal to making a function &lt;strong&gt;memoized function&lt;/strong&gt; is to store its last input and output. In JavaScript environment, Memoization heavily relies on &lt;strong&gt;Closure&lt;/strong&gt; and &lt;strong&gt;Higher-Order Functions&lt;/strong&gt;.&lt;/p&gt;

&lt;h4&gt;
  
  
  Code breakdown of &lt;code&gt;memoSquare()&lt;/code&gt; function:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;In line 3 we have variable named &lt;code&gt;cache&lt;/code&gt; to store previous inputs.&lt;/li&gt;
&lt;li&gt;In Line 5 we return the whole &lt;strong&gt;memoized&lt;/strong&gt; function.&lt;/li&gt;
&lt;li&gt;In Line 7 we check if the input is in the &lt;code&gt;cache&lt;/code&gt;. If so, we return the cached value.&lt;code&gt;cache&lt;/code&gt; can remember the values because of the &lt;strong&gt;closure&lt;/strong&gt; it's implemented in. And this only works because the function we're working with is a &lt;strong&gt;pure&lt;/strong&gt; function.&lt;/li&gt;
&lt;li&gt;If we check the output of cache in line 9 of &lt;strong&gt;Output&lt;/strong&gt;, we'll see that &lt;code&gt;cache&lt;/code&gt; object is containing all the inputs only once.For example, We have inputted value 4 multiple times but it only storing it &lt;strong&gt;once&lt;/strong&gt;. If the current inputted value is in the cache then it simply returns value. Check the Demo output
screenshot.&lt;/li&gt;
&lt;li&gt;From line 13 we write our function logic. In here it runs a &lt;code&gt;for&lt;/code&gt; loop and simply returns a square of a number.&lt;/li&gt;
&lt;li&gt;In line 15 we cache/store our new input value to the &lt;code&gt;cache&lt;/code&gt; object.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now lets checkout the &lt;strong&gt;completion&lt;/strong&gt; time of &lt;code&gt;memoSquare()&lt;/code&gt; function.&lt;/p&gt;

&lt;h4&gt;
  
  
  Invoking the function multiple times with same value:
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjfhzrt44jwxwmd23551z.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjfhzrt44jwxwmd23551z.png" alt="result" width="516" height="560"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Result:
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwpj1j3c8w4cpqxvpffnb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwpj1j3c8w4cpqxvpffnb.png" alt="memo function" width="426" height="374"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Invocations&lt;/th&gt;
&lt;th&gt;Time Taken&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;First&lt;/td&gt;
&lt;td&gt;7.741ms&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Second&lt;/td&gt;
&lt;td&gt;0.056ms&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Third&lt;/td&gt;
&lt;td&gt;0.52ms&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Fourth&lt;/td&gt;
&lt;td&gt;0.045ms&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;




&lt;h3&gt;
  
  
  Normal function vs Memoized Function:
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fauha86vmbablmod1djls.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fauha86vmbablmod1djls.PNG" alt="normal vs memoized" width="580" height="263"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;From the comparison table, you can see how Memoization grants us better performance aka execution time each time it is called with the same value. It cuts down the heavy calculations for a previous value. So it's a good idea to memoize a function that does heavy computations or is expensive on &lt;strong&gt;time and memory&lt;/strong&gt;.&lt;/p&gt;

&lt;h1&gt;
  
  
  Use Cases
&lt;/h1&gt;

&lt;p&gt;You can use Memoization in the following cases:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Repeated invocations of a function.&lt;/li&gt;
&lt;li&gt;When you have a wide range of input values.&lt;/li&gt;
&lt;li&gt;You have an idea what will be the possible inputs.&lt;/li&gt;
&lt;li&gt;Functions that involves mathematically heavy operations.&lt;/li&gt;
&lt;li&gt;In recursive functions.&lt;/li&gt;
&lt;/ul&gt;




&lt;h1&gt;
  
  
  Tradeoffs
&lt;/h1&gt;

&lt;p&gt;Like any other optimization technique, There are limitations of Memoization. In some cases, improper use of Memoization can actually harm performance. Memoization works by storing old results and it has to be stored somewhere. As a consequence, memoized functions consume &lt;strong&gt;additional&lt;/strong&gt; memory. &lt;br&gt;
Memoization is appropriate for functions where there’s a high chance that the same input values will be used regularly. So Memoization may not be ideal for &lt;strong&gt;infrequently&lt;/strong&gt; called or fast executing functions.&lt;/p&gt;

&lt;h1&gt;
  
  
  Third-party libraries for Memoization
&lt;/h1&gt;

&lt;p&gt;You can use following third party libraries to implement Memoization:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://github.com/caiogondim/fast-memoize.js" rel="noopener noreferrer"&gt;fast-memoize&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/alexreardon/memoize-one" rel="noopener noreferrer"&gt;memoize-one&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://lodash.com/docs/4.17.15#memoize" rel="noopener noreferrer"&gt;Lodash_memoize&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  References:
&lt;/h1&gt;

&lt;p&gt;Followings are some resources to help you out:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Memoization" rel="noopener noreferrer"&gt;Memoization&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures" rel="noopener noreferrer"&gt;Closure&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.freecodecamp.org/news/what-is-a-pure-function-in-javascript-acb887375dfe/" rel="noopener noreferrer"&gt;Pure Function&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.codecademy.com/learn/game-dev-learn-javascript-higher-order-functions-and-iterators/modules/game-dev-learn-javascript-iterators/cheatsheet" rel="noopener noreferrer"&gt;Higher-Order Functions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/console/time" rel="noopener noreferrer"&gt;console.time()&lt;/a&gt; / &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/console/timeEnd" rel="noopener noreferrer"&gt;console.timeEnd()&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.sitepoint.com/implement-memoization-in-react-to-improve-performance/" rel="noopener noreferrer"&gt;Memoization in React&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  Conclusion
&lt;/h1&gt;

&lt;p&gt;Memoization is a form of caching which gives performance improvements where a function is called many times with the same input. Applying Memoization will help you to write performant and robust code. But you have to be careful about not implementing it in an irrelevant scenario.&lt;/p&gt;

&lt;p&gt;That's all for today. Thank you for reading, and don't forget to connect on &lt;a href="https://www.linkedin.com/in/md-rakibur-rahman-talukder-04666519a/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt; or &lt;a href="https://twitter.com/RakibRahman06" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;If you have any questions or thoughts, please leave a comment!?&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>performance</category>
      <category>beginners</category>
      <category>webdev</category>
    </item>
    <item>
      <title>JavaScript Array Methods Cheat Sheet with brief explanation.</title>
      <dc:creator>RakibRahman</dc:creator>
      <pubDate>Sun, 14 Mar 2021 16:40:32 +0000</pubDate>
      <link>https://dev.to/rakibrahman/javascript-array-methods-cheat-sheet-with-brief-explanation-2km1</link>
      <guid>https://dev.to/rakibrahman/javascript-array-methods-cheat-sheet-with-brief-explanation-2km1</guid>
      <description>&lt;p&gt;Today I'll share some important array methods cheat sheet along with short summary which will tell you main usage of the particular method.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Lets Start!&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  ⚡ &lt;code&gt;concat()&lt;/code&gt;,&lt;code&gt;copyWithin()&lt;/code&gt;,&lt;code&gt;every()&lt;/code&gt;,&lt;code&gt;fill()&lt;/code&gt; Methods
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fn8ppau182b6hpsh5q643.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fn8ppau182b6hpsh5q643.png" alt="Alt Text" width="800" height="793"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h3&gt;
  
  
  ⚡ &lt;code&gt;filter()&lt;/code&gt;,&lt;code&gt;find()&lt;/code&gt;,&lt;code&gt;findIndex()&lt;/code&gt;,&lt;code&gt;forEach()&lt;/code&gt; Methods
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpj8ie0803jd5j0tenc5r.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpj8ie0803jd5j0tenc5r.png" alt="Alt Text" width="800" height="951"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h3&gt;
  
  
  ⚡ &lt;code&gt;reduce()&lt;/code&gt;,&lt;code&gt;join()&lt;/code&gt;,&lt;code&gt;includes()&lt;/code&gt;,&lt;code&gt;some()&lt;/code&gt; Methods
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl156274cynz942jsj7le.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl156274cynz942jsj7le.png" alt="Alt Text" width="800" height="697"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h3&gt;
  
  
  ⚡ &lt;code&gt;reverse()&lt;/code&gt;,&lt;code&gt;push()&lt;/code&gt;,&lt;code&gt;pop()&lt;/code&gt;,&lt;code&gt;unshfit()&lt;/code&gt;,&lt;code&gt;shift()&lt;/code&gt; Methods
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgpedazomy07ek5raofl6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgpedazomy07ek5raofl6.png" alt="Alt Text" width="800" height="729"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h3&gt;
  
  
  ⚡ &lt;code&gt;slice()&lt;/code&gt;,&lt;code&gt;splice()&lt;/code&gt;,&lt;code&gt;sort()&lt;/code&gt;,&lt;code&gt;flat()&lt;/code&gt; Methods
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fv7o2d6ry4g14m1uzsnaq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fv7o2d6ry4g14m1uzsnaq.png" alt="Alt Text" width="800" height="688"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;&lt;a href="https://github.com/RakibRahman/JavaScript/blob/master/array-methods.js" rel="noopener noreferrer"&gt;Get the source code&lt;/a&gt; || &lt;a href="https://drive.google.com/file/d/1WJ9sKUm-MGxBetbJGqq-hfW_xfRu9Hpi/view?usp=sharing" rel="noopener noreferrer"&gt;Download The CheatSheet&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Thanks for reading this article.Stay tuned and keep coding!&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
    <item>
      <title>The Set() Object in JavaScript - A Nimble Introduction</title>
      <dc:creator>RakibRahman</dc:creator>
      <pubDate>Mon, 01 Mar 2021 20:42:20 +0000</pubDate>
      <link>https://dev.to/rakibrahman/the-set-object-in-javascript-a-nimble-introduction-1dm1</link>
      <guid>https://dev.to/rakibrahman/the-set-object-in-javascript-a-nimble-introduction-1dm1</guid>
      <description>&lt;p&gt;Hello, I am going to give you a quick introduction about JavaScript &lt;strong&gt;Set()&lt;/strong&gt; object and its &lt;strong&gt;must know&lt;/strong&gt; properties and methods.&lt;/p&gt;

&lt;h1&gt;
  
  
  The Set() Object
&lt;/h1&gt;

&lt;p&gt;The &lt;code&gt;Set&lt;/code&gt; object is a collection of elements. It can store primitive values or object references.Set can only contains &lt;strong&gt;distinctive&lt;/strong&gt; elements,so With &lt;code&gt;Set&lt;/code&gt; object you can remove duplicate elements.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Using the Set object&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Setting up an empty &lt;code&gt;Set&lt;/code&gt; object
&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg2hh64zi5mah7y4dp3ls.png" alt="empty set" width="776" height="436"&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Set&lt;/code&gt; object With array
&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxefo3pwg7x49od8c20wl.png" alt="set with array" width="800" height="488"&gt;
&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;strong&gt;Iterating Sets&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You can iterate over items in &lt;code&gt;Set&lt;/code&gt; object using &lt;code&gt;for...of&lt;/code&gt; statement.
&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fu0m3ddaufvbl3vsk8pui.png" alt="Iterating Sets" width="800" height="613"&gt;
&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;strong&gt;Adding an element to a set&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You can add an element to the end of a &lt;code&gt;Set&lt;/code&gt; object via the &lt;code&gt;add()&lt;/code&gt; method.
&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ff6fqit3aeqjwswf939g8.png" alt="Alt Text" width="800" height="381"&gt;
&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;strong&gt;Number of elements in a Set&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;To see the number of (unique) elements in a &lt;code&gt;Set&lt;/code&gt; object use the &lt;code&gt;size&lt;/code&gt; property.
&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4r2nxamqgcmfbo68kyh3.png" alt="size" width="776" height="388"&gt;
&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;strong&gt;Checking an element in the set&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;has&lt;/code&gt; method will tell you whether a value exists in a &lt;code&gt;Set&lt;/code&gt; object.
&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4iyqgkfdh8u5jf1ncz7j.png" alt="has" width="800" height="333"&gt;
&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;strong&gt;Delete elements from set&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Using &lt;code&gt;delete&lt;/code&gt; method you can remove a value from the &lt;code&gt;Set&lt;/code&gt; object.
&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7xvaqelwtalhzsfgu9a1.png" alt="delete" width="800" height="224"&gt;
&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;strong&gt;Remove all elements from set&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;To remove all the elements from &lt;code&gt;Set&lt;/code&gt; object simply use &lt;code&gt;clear&lt;/code&gt; method.
&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fufpfrj8m6wzsd1gozbqy.png" alt="clear" width="676" height="436"&gt;
&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;Hope you have learnt something from this article.Kindly forgive any mistake as it is my first article. &lt;strong&gt;Happy Coding!&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
      <category>webdev</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
