<?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: Subhasish Kundu</title>
    <description>The latest articles on DEV Community by Subhasish Kundu (@thecuriouscoder).</description>
    <link>https://dev.to/thecuriouscoder</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%2F642448%2Fac5c8424-9b65-4a49-ac41-30637c264c36.jpeg</url>
      <title>DEV Community: Subhasish Kundu</title>
      <link>https://dev.to/thecuriouscoder</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/thecuriouscoder"/>
    <language>en</language>
    <item>
      <title>OSS Contributions: 16th-23rd August 2021</title>
      <dc:creator>Subhasish Kundu</dc:creator>
      <pubDate>Sun, 22 Aug 2021 17:20:46 +0000</pubDate>
      <link>https://dev.to/thecuriouscoder/oss-contributions-16th-23rd-august-2021-2al6</link>
      <guid>https://dev.to/thecuriouscoder/oss-contributions-16th-23rd-august-2021-2al6</guid>
      <description>&lt;p&gt;After a long time, I started contributing to open-source software. For a long time, I had my eye on  &lt;a href="https://deno.land/"&gt;Deno&lt;/a&gt;. This week, I merged my first PR in &lt;a href="https://github.com/denoland/deno_lint"&gt;Deno Lint&lt;/a&gt;. Following is the detailed post about the issue.&lt;/p&gt;

&lt;h2&gt;
  
  
  Issue &lt;a href="https://github.com/denoland/deno_lint/issues/425"&gt;425&lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--c4JHrZA5--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1629650692526/tEeRz2p1U.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--c4JHrZA5--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1629650692526/tEeRz2p1U.jpeg" alt="deno.jpeg"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Category:&lt;/strong&gt; Refactoring&lt;/p&gt;

&lt;h3&gt;
  
  
  Description of the Issue
&lt;/h3&gt;

&lt;p&gt;If we go through the issue, we could see that in the tests of each rule, there is a repeat of messages and hints. For example, from *\ban_ts_comments.rs from a &lt;a href="https://github.com/denoland/deno_lint/blob/a15d25bb84d0067971eaf3c530548b50556e35ad/src/rules/ban_ts_comment.rs#%5BL252,L260%5D"&gt;previous commit&lt;/a&gt;, we can see that messages and hints are being repeated&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    r#"// @ts-nocheck"#: [
            {
              col: 0,
              message: DirectiveKind::Nocheck.as_message(),
              hint: DirectiveKind::Nocheck.as_hint(),
            }
          ],
    r#"/// @ts-nocheck"#: [
            {
              col: 0,
              message: DirectiveKind::Nocheck.as_message(),
              hint: DirectiveKind::Nocheck.as_hint(),
            }
          ],
    r#"//@ts-nocheck"#: [
            {
              col: 0,
              message: DirectiveKind::Nocheck.as_message(),
              hint: DirectiveKind::Nocheck.as_hint(),
            }
          ],
    r#"// @ts-nocheck    "#: [
      {
        col: 0,
        message: DirectiveKind::Nocheck.as_message(),
        hint: DirectiveKind::Nocheck.as_hint(),
      }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The test cases for each rule in Deno Lint could be grouped together based on common messages and hints. This issue talks about that. Macro &lt;a href="https://github.com/denoland/deno_lint/blob/a15d25bb84d0067971eaf3c530548b50556e35ad/src/test_util.rs#L37"&gt;assert_lint_err&lt;/a&gt; is responsible for running test cases. &lt;/p&gt;

&lt;h3&gt;
  
  
  Solution
&lt;/h3&gt;

&lt;p&gt;In this &lt;a href="https://github.com/denoland/deno_lint/commit/576f5a1fc725a49aa86ea5be0ae061ffaaed6bcf"&gt;commit&lt;/a&gt;, I have extended this macro with new rules, where we could use it to run multiple test cases with the same messages and hints. Following is the modified &lt;a href="https://github.com/denoland/deno_lint/blob/main/src/test_util.rs#%5BL65,L97%5D"&gt;assert_lint_err&lt;/a&gt; macro. I have added two new rules, where we could group tests based on messages and hints.&lt;/p&gt;

&lt;h3&gt;
  
  
  Challenges
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;I did not know about Rust. I had to learn about &lt;a href="https://doc.rust-lang.org/rust-by-example/macros.html"&gt;macro_rules!&lt;/a&gt; to solve this issue. I have gotten interested in it. Let me see, how much I make progress.&lt;/li&gt;
&lt;li&gt;As this is the first time, I was contributing to Deno, I was not aware of all the formalities. &lt;a href="https://github.com/magurotuna"&gt;Yusuke Tanaka&lt;/a&gt; from the Deno team helped me a lot. They have been very receptive and active. Their help has encouraged me to take up my &lt;a href="https://github.com/denoland/deno_lint/issues/779"&gt;new issue&lt;/a&gt; as well.&lt;/li&gt;
&lt;li&gt;This is not a challenge, but learning. I could not totally comprehend Rust-style styling. The reviewer pointed those out to me. From next time onwards, I have to be better with that.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Follow up
&lt;/h3&gt;

&lt;p&gt;In this commit, I have covered  &lt;a href="https://github.com/denoland/deno_lint/blob/main/src/rules/ban_ts_comment.rs"&gt;ban_ts_comment.rs&lt;/a&gt;  and &lt;br&gt;
  &lt;a href="https://github.com/denoland/deno_lint/blob/main/src/rules/no_await_in_loop.rs"&gt;no_await_in_loop.rs&lt;/a&gt;. I need to cover other files as well. If someone reads this post and feels good to contribute, I would encourage them to do that 😀😀. Connect with me or anyone in Deno team for help/any questions. We will be happy to help.&lt;/p&gt;

&lt;p&gt;I will write a detailed post on various aspects of Deno and Deno development and contributions in subsequent blog posts.&lt;/p&gt;

</description>
      <category>showdev</category>
      <category>programming</category>
      <category>deno</category>
    </item>
    <item>
      <title>Best Practices of Exception Handling</title>
      <dc:creator>Subhasish Kundu</dc:creator>
      <pubDate>Sat, 17 Jul 2021 06:15:24 +0000</pubDate>
      <link>https://dev.to/thecuriouscoder/best-practices-of-exception-handling-33pe</link>
      <guid>https://dev.to/thecuriouscoder/best-practices-of-exception-handling-33pe</guid>
      <description>&lt;p&gt;Exception handling is one of the most important aspects of software engineering. There are many articles on this topic. Yet, I have seen other developers and myself making mistakes and not exiting gracefully. In my experience, I have encountered many exceptional scenarios and failure reports. I have written a lot of codes and made mistakes a thousand times. The following quote by Malcolm Muggeridge summarises exception handling pretty well.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Few men of action have been able to make a graceful exit at the appropriate time.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In this article, I am documenting my share of learnings along the process.&lt;/p&gt;

&lt;p&gt;Note: I am using Java in this article as a reference. It is my primary language of coding. But, the principles are language agnostic. I will cover the things that are out of the scope of coding as well. As I learn new things about the topic, I will keep this post updated. I have used &lt;em&gt;unchecked&lt;/em&gt; and &lt;em&gt;runtime exceptions&lt;/em&gt; interchangeably.&lt;/p&gt;

&lt;p&gt;I am dividing this article into two sections&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; Handling exceptions inside code&lt;/li&gt;
&lt;li&gt;Handling exceptions outside code&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Handling exceptions inside code
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. Use Exceptions for Exceptional Scenarios
&lt;/h3&gt;

&lt;p&gt;Exceptions should be used for exceptional scenarios only. In  &lt;a href="https://www.oreilly.com/library/view/effective-java/9780134686097/"&gt;Effective Java&lt;/a&gt;, author  &lt;a href="https://en.wikipedia.org/wiki/Joshua_Bloch"&gt;Joshua Bloch&lt;/a&gt; is extremely vocal about this. If he is so vocal about this, it is an issue. I hope none of us do this anymore. Following is an example from the book&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Horrible abuse of exceptions. Don't ever do this!
try {
    int i = 0;
    while(true)
        range[i++].climb();
} catch (ArrayIndexOutOfBoundsException e) {
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Try to guess the answer! The above code is clever but lacks readability, intent, and performance. JVM does not apply some optimization as well seeing try-catch.&lt;/p&gt;

&lt;p&gt;The simpler version is readable, understandable, and lets JVM apply optimizations.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for (Mountain m : range)
    m.climb();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2. Never Ignore Exceptions in Code
&lt;/h3&gt;

&lt;p&gt;It is obvious but often forgotten. I have seen a similar code as follows.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try {
     executeCommand();
} catch (IllegalStateException e) {
    //Highly suspicious. Anything can happen here
    //without your knowledge.
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is not a good practice at all. In the future, if something happens, you will never know. I am also a criminal of ignoring an exception altogether (by mistake) 😔. Later I fixed it while refactoring. I still don't know about the impact 🥶. And it still bugs me!&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Make Exceptions Visible When Occurs
&lt;/h3&gt;

&lt;p&gt;Make sure you have ways to know that exception has occurred. It might be some metrics or UI-based log aggregator for capturing all logs. But it is a necessity. Otherwise, you will not know if there is anything wrong with the system.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. Don't Use "Log and Then Throw" Exception Strategy
&lt;/h3&gt;

&lt;p&gt;If you log and throw another exception, the catcher of exceptions might again log details about exceptions. So, you will have redundant information for the same exception. It will pollute error logs. In turn, it will make your life uneasy while debugging.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try {
      executeCommand();
} catch (IllegalStateException e) {
      // Following log is redundant information.
      // It will pollute your error log.
      log.error("Exception at doSomething:", e); 
      throw new BadRequest("Exception has occurred.", e);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  5. Log Errors with Exception Details
&lt;/h3&gt;

&lt;p&gt;This is a common practice. Let me warn you! If you are not logging exception details, you are digging a hole for the future. It will be hard to debug an actual issue. Your on-call will keep looking for issues without knowing where to look. Having a proper stack trace will help him to decide where to look. It will help root cause the issue faster.&lt;/p&gt;

&lt;h3&gt;
  
  
  6. Use Exception Translator
&lt;/h3&gt;

&lt;p&gt;Dependencies or library calls throw exceptions. Those exceptions can be specific to the callee. Those are seldom related to the caller. But we need to handle exceptions at the caller end. It is better to map specific exceptions from the callee to exception types of the caller. Exception Translator is one of the best tools available in this case. Another way can be propagating status codes such as success or failure, of the operation. In the following example, CommandArgumentException conveys better meaning relative to the caller.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try {
      executeCommand();
} catch (IllegalStateException e) {
      throw new CommandArgumentException("Arguments 
             to command are not right.", e);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Also, I have worked on monolith software written in C (codebase size was 2.2GB). In C, we don't have a proper exception handling framework like in Java. In such cases, exception translator and framework help a lot. Following are a couple of ways&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;It simplifies the handling of exceptions by calling call-back functions. In case of some null pointer exception, you should hand over the control to the exception handler. You cannot call exit(). For debugging, you need to collect reports.&lt;/li&gt;
&lt;li&gt;If you don't capture stack trace in Exception Handler, you will not be able to debug the issue. The stack trace will help you create the test case. It will be your friend for the entire debugging.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  7. Be skeptical about Runtime Exception
&lt;/h3&gt;

&lt;p&gt;Compilers force us to try-catch checked exceptions. We often miss runtime exceptions. We should be skeptical about runtime exceptions especially while calling dependencies. In large-scale distributed systems, failure is common. We once encountered a dependency call that does not have any checked exceptions. After careful inspection, we wrapped it up inside try-catch for runtime exceptions. It allowed us to exit gracefully.&lt;/p&gt;

&lt;h3&gt;
  
  
  8. Consider catching Generic Exception
&lt;/h3&gt;

&lt;p&gt;As I work in distributed system development, I generally follow this. It helps to exit with grace. But I make sure to log this and capture such exceptions. In case of a surge of generic exceptions, we should investigate the issue. There might be some new checked exception in the callee side or there is some runtime exception. In any case, we should check the issue.&lt;/p&gt;

&lt;h3&gt;
  
  
  9. Don't catch Throwables
&lt;/h3&gt;

&lt;p&gt;Throwables are the superclass of everything including Errors. Errors are used by JVM to indicate a serious system-related problem like StackOverflowError etc. Applications are not supposed to handle these errors. When JVM throws an error, there is some problem. Go check it! 🧐&lt;/p&gt;

&lt;h3&gt;
  
  
  10. Strive for Failure Atomicity
&lt;/h3&gt;

&lt;p&gt;This one is interesting. Let me elaborate on failure atomicity. In case of a failed operation on an object, we should roll back all the changes to the previous state. The object should not have partial updates. So, we can check if an operation can fail or not. We can use a checker function for this. JDK has some good examples of this. Iterator interface in Java has a checker hasNext() method. If it fails, we generally don't call the next() method. We can use this pattern as well when needed.&lt;/p&gt;

&lt;h3&gt;
  
  
  11. Document All Exceptions
&lt;/h3&gt;

&lt;p&gt;Most of the developers dislike documentation. As we write a piece code, we leave our legacy. Your documentation ensures your successor understands your code. Secretly, we all hope - when the next developer sees our code, he says &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s---u78ATlQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1626501053543/sxoZWV83v.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s---u78ATlQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1626501053543/sxoZWV83v.jpeg" alt="itsgood.jpeg"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We should document all the exceptions including runtime exceptions. In Java, the "throws" clause forces to check checked exceptions. For covering all the bases, we should document runtime exceptions as well.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;We should document all exceptions including checked and unchecked using the JavaDoc '@throws' tag. Don't just mention Exception or Throwable. The below example does not express anything.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/**
 * JavaDoc Exception sample documentation
 *  @throws Exception in case of exceptional scenarios. 
 */
public void doSomething() throws AnException, AnotherException {
    ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;We should only include checked exceptions in the throws clause, but not unchecked exceptions. It lets developers know that an exception mentioned in JavaDoc, but missing in the throws clause is &lt;em&gt;unchecked&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;Document the condition for which exception is thrown. For the above example, it is desirable to include conditions for which each exception is thrown.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  12. Always cover Exceptions in Unit Tests
&lt;/h3&gt;

&lt;p&gt;This will give you confidence that your code works during exceptional scenarios. Check for outputs during exceptions. If it is not the same as you expected, anything can fail in production. &lt;/p&gt;

&lt;h3&gt;
  
  
  13. Add Your Counters in Unit Tests
&lt;/h3&gt;

&lt;p&gt;In case you use some counter or special logs during the exception, your unit tests for exceptions should cover those. Unit tests will fail in case someone changes counter or logs. And seldom, we have reasons to change these. If there is any reason, the developer should know why it was there in the first place. Your tests should be like documentation. It should cover all the aspects of your code including exceptional scenarios.&lt;/p&gt;

&lt;h2&gt;
  
  
  Handling exceptions outside code
&lt;/h2&gt;

&lt;p&gt;Operations are one of the big issues in large software systems. It includes a large-scale distributed system as well as a standalone desktop or mobile app. Sustenance of our service is one of the most important goals. We should have a proper mechanism for handling error scenarios. Following are my two cents on this&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Indicators and Logs Should have Meaning
&lt;/h3&gt;

&lt;p&gt;Your on-call might have to debug a production issue at midnight. The last thing he wants at that time is confusion. Good logs and indicators (specific to your use case) can help him find the root cause of the issue faster. Ambiguity and complexity are hindrances to the root cause of the issue.&lt;/p&gt;

&lt;p&gt;Now food for thought, we have two code segments.&lt;br&gt;
&lt;strong&gt;Option 1&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;String serviceA = "Something has happened in serviceA";
String serviceB = "Something has happened in serviceB";
//somewhere else
log.error(serviceA);
//somewhere else
log.error(serviceB);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Option 2&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;String errorStatement = "Something has happened in ";
String serviceA = "serviceA";
String serviceB = "serviceB";
//somewhere else
log.error(errorStatement + serviceA);
//somewhere else
log.error(errorStatement + serviceB);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Suppose, we got an exception at midnight and we are getting "Something has happened in serviceA" as exception signature. Which one do you think will help to find code faster? I think Option 1. Single copy-pasting is easier than creating strings from multiple variables. Obviously, with the signature of exception, you can fast-track your problematic point. I still find Option 1 easier for on-call.&lt;/p&gt;

&lt;p&gt;Note: Have you checked the last blank space at the end of &lt;em&gt;errorStatement&lt;/em&gt; definition? These small spaces can give you nightmares.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Don't Ignore Metrics
&lt;/h3&gt;

&lt;p&gt;Add metrics wherever you think an error might occur. And add alarms on this. This will let you know if something is wrong with your system. In the monolith that I worked on, we incorporated  &lt;a href="https://en.wikipedia.org/wiki/AddressSanitizer"&gt;AddressSantizer&lt;/a&gt; to collect data about runtime exceptions. It was worth it. It helped a lot for finding a lot of long-term issues. I can still remember the days of debugging a problematic pointer! 😫&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Plan Your Action
&lt;/h3&gt;

&lt;p&gt;Metrics and alarms without action items are meaningless. It is the same as a fire brigade team without protocol. Update the run-book with all relevant details and action items for important exceptions. Also, if required, add metrics to the dashboard.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. Keep your Counters Updated
&lt;/h3&gt;

&lt;p&gt;You don't want a false alarm in the middle of the night. If you need to update an alarm, update it without delay. Getting regular wrong alarms can make you lose your trust in your system.&lt;/p&gt;

&lt;h2&gt;
  
  
  Generic Guidelines for Handling Exception
&lt;/h2&gt;

&lt;p&gt;Here are some general guidelines for handling exceptions.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Always Be Skeptical
&lt;/h3&gt;

&lt;p&gt;Skepticism is better than optimism for handling errors and exceptions. Even if you have done everything, exceptions will occur.  If you have a proper mechanism in place, you can debug an issue faster.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Aim for Sustenance
&lt;/h3&gt;

&lt;p&gt;If you build your system for sustenance, you will be better prepared for unknowns. This is one of the signs of mature developers.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Exceptions are not Your Mistake
&lt;/h3&gt;

&lt;p&gt;Failure is seldom a single developer's mistake. From coding a solution to deploying that involves a lot of steps. Any mistake at any stage can cause failure. We should aim for reducing failures by owning the process. There might be some issues unknown to the team. The developer and reviewers might miss it. Lack of testing might have missed the bug. We should look forward to improving the process. A root-cause analysis might help in this regard.&lt;/p&gt;

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

&lt;p&gt;Exception handling is a well-known misunderstood aspect of programming. In summary, we&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; Should aim for sustenance and share knowledge across the way. It will help a lot.&lt;/li&gt;
&lt;li&gt;Do not ignore exceptions. Handle it properly. Some principles mentioned might not be applicable to you. Break those and make yours. And share it with others.&lt;/li&gt;
&lt;li&gt;Do not play blame games. It will not help anyone.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;We know how to use try-catch, but we don't know how it can affect our system. This article is my attempt to capture my thoughts on this topic. Please like the post if you enjoyed reading it. Let me know in the comments if you have any thoughts or questions.&lt;/p&gt;

&lt;p&gt;Happy Learning!! 😀&lt;/p&gt;

</description>
      <category>programming</category>
      <category>codequality</category>
      <category>codereview</category>
    </item>
    <item>
      <title>JavaScript Event Loop in Depth</title>
      <dc:creator>Subhasish Kundu</dc:creator>
      <pubDate>Mon, 28 Jun 2021 04:01:19 +0000</pubDate>
      <link>https://dev.to/thecuriouscoder/javascript-event-loop-51cc</link>
      <guid>https://dev.to/thecuriouscoder/javascript-event-loop-51cc</guid>
      <description>&lt;p&gt;Sometime back, I started learning about JavaScript and React JS internals. My goal is to understand the internals of JavaScript and frameworks. In my last article, I wrote about  &lt;a href="https://blog.thecuriouscoder.in/abstract-introduction-to-react-internals" rel="noopener noreferrer"&gt;ReactJS internals&lt;/a&gt;. To understand more about React Fiber, we need to understand some preliminary JavaScript concept implementation. In the next three posts, I will be explaining in detail the following three concepts&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;JavaScript Event Loop&lt;/li&gt;
&lt;li&gt;requestAnimationFrame and rendering cycle&lt;/li&gt;
&lt;li&gt;requestIdleCallBack&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In this article, I will attempt to document my learning about Event Loop. This topic might be particularly interesting to people who want to learn how NodeJS and Deno internals work. The next two topics are interesting to me for understanding how React works internally (for code base understanding). So, let's dive deep.&lt;/p&gt;

&lt;h2&gt;
  
  
  JavaScript Execution Environment
&lt;/h2&gt;

&lt;p&gt;JavaScript is a single-threaded language. It executes one method at a time. Following high-level components are integral to its execution environment -&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Call Stack&lt;/li&gt;
&lt;li&gt;Job Queues&lt;/li&gt;
&lt;li&gt;Rendering Step&lt;/li&gt;
&lt;li&gt;Microtasks&lt;/li&gt;
&lt;li&gt;Event Loops&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Note: I have used runtime environment and execution environment interchangeably. At some points, I have used EcmaScript references. I am finding EcmaScript standards quite interesting. So, I thought to include those as well.&lt;/p&gt;

&lt;h3&gt;
  
  
  Call Stack
&lt;/h3&gt;

&lt;p&gt;Like other languages like C, C++, etc., JavaScript uses a &lt;a href="https://262.ecma-international.org/6.0/#sec-execution-contexts" rel="noopener noreferrer"&gt;Call Stack&lt;/a&gt; to execute methods. Whenever it decides to execute a method, it wraps the method in a stack frame and pushes the frame into the Call Stack. For any eventual sub-method calls, it keeps on pushing sub-methods into the stack (&lt;em&gt;LIFO&lt;/em&gt; order). Once a method is executed, the corresponding stack frame is popped. Call Stack is an integral part of JavaScript for synchronous programming.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test1();
function test1() {
    console.log("Test 1 entry");
    test2();
    console.log("Test 1 exit");
}
function test2() {
    console.log("Test 2 entry");
    console.log("Test 2 exit")
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For the above script, the result is as same as predicted:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Test 1 entry
Test 2 entry
Test 2 exit
Test 1 exit
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But, JavaScript supports asynchronous programming. We can use setTimeout to execute something in the future like the below example. We could use the following code snippet that might trigger an alert and console.log() after 10s.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    test1();
    function test1() {
        console.log("Test 1 entry");
        setTimeout(test2, 10000);
        console.log("Test 1 exit");
    }
    function test2() {
        console.log("Test 2 entry");
        alert("Test 2 execution");
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As expected, the result is &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1624265648320%2F3nph6r_jE.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1624265648320%2F3nph6r_jE.png" alt="Screenshot 2021-06-21 at 2.23.51 PM.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Well, there was an alert as well. Following is the timeline of events&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1624266204462%2FmWCwELODd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1624266204462%2FmWCwELODd.png" alt="Screenshot 2021-06-21 at 2.30.37 PM.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We can see the "Install Timer" at the bottom left. This is where the timer was installed to be fired after 10 seconds (10847ms). &lt;/p&gt;

&lt;p&gt;It seems some thread is running in the background. Hold on! Did I not mention JavaScript is single-threaded? Let's see what could happen if JavaScript is multi-threaded. Suppose, in our hypothetical model, for the above JavaScript code execution, we are allowed to spawn a new thread for executing a single setTimeout. So, for one thousand setTimeout calls, we have a thousand threads. Each thread might attempt to change DOM as well independently. Now, if DOM is a shared resource for all the threads, multiple threads are bound to create chaos reading it at the same time. We would have spent most of our time debugging race conditions rather than building rich applications 😛. So, yes, JavaScript is single-threaded and it has served JavaScript and us well.&lt;/p&gt;

&lt;p&gt;How come JavaScript schedule setTimeout callback after 10s then if there is no thread? The answer is Job or Task Queue. I am using both names interchangeably.&lt;/p&gt;

&lt;h3&gt;
  
  
  Job Queue
&lt;/h3&gt;

&lt;p&gt;With Es6, the concept of  &lt;a href="https://262.ecma-international.org/6.0/#sec-jobs-and-job-queues" rel="noopener noreferrer"&gt;Job Queue&lt;/a&gt; has been introduced. All the asynchronous tasks such as Mouse click, setTimeouts, etc., are pushed into the Job Queue for execution. JavaScript engine picks up tasks one by one and executes them using Call Stack (&lt;em&gt;FIFO&lt;/em&gt; order).&lt;/p&gt;

&lt;h3&gt;
  
  
  What part of the JavaScript engine picks up tasks from Task Queue?
&lt;/h3&gt;

&lt;p&gt;The Event Loop. It runs in a loop throughout the life cycle of the app. It picks up tasks from the Task Queue and executes them with the help of Call Stack.&lt;/p&gt;

&lt;p&gt;Note: My guess is the browser might maintain different queues for different kinds of event handling such as button clicks, mouse clicks, setTimeout calls, etc. Each browser can have different prioritization for each queue. It is just my guess. I am looking for ways to confirm that. I might write about that in the future.&lt;/p&gt;

&lt;h4&gt;
  
  
  What does the Event Loop do when there is nothing in Call Stack and Task Queue?
&lt;/h4&gt;

&lt;p&gt;You guessed it right - it runs in a loop.&lt;/p&gt;

&lt;h3&gt;
  
  
  How does the Event Loop know if it needs to execute something from Task Queue?
&lt;/h3&gt;

&lt;p&gt;The Browser engine can enqueue a task in the relevant queue. The Event Loop, in the next rotation, can dequeue the task and execute it.&lt;/p&gt;



&lt;h3&gt;
  
  
  What happens if we encounter an infinite loop?
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    &amp;lt;body&amp;gt;
        &amp;lt;button id="demo"&amp;gt;Trigger Alert&amp;lt;/button&amp;gt;
    &amp;lt;/body&amp;gt;
    &amp;lt;script&amp;gt;
        document.getElementById("demo").addEventListener("click", () =&amp;gt; {
            console.log("Clicked");
            while(true);
            console.log("After loop is executed");
        });
    &amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, the button click will enqueue the above synchronous script in Task Queue. In the next rotation, the Event Loop starts executing the task. Now, our script is stuck with &lt;em&gt;infinite while loop&lt;/em&gt;. As a result, the Event Loop is stuck in the same position because of our infinite loop.&lt;/p&gt;

&lt;h3&gt;
  
  
  Rendering Step
&lt;/h3&gt;

&lt;p&gt;Let's look into another aspect of the JavaScript runtime environment - the Rendering Step. Let's take the following example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;body&amp;gt;
        &amp;lt;p id="test_paragraph"&amp;gt; Test JS Hello&amp;lt;/p&amp;gt;

        &amp;lt;button onclick="changeParagraphColor()"&amp;gt;Trigger Alert&amp;lt;/button&amp;gt;
    &amp;lt;/body&amp;gt;
    &amp;lt;script&amp;gt;
        function changeParagraphColor() {
            document.getElementById("test_paragraph").style.background = "red";
            var top = 100, nested = 1000;
            for(var i=0; i&amp;lt;top; i++) {
                for(var j=0; j&amp;lt;nested; j++) {
                    console.log(i + ":" + j);
                }
            }
            console.log("Changing color");
            document.getElementById("test_paragraph").style.background = "blue";
        }
    &amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the browser, we can see the following output.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1624807630595%2FsKsGkr4pB.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1624807630595%2FsKsGkr4pB.png" alt="Screenshot 2021-06-27 at 8.56.51 PM.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the above example, the background color of the paragraph is changed to blue after the execution of the loop. The red background never takes effect. If I remove line 21, I can see the red paragraph, but after the execution of the script (including the loop). I expected to see first a paragraph with red background and then a blue. But I only saw, blue background.&lt;/p&gt;

&lt;p&gt;Here, we are seeing the UI effect for the last line, but not the previous UI change. Why is that? That is because of the Rendering Step. The browser does not repaint the screen after the execution of each JavaScript code. It executes the above JavaScript code and collects all styling and UI changes. It applies final change (in this case line 21) in a single shot afterward, in the Rendering step. It is a step in the Event Loop that is executed independently. And initially, I thought the changes are happening so fast that my eyes could not catch them 😤. I will dive into the Rendering step in my next post.&lt;/p&gt;

&lt;h3&gt;
  
  
  Microtasks
&lt;/h3&gt;

&lt;p&gt;For now, I am associating Microtasks with JavaScript Promises. Promises are used to perform asynchronous operations in JavaScript. If you want to know more about Promises, visit this page for  &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" rel="noopener noreferrer"&gt;more details&lt;/a&gt;. The tasks executed inside Promise are called &lt;em&gt;Microtasks&lt;/em&gt;. Following is an example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    &amp;lt;body&amp;gt;
        &amp;lt;button id="demo"&amp;gt;Trigger Alert&amp;lt;/button&amp;gt;
    &amp;lt;/body&amp;gt;
    &amp;lt;script&amp;gt;
        document.getElementById("demo").addEventListener("click", () =&amp;gt; {
            Promise.resolve().then(() =&amp;gt; console.log("Micro Task 1"));
            console.log("Task 1");
        });
    &amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above example will print the following output as expected. Microtask will be executed after all the synchronous tasks are executed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Task 1
Micro Task 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's look into another interesting example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    &amp;lt;body&amp;gt;
        &amp;lt;button id="demo"&amp;gt;Trigger Alert&amp;lt;/button&amp;gt;
    &amp;lt;/body&amp;gt;
    &amp;lt;script&amp;gt;
        document.getElementById("demo").addEventListener("click", () =&amp;gt; {
            Promise.resolve().then(() =&amp;gt; console.log("Micro Task 1"));
            console.log("Task 1");
        });
        document.getElementById("demo").addEventListener("click", () =&amp;gt; {
            Promise.resolve().then(() =&amp;gt; console.log("Micro Task 2"));
            console.log("Task 2");
        });
    &amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Try guessing the output (take 5 seconds). If you guess the following output, it's perfectly alright! It is natural, intuitive, and we are human.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Task 1
Task 2
Micro Task 1
Micro Task 2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But the answer is&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Task 1
Micro Task 1
Task 2
Micro Task 2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you thought of the above answer, Congratulations! 😀 👍&lt;/p&gt;

&lt;h4&gt;
  
  
  How microtasks are executed?
&lt;/h4&gt;

&lt;p&gt;Micro tasks are executed in two situations&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;At the end of the synchronous script execution.&lt;/li&gt;
&lt;li&gt;If the Call Stack is empty.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;For handling microtasks, JavaScript maintains another queue - Microtask Queue. For each call to Promise, an entry for each microtask is pushed into Microtask Queue. So, for the above example, the following will be the order&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;em&gt;Task 1&lt;/em&gt; got pushed into Call Stack for synchronous execution. Also, &lt;em&gt;Microtask 1&lt;/em&gt; is enqueued in the Microtask Queue.&lt;/li&gt;
&lt;li&gt;After execution of &lt;em&gt;Task 1&lt;/em&gt;, the Call Stack gets empty. So, it's the microtask time (condition 2 above)! If there were any other synchronous calls, &lt;em&gt;Microtask 1&lt;/em&gt; would have been picked up after execution of those.&lt;/li&gt;
&lt;li&gt;Microtask Queue is dequeued and the &lt;em&gt;Microtask 1&lt;/em&gt; gets executed.&lt;/li&gt;
&lt;li&gt;After step 3, the second handler gets called by Event Loop. The same thing repeats for the second microtask.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  What are Event Loops?
&lt;/h2&gt;

&lt;p&gt;I know you might be thinking what am I talking about for this long. Nowadays, all browsers create a separate event loop for each browser tab. Collectively these are called &lt;strong&gt;Event Loops&lt;/strong&gt;. At first, Chrome started doing this. Others followed soon. &lt;/p&gt;

&lt;h3&gt;
  
  
  Impact of Event Loops
&lt;/h3&gt;

&lt;p&gt;I have seen one unresponsive page causing the entire browser to get stuck in Firefox's earlier version. I have never seen this issue with Chrome. Chrome has a separate JavaScript environment for each tab from early versions I believe. The browser might require more resources to do this. But I think, it is worth the better and richer experience.😌&lt;/p&gt;

&lt;h3&gt;
  
  
  Interesting Use case: Opening a page in a separate new tab
&lt;/h3&gt;

&lt;p&gt;Let's assume, for the below three examples, &lt;em&gt;target_page&lt;/em&gt; contains an infinite loop.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;a href="target_page" target="_blank"&amp;gt;New Target Page&amp;lt;/a&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For the earlier version browser, for the above scenario, the &lt;em&gt;target_page&lt;/em&gt; and &lt;em&gt;current page&lt;/em&gt; used to share the same Event Loop for all the JavaScript tasks. As a result, if the &lt;em&gt;target_page&lt;/em&gt; is containing an infinite loop, both the &lt;em&gt;current&lt;/em&gt; and &lt;em&gt;target_page&lt;/em&gt; got stuck in an infinite loop as well. Both the pages used to become unresponsive. The workaround proposed&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;a href="target_page" target="_blank" rel="noopener"&amp;gt;New Tab&amp;lt;/a&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Upon setting "rel=noopener", each page gets separate environment. It was introduced to reduce the impact of untrusted pages containing malicious JavaScript, which might affect the current page. Now, all the browsers have started implementing this behavior by default ( &lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Link_types/noopener" rel="noopener noreferrer"&gt;relevant MDN doc&lt;/a&gt;). I have tested with the latest Chrome. It is implemented there.&lt;/p&gt;

&lt;p&gt;Also, for this example,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;a href="target_page"&amp;gt;New Tab&amp;lt;/a&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you open &lt;em&gt;target_page&lt;/em&gt; in a new tab (by right click on the mouse), both the pages share the same JavaScript runtime environment. So, if &lt;em&gt;target_page&lt;/em&gt; has an infinite loop, both the pages get stuck.&lt;/p&gt;

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

&lt;p&gt;The Event Loop is an interesting and critical component for understanding any JavaScript run time environments. I am building up my knowledge on React JS and Node JS internals upon this. If you have enjoyed the article, do give me thumbs up. In case of any questions, let me know in the comments.&lt;/p&gt;

&lt;p&gt;Happy learning! 😀&lt;/p&gt;

&lt;h2&gt;
  
  
  References for further reading
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;a href="https://262.ecma-international.org/6.0/" rel="noopener noreferrer"&gt;EcmaScript Standard&lt;/a&gt; - EcmaScript standard has documentation around how each component such as Job Queues, Call Stack should be implemented. I find these details particularly interesting.&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>programming</category>
      <category>computerscience</category>
    </item>
    <item>
      <title>Abstract Introduction to React Internals</title>
      <dc:creator>Subhasish Kundu</dc:creator>
      <pubDate>Sat, 05 Jun 2021 15:50:25 +0000</pubDate>
      <link>https://dev.to/thecuriouscoder/abstract-introduction-to-react-internals-4gef</link>
      <guid>https://dev.to/thecuriouscoder/abstract-introduction-to-react-internals-4gef</guid>
      <description>&lt;p&gt;React is a rich JavaScript framework. I think it's necessary to know a high-level internal working of a language or a framework to use it effectively. React's performance comes from its internal data structures and algorithms. In this article, I will not touch upon the actual codebase, data structures, or algorithms. I will share, on a high level, how React 16 renders and updates the UI. So, let's get started!&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Smart data structures and dumb code works a lot better than the other way around. - Eric S. Raymond&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Internal Representation of Components
&lt;/h2&gt;

&lt;p&gt;During parsing, React creates an in-memory representation of components for easy rendering and updating. Typical React components can have multiple children and sibling components. We have multiple options to represent a component.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;N-ary tree.&lt;/li&gt;
&lt;li&gt;Multi-linked doubly linked list.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Sample Component
&lt;/h3&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h3&gt;
  
  
  Representation of The Component
&lt;/h3&gt;

&lt;p&gt;The following diagram shows the internal representation for the above component using both data structures. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1622879498150%2F5yXjKc_DU.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1622879498150%2F5yXjKc_DU.png" alt="BlogPosts (2).png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;For both the data structures, &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;we can represent the parent-child relationship vertically.&lt;/li&gt;
&lt;li&gt;we can represent sibling relationships horizontally.&lt;/li&gt;
&lt;li&gt;all the relationships are bidirectional for easy traversal. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;One thing to note - I am taking a component for simplicity. I am not taking the entire page into the scope.&lt;/p&gt;

&lt;h2&gt;
  
  
  Rendering and Updating React Component
&lt;/h2&gt;

&lt;p&gt;There can be two types of rendering - simple rendering without any updates or rendering page components after updates in a dynamic UI. Let's see how each scenario works.&lt;/p&gt;

&lt;h3&gt;
  
  
  Simple Rendering without Updates
&lt;/h3&gt;

&lt;p&gt;In this case, React can use a combination of Depth-First and Breadth-First Traversal to render the entire component (for both types of representation).&lt;/p&gt;

&lt;h3&gt;
  
  
  Handling UI Changes
&lt;/h3&gt;

&lt;p&gt;In a dynamic user interface, we will have periodic updates as well as other high-priority activities like network calls. It is possible while rendering current changes, some other high-priority tasks come up. In that case, React may have to do a context switch. And that's where React shines. How does React handle that? Let's jump into that.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;[I will use &lt;strong&gt;representation&lt;/strong&gt; and &lt;strong&gt;DS&lt;/strong&gt; (for data structure) inter-changeably.]&lt;/em&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Rendering Phase
&lt;/h4&gt;

&lt;p&gt;Let's call the original representation &lt;em&gt;current copy&lt;/em&gt;. Let's go step by step.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Engine starts cloning the &lt;em&gt;current copy&lt;/em&gt; into another DS by traversal. Let's call it &lt;em&gt;work-in-progress copy&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;If there is any change in any Node, it can tag the updated Node during traversal. It can store the updates in a separate internal DS like a list. Let's call it &lt;em&gt;effects list&lt;/em&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let's assume, for our example, &lt;em&gt;Logo&lt;/em&gt;,  &lt;em&gt;About Us&lt;/em&gt;, and &lt;em&gt;Products&lt;/em&gt; sub-components have changed after this operation. In that case, the following can be the &lt;em&gt;effects list&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1622888946045%2FLXypOKvMU.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1622888946045%2FLXypOKvMU.png" alt="Blog post List (3).png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why not update the UI while traversal?&lt;/strong&gt;&lt;br&gt;
Let's suppose, the user creates an animation with tasks A and B. React is supposed to render A and B consecutively for creating a rich experience. Now, a high-priority task has arrived between A and B. Engine cannot ignore it. If the engine has to perform it between A and B by stopping B, the user will see a glitch between A and B. It is not desired user experience.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why collect updates in a separate DS?&lt;/strong&gt;&lt;br&gt;
As a high-priority task may arrive in between, rendering may not be as important as that task. In that case, React should switch context. After finishing that task, it can resume the traversal again. This collection of updates will help React to start the operation easily again.&lt;/p&gt;

&lt;h4&gt;
  
  
  Commit Phase
&lt;/h4&gt;

&lt;p&gt;After the collection of updates in a DS, it's time for applying the changes. It has to go in one shot. Otherwise, the user will see glitches and partial updates.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;We can traverse the &lt;em&gt;effects list&lt;/em&gt; and apply the updates in the actual UI. It has to be synchronous operation.&lt;/li&gt;
&lt;li&gt;Once everything is done, React needs to store the updated DS in &lt;em&gt;current copy&lt;/em&gt; to represent the current UI. How to do that? Yes, you guessed it right - point &lt;em&gt;current copy&lt;/em&gt; to &lt;em&gt;work-in-progress copy&lt;/em&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The above steps complete the entire update cycle. React engine applies various optimizations. We will explore React internals in detail in the next post. I promise I will touch on React data structures and codebase.&lt;/p&gt;

&lt;h3&gt;
  
  
  Notes
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;React uses the Multi-Linked Doubly Linked List representation internally.&lt;/li&gt;
&lt;li&gt;I have used nomenclature used by React teams like &lt;em&gt;current copy&lt;/em&gt;, &lt;em&gt;work-in-progress copy&lt;/em&gt;, and &lt;em&gt;effects list&lt;/em&gt;. Naming is always harder. They did a good job with these names. So, I just used the names.&lt;/li&gt;
&lt;li&gt;In React 15, React used to perform partial updates as I mentioned in &lt;em&gt;Why not update the UI while traversal?&lt;/em&gt; section. In React 16, they have changed the algorithm.&lt;/li&gt;
&lt;li&gt;Using an effects list kind of DS in compiler is quite interesting. It is worth a separate post. I have seen this pattern to execute a bunch of assembly code for showing the final updates to the user for low-level language compilation. It is a great example of the power of simple data structures like Linked List. Let me know if you want to know more about this technique in the comments. I will try to create a post on that particularly.&lt;/li&gt;
&lt;li&gt;Check out my article about  &lt;a href="https://dev.to/subhakundu/virtual-dom-in-react-through-beginner-s-eye-39ph"&gt;React Virtual DOM&lt;/a&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If you enjoyed the article, please don't forget to like it. In case you have any doubts, ask in the comment section.&lt;/p&gt;

&lt;p&gt;Happy Learning! 😀&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>programming</category>
      <category>computerscience</category>
      <category>react</category>
    </item>
    <item>
      <title>How Virtual DOM is Powering React?</title>
      <dc:creator>Subhasish Kundu</dc:creator>
      <pubDate>Wed, 02 Jun 2021 20:19:09 +0000</pubDate>
      <link>https://dev.to/thecuriouscoder/virtual-dom-in-react-through-beginner-s-eye-39ph</link>
      <guid>https://dev.to/thecuriouscoder/virtual-dom-in-react-through-beginner-s-eye-39ph</guid>
      <description>&lt;p&gt;I have been doing front-end web development for last year only. Lately, I started playing with ReactJS. I have worked on vanilla JavaScript and jQuery for quite some time. My expert colleague at Amazon suggested I explore React. My only sin was I said, "Can't we have an abstraction over jQuery?"&lt;/p&gt;

&lt;p&gt;I have heard about React for a long time. The overwhelming number of tutorials on React made my learning very easy. I apologize to myself for not starting early. But better late, than never.&lt;/p&gt;

&lt;p&gt;I have worked on compilers for a long time. So, while exploring a new language, I try to think how an interpreter or compiler might do the trick. After learning syntax, I started exploring how React is improving performance. And I encountered Virtual DOM.&lt;/p&gt;

&lt;p&gt;[In this article, I will try to explain how virtual DOM might work with respect to a compiler. I will not go into any specific details. I am still learning how React is implemented. I will keep posting details.]&lt;/p&gt;

&lt;h2&gt;
  
  
  Document Object Model or DOM
&lt;/h2&gt;

&lt;p&gt;A tree of individual components that the browser creates upon receiving an HTML response from a server. JavaScript provides us ways to manipulate DOM to get the desired effect like displaying a div on clicking a button (Codepen sample).&lt;/p&gt;

&lt;p&gt;The above operation is expensive as the browser manipulating the DOM tree each time some changes are applied. I believe the browser has to do some smart computation for identifying the changed element and making the changes (like suppose, keeping a reference to each element in a hash map. I am still exploring it.). It is definitely an expensive operation - time and memory-wise. Also, the browser has other tasks to do like displaying the page.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Virtual DOM?
&lt;/h2&gt;

&lt;p&gt;"The virtual DOM (VDOM) is a programming concept where an ideal, or “virtual”, representation of a UI is kept in memory and synced with the “real” DOM by a library such as ReactDOM." - React Documentation .&lt;/p&gt;

&lt;p&gt;I did not even try to define it with my words. It is such a concise definition. What I have understood so far - React virtual DOM is an in-memory optimized representation of DOM. And React engine deals with low-level APIs to apply the changes.&lt;/p&gt;

&lt;h2&gt;
  
  
  How React brings Performance into Picture?
&lt;/h2&gt;

&lt;p&gt;Now, with the above concept, let's bring the compiler into the picture.&lt;/p&gt;

&lt;p&gt;Every compiler stores an entire program in some form of representation (Abstract Syntax Tree). I am mapping Virtual DOM to AST (I am still learning how React optimizes). As virtual DOM is an in-memory representation, React engine or compiler can access it fast. Now, let's go step by step.&lt;/p&gt;

&lt;p&gt;Now, if there is some change - React changes virtual DOM.&lt;br&gt;
React engine compares the virtual DOM with real DOM (aka "diffing") and applies the changes to the changed part only. It finds out the changes.&lt;br&gt;
It applies the changes using low-level APIs directly (like the JavaScript engine does for our code).&lt;br&gt;
React engine can apply optimizations in all three steps because virtual DOM representation is in its control. React engine is actually a very advanced JavaScript engine. With syntax and semantics of React, it can fasten the performance.&lt;/p&gt;

&lt;p&gt;Now, in JS, the browser is doing all the work. Also, to some extent, it is dependent on how code is being written. In the case of React, React engine is abstracting (remember the word I mentioned at the beginning) out all optimization.&lt;/p&gt;

&lt;p&gt;This is one of the reasons, React is faster than traditional HTML JS webpages. I know technically everything I mentioned might not be true and I have not touched upon a lot of things. As I keep exploring, I will keep posting my findings in detail. I will see how my concepts get cleared on the way. I hope you enjoyed the article.&lt;/p&gt;

&lt;p&gt;Happy learning!&lt;/p&gt;

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