JavaScript – How to Schedule a Timeout ?

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about JavaScript Timeout Concept. There can be multiple scenarios where a programmer decides to execute a function at a later time, instead of running it instantaneously. This kind of behavior is called “scheduling as call or “scheduling a timeout”.

For better understanding about the timeout concepts, We will discuss the below following the list of topics which we are going to cover in this article:-

  • What is Timeout in JavaScript?
  • How to Schedule a Timeout in JavaScript?
  • How to clear the Scheduled Timeout in JavaScript?

A famous quote about learning is :

” Tell me and I forget, teach me and I may remember, involve me and I learn.”

So, Let’s begin.

What is Timeout in JavaScript?

We are sure that every programmer would have faced the following scenarios during their development career:

  • A specific function developed need to wait for some time before performing a particular task or triggering an event.
  • A specific function or task needs to repeat at a predefined interval.

Now, to handle all such kind of scenarios, JavaScript provides the “Timeout” functionality. Moreover, this functionality essentially allows the JavaScript developer to specify in a script that a particular function or piece of JavaScript code should execute after a specified interval of time has elapsed or should be repeated at a set interval time only.

How to schedule a Timeout in JavaScript?

JavaScript provides two methods to achieve the scheduling functionality. These are:

  • setTimeout()
  • setInterval()

Let’s discuss both of these functions in detail:

1. setTimeout()

This function allows us to run a function once after the specified interval of time. Additionally, its syntax looks like below:

Syntax:

let timerId = setTimeout(function, timeInMilliseconds, <em>param1, param2, ...</em>);

Where,

  • function: This parameter specifies the function that needs to execute. Additionally, it is a mandatory parameter.
  • timeInMilliseconds: The parameter specifies the “number of milliseconds” to wait before executing the code. If omitted, we use the value 0. Additionally, it is an optional parameter.
  • param1, param2, … : These are the additional parameters to pass to the function. Moreover, these are the optional parameters.

Let’s understand the usage of setTimeout() function with few examples for some sample scenarios:

Example 1: Wait for Alert

Now, consider a straightforward situation, that the user needs to display an alert after 2 seconds. One can achieve this with the help of setTimeout() as shown in the below code snippet:

<html>

   <body>  

      Demonstrating setTimeout in javascript

   </br>

      <script type = "text/javascript">

        setTimeout(()=>{

            alert("WelCome!!");

        },2000)

      </script>   

   </body>

</html>

It is evident from the above code that the browser will display the alert with “WelCome!!” as text after 2 seconds of the page load.

2. setInterval()

This method allows us to run a function repeatedly, starting after the interval of time and then repeating continuously at that interval. Additionally, its syntax looks like below:

Syntax:

let timerId = setInterval(<em>function, timeInMilliseconds, param1, param2, ...</em>)

Where,

  • function: This parameter specifies the function that needs to execute. Additionally, it is a mandatory parameter.
  • timeInMilliseconds: The parameter specifies the intervals (in milliseconds) on how often to execute the code. If the value is less than 10, we use the value 10. Also, it is an optional parameter.
  • param1, param2, … : These are the additional parameters to pass to the function. Moreover, these are the optional parameters.

Let’s understand the usage of setInterval() function with the following example:

Example: Display a digital clock

Let’s modify the above scenario of displaying a digital clock using the setInterval() method as shown in the below code snippet:

<html>
  <body>
    Demonstrating setInterval for displaying a clock in javascript:
  
    <p id="txt"></p>

    <script>
      const myLet = setInterval(myTimer, 1000);

      function myTimer() {
        const date = new Date();
        const time = date.toLocaleTimeString();
        document.getElementById("txt").innerHTML = time;
      }
    </script>

  </body>
</html>

As it is evident from the above code snippet, it displays the digital time that gets updated every second using the setInterval() method.

How to clear the Scheduled Timeout in JavaScript?

To cancel the scheduled tasks, JavaScript provides two methods:

  • clearTimeout()
  • clearInterval()

1. clearTimeout()

This method clears a timer set with the setTimeout() method and prevents the function set with the setTimeout() to execute. Additionally, its syntax looks like below:

Syntax:

clearTimeout(timerId_of_setTimeout)

Where,

  • timerId_of_setTimeout: This parameter is the ID value of the timer returned by the setTimeout() method. Moreover, it is a mandatory field.

Let’s understand the functionality of clearTimeout() in detail with the help of following code snippet:

<html>
	<body>

		<button onclick="startCount()">Start count!</button>
		<input type="text" id="txt">
		<button onclick="stopCount()">Stop count!</button>

		<p>
			Click on the "Start count!" button above to start the timer 
			</br> Click on the "Stop count!" button to stop the counting.
		</p>

		<script>
			let count = 0;
			let time;
			let timer_flag = 0;

			function timedCount() {
	  			document.getElementById("txt").value = count;
	  			count = count + 1;
	  			time = setTimeout(timedCount, 1000);
			}

			function startCount() {
	  			if (!timer_flag) {
	    			timer_flag = 1;
	    			timedCount();
	  			}
			}

			function stopCount() {
	  			clearTimeout(time);
	  			timer_flag = 0;
			}
		</script>

	</body>
</html>

The above code snippet file shows how using the clearTimeout() method. The user can prevent the function from executing, which set using the setTimeout() method.

2. clearInterval()

This method clears the timer set with the setInterval() method or can cancel the schedule created using the setInterval() method. Additionally, its syntax looks like below:

Syntax:

clearInterval(timerId);

Where,

timeId: The parameter signifies the timer returned by the setInterval() method. It is a required field.

Let’s understand the functionality of clearInterval() in detail with the help of following code snippet, where user can invoke the clearInterval() method to stop the digital clock initiated using setInterval() method:

<html>
  <body>
    Demonstrating clearInterval for displaying/Stopping a clock in javascript:
  
    <p id="txt"></p>

    <button onclick="stopWatch()">Stop Timer</button>

    <script>
      const myInterval = setInterval(myTimer, 1000);

      function myTimer() {
        const date = new Date();
        const time = date.toLocaleTimeString();
        document.getElementById("txt").innerHTML = time;
      }

      function stopWatch() {
        clearInterval(myInterval);
      }
    </script>

  </body>
</html>

In the above example, as soon as one clicks the Stop Timer button, the setInterval function terminates.

That’s all about in this article.

Conclusion

In this article, We understood about JavaScript Timeout Concepts. We conclude that :

  • If we want to schedule the execution of a task/function, the same can be achieved in JavaScript using the setTimeout() and setInterval() methods.
  • If we want to cancel the already scheduled tasks, the same can be achieved in JavaScript using the clearTimeout() and clearInterval() method.

Thanks for reading ! I hope you enjoyed and learned about JavaScript Timeout Concept. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

JavaScript – Understanding DOM Manipulation

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about JavaScript popular DOM Manipulation Concepts. When developing a front-end application, one of the most expected things a programmer wants to do is to manipulate the document structure in some way. It happens by using the Document Object Model (DOM), which is a set of APIs for controlling HTML and styling information.

For better understanding about the concepts, We will discuss the following details related to DOM manipulation using JavaScript:

  • What is DOM?
  • DOM Terminologies
  • How to access DOM elements using JavaScript?
  • How to manipulate DOM elements using JavaScript?

A famous quote about learning is :

” Anyone who stops learning is old, whether at twenty or eighty. Anyone who keeps learning stays young. “

So, Let’s start.

What is DOM?

 DOM is a data representation of the objects in the HTML and XML pages. The document loaded in your browser is represented by a document object model. Moreover, it is a “tree structure” representation created by the browser that enables the HTML structure to be easily accessed by programming languages. Additionally, the DOM represents the document as nodes and objects. In this way, programming languages can connect to the page. Furthermore, a simple structure of a web page DOM will look like below:

DOM Terminologies

Before starting working on the DOM, we should understand the following terminologies related to DOM:

  • Element node: It represents any element that exists in the DOM.
  • Root node: This is the top node in the tree, which in the case of HTML, is always the “HTML” node.
  • Child node: This is a node that is directly inside another node. For example, <h2> is a child of  <body> in the above example.
  • Descendant node: This is a node that exists anywhere in the hierarchy of another node. For example, <h2> is a descendant of <html> in the above example.
  • Parent node: This is a node that has another node inside it. For example, <body> is the parent node of  <h2> in the above example.
  • Sibling nodes: The nodes which sit on the same level in the DOM tree. For example, <h2> and  <p> are siblings in the above example.
  • Text node: This is a node that contains a text string.

As we are now clear about the fundamental terminologies used in a document, let’s move to the next section to understand how the DOM elements can be accessed using JavaScript.

How to access DOM elements using JavaScript?

A webpage in JavaScript is a document, and JavaScript provides an object “document,” which designates the complete webpage. Moreover, the document object provides various properties and methods to access and manipulate the web elements loaded on the page. To identify and access the DOM elements, JavaScript uses three ways:

  • Accessing elements By ID
  • Accessing elements By TagName
  • Accessing elements By className

Let’s understand the details of each of these ways in the following sections:

1. Accessing elements By ID:

JavaScript can find HTML elements in the DOM based on the “id” of the element. The document object provides a method “getElementById()” to accomplish this task. Moreover, its syntax looks like below: 

Syntax :

document.getElementById(“IDName”);

Let’s understand the usage of the “getElementById” method with the help of the following code snippet.

<body>
 Demonstrating getElementById in javascript:    </br>
    <b id="bold">Development Tools Tutorial</b>
 
     <script type="text/javascript">
    // Get the element by Id and update text on that
     document.getElementById("bold").innerHTML = "Development Tools";
     </script>
    </body>
</html>

In the above example, we can see that element by id “bold” has been found. In addition to that, we also changed its attribute innerHTML to Development Tools.

2. Accessing a DOM element By TagName:

JavaScript can find the elements in the HTML based on the “tagName” and return an array of matching nodes. The inbuilt function, of document object, available for this is getElementByTagName(). Additionally, its syntax looks like below:

Syntax :

document.getElementByTagName(“tagName”);

Let’s understand the usage of “getElementByTagName” method with the help of following code snippet:

<html>    
 <body>
 Demonstrating getElementByTag in javascript:    </br>
    <b>Development Tools Tutorial</b>
 
     <script type="text/javascript">
    // Get the element by tag <b> and update text on that
     document.getElementsByTagName("b")[0].innerHTML = "Development Tools";
     </script>
    </body>
</html>

In the above example, we can see that the element by HTML tag “<b>” has been found. Additionally, we changed its attribute innerHTML to Development Tools.

3. Accessing a DOM element By ClassName:

JavaScript can find the element in the HTML based on the className attribute of the element and returns an array of matching nodes. The inbuilt function available in this operation is getElementByClassName(). Additionally, its syntax looks like below:

Syntax :

document.getElementByClassName(“ClassName”);

Let’s understand the usage of “getElementByClassName” method with the help of following code snippet:

<html>    
 <body>
 Demonstrating getElementsByClassName in javascript:    </br>
    <b class="bold">Development Tools Tutorial</b>
 
     <script type="text/javascript">
    // Get the element by className "bold" and update text on that
     document.getElementsByClassName("bold")[0].innerHTML = "Development Tools";
     </script>
    </body>
</html>

In the above example, we can see that element by className “bold” has been found. Additionally, we changed its attribute innerHTML to Development Tools.

How to manipulate DOM elements using JavaScript?

Apart from accessing the elements, JavaScript provides some methods and properties which can manipulate or change the values of the DOM elements. Few of those methods and properties are:

  • write
  • innerHTML
  • attributeName
  • Style.property
  • setAttribute
  • createElement and appendChild
  • removeChild
  • replaceChild

Let’s discuss all of these methods and properties in detail in the below sections:

1. write :

This method writes new elements or text to the HTML page. Additionally, its syntax looks like below:

Syntax:

document.write(“data”);

Let’s understand the usage of “write()” method with the help of following code snippet:

<html>
 
   <body>  
 
      Demonstrating document's write function in javascript:
 
   </br>
 
      <script type = "text/javascript">
 
         document.write("Development Tools Tutorials");
 
         document.write("</br>");
 
         document.write("<b>JavaScript Tutorial</b>");
 
      </script>   
 
   </body>
 
</html>

In the above example, we use the write function to add a text as well as to add a new HTML element.

2. innerHTML :

It is a property that we use to get or set the HTML or XML markup contained within the element. Also, its syntax looks like below:

Syntax:

node.innerhtml = “changingText”;

Where,

node: is any web element that can be found on the web page using document.getElementBy<Id/tagName/className>.

Let’s understand the usage of “innerHTML” property with the help of following code snippet:

<html>
 
   <body>  
 
      Demonstrating innerHTML property in javascript
 
   </br>
 
   <b id="example">JavaScript Tutorial</b>
 
      <script type = "text/javascript">
 
         document.getElementById("example").innerHTML="Development Tools";
 
      </script>   
 
   </body>
 
</html>

In the above example, we can see that the innerHTML property updates the text of the HTML element.

3. attributeName :

We use his property is used to get and update the value of an attribute of an HTML element. Additionally, its syntax looks like below:

Syntax :

node.atrributeName = value;

Where,

node: is any web element that can be found on the web page using document.getElementBy<Id/tagName/className>.

Let’s understand the usage of “attributeName” property with the help of following code snippet:

<html>
 
   <body>  
 
      Demonstrating attributeName property in javascript
 
   </br>
 
   <b id="example">JavaScript Tutorial</b>
 
      <script type = "text/javascript">
 
         // Update the "id" of the element to "demo" which has "id" as "example"
         document.getElementById("example").id="demo";
 
         
         // Get the element with "id" as "demo" and update its innerHTML text
         document.getElementById("demo").innerHTML="Development Tools";
 
      </script>   
 
   </body>
 
</html>

In the above example, the element is first changed from “example” to “demo” and then based on id “demo,” we are manipulating the text of the element.

4. Style.property :

We use this property to set or edit the existing style properties of an HTML tag. Also, its syntax looks like below:

Syntax:

node.Style.attribute = value;

Where,

node: is any web element that can be found on the web page using document.getElementBy<Id/tagName/className>.

Let’s understand the usage of “Style.attribute” method with the help of following code snippet:

<html>
 
   <body>  
 
      Demonstrating updating style properties in javascript
 
   </br>
 
   <b id="example">JavaScript Tutorial</b>
 
      <script type = "text/javascript">
 
         document.getElementById("example").style.color = "red";
 
      </script>   
 
   </body>
 
</html>

In the above example, the style attribute “color” has been updated to “red.”

5. setAttribute :

We use this function to create or update an attribute for the existing HTML element. Additionally, its syntax looks like below:

Syntax :

node.setAttribute(attributeName, attributeValue);

Where,

node: is any web element that can be found on the web page using document.getElementBy<Id/tagName/className>.

Let’s understand the usage of “setAttribute()” method with the help of following code snippet:

<html>
 
   <body>  
 
      Demonstrating setAttribute function in javascript
 
   </br>
 
   <b>JavaScript Tutorial</b>
 
      <script type = "text/javascript">
 
         document.getElementsByTagName("b")[0].setAttribute("id","example");
 
         document.getElementById("example").innerHTML="Development Tools";
 
      </script>   
 
   </body>
 
</html>

In the above example, the element is first added a new attribute “id” with value “example” to the <b> tagged HTML element and then based on id “example,” we are manipulating the text of the element.

6. createElement and appendChild :

This createElement() method is used to create a new element in the HTML DOM. Once the creation of element happens, it can append to a parent element using the appendChild() method. Moreover, its syntax looks like below: 

Syntax:

// Create a new node
var node = document.createElement(tagName);


// Append the node to parent
document.parentTag.appendChild(node);

Let’s understand the usage of “createElement() and appendChild()  method with the help of following code snippet:

<html>

   <body>  

      Demonstrating createElement function in javascript

   </br>

   <b>JavaScript Tutorial</b>

      <script type = "text/javascript">

         var b = document.createElement("a");

         b.innerHTML="ClickME";

         document.body.appendChild(b);

      </script>   

   </body>

</html>

In the above example, we created a new “anchor” element with the help of the “createElement” method and then appended the element to the document’s <body> element. Hence, it displays on the HTML page.

7. removeChild :

This function removes an HTML element from the document. Also, its syntax looks like below:

Syntax:

node.removechild(childNode);

Where,

node: is any web element that can be found on the web page using document.getElementBy<Id/tagName/className>.

Let’s understand the usage of “removeChild()” method with the help of following code snippet:

<html>

   <body>  

      Demonstrating removeChild function in javascript

   </br>

   <b>TOOLS QA</b>

   </br>

   <b id="demo">JavaScript Tutorial</b>

      <script type = "text/javascript">

        document.body.removeChild(document.getElementById("demo"));

      </script>   

   </body>

</html>

In the above example, we removed the HTML element, which was having “id” as “demo,” due to which the value “JavaScript Tutorial” could not print on the webpage.

8. replaceChild :

The replaceChild() method replaces a child node with a new node. The new node could be an existing node in the document, or you can create a new node. Additionally, its syntax looks like below: 

Syntax:

node.replaceChild(newnode, oldnode);

Where,

node: is any web element that can be found on the web page using document.getElementBy<Id/tagName/className>.

Let’s understand the usage of “replaceChild()” method with the help of following code snippet:

<html>
   <body>  
      Demonstrating replaceChild function in javascript: </br>
 
      <ul id="myList"><li>Coffee</li><li>Tea</li><li>Milk</li></ul>

      <button onclick="replaceListValue()">Replace first value of list</button>

      <script type = "text/javascript">
         
         function replaceListValue() {
            // Create a new list element
            var newListElement = document.createElement("li");
            var textNode = document.createTextNode("Water");
            newListElement.appendChild(textNode);

            // Replace the first element of list by the newly created element
            var list = document.getElementById("myList");
            list.replaceChild(newListElement, list.childNodes[0]);
         }
    
      </script>   
 
   </body>
 
</html>

In the above example, we replace the first element of the list on the click of the button. The replaceChild method also achieves the same.

That’s all about in this article.

Conclusion

In this article, We understood about JavaScript Fundamental Concept DOM Manipulation. We conclude that :

  • The document loaded in a browser is represented by the document object model (DOM). Moreover, it is a data representation of the objects in the HTML page.
  • Also, the ID, Tag Name, or Class Name of the HTML elements can access the DOM elements.
  • In addition to the above, JavaScript also provides various methods such as setAttribute, createElement, appendChild, removeChild, etc. Moreover, we can use them to manipulate/change multiple HTML elements within the page at run time.

Thanks for reading !! I hope you enjoyed and learned about JavaScript Fundamental Concept DOM Manipulation. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

ReactJS – Recommended Valuable Design Principles You Need To Know

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about Recommended Design Principles used in ReactJS , and then we will also try to understand a better idea of how we decide what React does and what React doesn’t do, and what our development philosophy is like. The React recommends below common design principles which we will discuss one by one:

  • Composition
  • Common Abstraction
  • Escape Hatches
  • Stability
  • Interoperability
  • Scheduling
  • Developer Experience
  • Debugging
  • Configuration
  • Beyond the DOM
  • Implementation
  • Optimized for Tooling
  • Dogfooding

A famous quote about learning is :

Learning never exhausts the mind.

So, Let’s begin.

1. Composition

The key feature of React is composition of components. Components written by different people should work well together. It is important to us that you can add functionality to a component without causing rippling changes throughout the codebase.

For example, it should be possible to introduce some local state into a component without changing any of the components using it. Similarly, it should be possible to add some initialization and teardown code to any component when necessary.

Components are often described as “just functions” but in our view they need to be more than that to be useful. In React, components describe any composable behavior, and this includes rendering, lifecycle, and state. Some external libraries like Relay augment components with other responsibilities such as describing data dependencies. It is possible that those ideas might make it back into React too in some form.

2. Common Abstraction

In general, we resist adding features that can be implemented in userland. We don’t want to bloat your apps with useless library code. However, there are exceptions to this.

For example, if React didn’t provide support for local state or lifecycle methods, people would create custom abstractions for them. When there are multiple abstractions competing, React can’t enforce or take advantage of the properties of either of them. It has to work with the lowest common denominator.

This is why sometimes we add features to React itself. If we notice that many components implement a certain feature in incompatible or inefficient ways, we might prefer to bake it into React. We don’t do it lightly. When we do it, it’s because we are confident that raising the abstraction level benefits the whole ecosystem. State, lifecycle methods, cross-browser event normalization are good examples of this.

3. Escape Hatches

React is pragmatic. It is driven by the needs of the products written at Facebook. While it is influenced by some paradigms that are not yet fully mainstream such as functional programming, staying accessible to a wide range of developers with different skills and experience levels is an explicit goal of the project.

If we want to deprecate a pattern that we don’t like, it is our responsibility to consider all existing use cases for it and educate the community about the alternatives before we deprecate it. If some pattern that is useful for building apps is hard to express in a declarative way, we will provide an imperative API for it. If we can’t figure out a perfect API for something that we found necessary in many apps, we will provide a temporary subpar working API as long as it is possible to get rid of it later and it leaves the door open for future improvements.

4. Stability

We value API stability. At Facebook, we have more than 50 thousand components using React. Many other companies, including Twitter and Airbnb, are also heavy users of React. This is why we are usually reluctant to change public APIs or behavior.

However we think stability in the sense of “nothing changes” is overrated. It quickly turns into stagnation. Instead, we prefer the stability in the sense of “It is heavily used in production, and when something changes, there is a clear (and preferably automated) migration path.”

When we deprecate a pattern, we study its internal usage at Facebook and add deprecation warnings. They let us assess the impact of the change. Sometimes we back out if we see that it is too early, and we need to think more strategically about getting the codebases to the point where they are ready for this change.

If we are confident that the change is not too disruptive and the migration strategy is viable for all use cases, we release the deprecation warning to the open source community. We are closely in touch with many users of React outside of Facebook, and we monitor popular open source projects and guide them in fixing those deprecations.

Given the sheer size of the Facebook React codebase, successful internal migration is often a good indicator that other companies won’t have problems either. Nevertheless sometimes people point out additional use cases we haven’t thought of, and we add escape hatches for them or rethink our approach.

We don’t deprecate anything without a good reason. We recognize that sometimes deprecations warnings cause frustration but we add them because deprecations clean up the road for the improvements and new features that we and many people in the community consider valuable.

5. Interoperability

We place high value in interoperability with existing systems and gradual adoption. Facebook has a massive non-React codebase. Its website uses a mix of a server-side component system called XHP, internal UI libraries that came before React, and React itself. It is important to us that any product team can start using React for a small feature rather than rewrite their code to bet on it.

This is why React provides escape hatches to work with mutable models, and tries to work well together with other UI libraries. You can wrap an existing imperative UI into a declarative component, and vice versa. This is crucial for gradual adoption.

6. Scheduling

Even when your components are described as functions, when you use React you don’t call them directly. Every component returns a description of what needs to be rendered, and that description may include both user-written components like <LikeButton> and platform-specific components like <div>. It is up to React to “unroll” <LikeButton> at some point in the future and actually apply changes to the UI tree according to the render results of the components recursively.

This is a subtle distinction but a powerful one. Since you don’t call that component function but let React call it, it means React has the power to delay calling it if necessary. In its current implementation React walks the tree recursively and calls render functions of the whole updated tree during a single tick. However in the future it might start delaying some updates to avoid dropping frames.

This is a common theme in React design. Some popular libraries implement the “push” approach where computations are performed when the new data is available. React, however, sticks to the “pull” approach where computations can be delayed until necessary.

React is not a generic data processing library. It is a library for building user interfaces. We think that it is uniquely positioned in an app to know which computations are relevant right now and which are not.

If something is offscreen, we can delay any logic related to it. If data is arriving faster than the frame rate, we can coalesce and batch updates. We can prioritize work coming from user interactions (such as an animation caused by a button click) over less important background work (such as rendering new content just loaded from the network) to avoid dropping frames.

To be clear, we are not taking advantage of this right now. However the freedom to do something like this is why we prefer to have control over scheduling, and why setState() is asynchronous. Conceptually, we think of it as “scheduling an update”.

The control over scheduling would be harder for us to gain if we let the user directly compose views with a “push” based paradigm common in some variations of Functional Reactive Programming. We want to own the “glue” code.

It is a key goal for React that the amount of the user code that executes before yielding back into React is minimal. This ensures that React retains the capability to schedule and split work in chunks according to what it knows about the UI.

There is an internal joke in the team that React should have been called “Schedule” because React does not want to be fully “reactive”.

7. Developer Experience

Providing a good developer experience is important to us.

For example, we maintain React DevTools which let you inspect the React component tree in Chrome and Firefox. We have heard that it brings a big productivity boost both to the Facebook engineers and to the community.

We also try to go an extra mile to provide helpful developer warnings. For example, React warns you in development if you nest tags in a way that the browser doesn’t understand, or if you make a common typo in the API. Developer warnings and the related checks are the main reason why the development version of React is slower than the production version.

The usage patterns that we see internally at Facebook help us understand what the common mistakes are, and how to prevent them early. When we add new features, we try to anticipate the common mistakes and warn about them.

We are always looking out for ways to improve the developer experience. We love to hear your suggestions and accept your contributions to make it even better.

8. Debugging

When something goes wrong, it is important that you have breadcrumbs to trace the mistake to its source in the codebase. In React, props and state are those breadcrumbs.

If you see something wrong on the screen, you can open React DevTools, find the component responsible for rendering, and then see if the props and state are correct. If they are, you know that the problem is in the component’s render() function, or some function that is called by render(). The problem is isolated.

If the state is wrong, you know that the problem is caused by one of the setState() calls in this file. This, too, is relatively simple to locate and fix because usually there are only a few setState() calls in a single file.

If the props are wrong, you can traverse the tree up in the inspector, looking for the component that first “poisoned the well” by passing bad props down.

This ability to trace any UI to the data that produced it in the form of current props and state is very important to React. It is an explicit design goal that state is not “trapped” in closures and combinators, and is available to React directly.

While the UI is dynamic, we believe that synchronous render() functions of props and state turn debugging from guesswork into a boring but finite procedure. We would like to preserve this constraint in React even though it makes some use cases, like complex animations, harder.

9. Configuration

We find global runtime configuration options to be problematic.

For example, it is occasionally requested that we implement a function like React.configure(options) or React.register(component). However this poses multiple problems, and we are not aware of good solutions to them.

What if somebody calls such a function from a third-party component library? What if one React app embeds another React app, and their desired configurations are incompatible? How can a third-party component specify that it requires a particular configuration? We think that global configuration doesn’t work well with composition. Since composition is central to React, we don’t provide global configuration in code.

We do, however, provide some global configuration on the build level. For example, we provide separate development and production builds. We may also add a profiling build in the future, and we are open to considering other build flags.

10. Beyond the DOM

We see the value of React in the way it allows us to write components that have fewer bugs and compose together well. DOM is the original rendering target for React but React Native is just as important both to Facebook and the community.

Being renderer-agnostic is an important design constraint of React. It adds some overhead in the internal representations. On the other hand, any improvements to the core translate across platforms.

Having a single programming model lets us form engineering teams around products instead of platforms. So far the tradeoff has been worth it for us.

11. Implementation

We try to provide elegant APIs where possible. We are much less concerned with the implementation being elegant. The real world is far from perfect, and to a reasonable extent we prefer to put the ugly code into the library if it means the user does not have to write it. When we evaluate new code, we are looking for an implementation that is correct, performant and affords a good developer experience. Elegance is secondary.

We prefer boring code to clever code. Code is disposable and often changes. So it is important that it doesn’t introduce new internal abstractions unless absolutely necessary. Verbose code that is easy to move around, change and remove is preferred to elegant code that is prematurely abstracted and hard to change.

12. Optimized for Tooling

Some commonly used APIs have verbose names. For example, we use componentDidMount() instead of didMount() or onMount(). This is intentional. The goal is to make the points of interaction with the library highly visible.

In a massive codebase like Facebook, being able to search for uses of specific APIs is very important. We value distinct verbose names, and especially for the features that should be used sparingly. For example, dangerouslySetInnerHTML is hard to miss in a code review.

Optimizing for search is also important because of our reliance on codemods to make breaking changes. We want it to be easy and safe to apply vast automated changes across the codebase, and unique verbose names help us achieve this. Similarly, distinctive names make it easy to write custom lint rules about using React without worrying about potential false positives.

JSX plays a similar role. While it is not required with React, we use it extensively at Facebook both for aesthetic and pragmatic reasons.

In our codebase, JSX provides an unambiguous hint to the tools that they are dealing with a React element tree. This makes it possible to add build-time optimizations such as hoisting constant elements, safely lint and codemod internal component usage, and include JSX source location into the warnings.

13. Dogfooding

 Dogfooding it means that our vision stays sharp and we have a focused direction going forward.

We try our best to address the problems raised by the community. However we are likely to prioritize the issues that people are also experiencing internally at Facebook. Perhaps counter-intuitively, we think this is the main reason why the community can bet on React.

Heavy internal usage gives us the confidence that React won’t disappear tomorrow. React was created at Facebook to solve its problems. It brings tangible business value to the company and is used in many of its products. 

For example, we added support for web components and SVG to React even though we don’t rely on either of them internally. We are actively listening to your pain points and address them to the best of our ability. The community is what makes React special to us, and we are honored to contribute back.

After releasing many open source projects at Facebook, we have learned that trying to make everyone happy at the same time produced projects with poor focus that didn’t grow well. Instead, we found that picking a small audience and focusing on making them happy brings a positive net effect. That’s exactly what we did with React, and so far solving the problems encountered by Facebook product teams has translated well to the open source community.

The downside of this approach is that sometimes we fail to give enough focus to the things that Facebook teams don’t have to deal with, such as the “getting started” experience. We are acutely aware of this, and we are thinking of how to improve in a way that would benefit everyone in the community without making the same mistakes we did with open source projects before.

That’s all about in this article.

Conclusion

In this article, We understood about Recommended Design Principles used in ReactJS.

Thanks for reading ! I hope you enjoyed and learned about React recommended design principles. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

ReactJS – Is SOLID Valid For React?

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about topic ” Is Solid principle valid for React? “. We will focus each principle details of the SOLID one by one using below points:

  • What does the principle mean?
  • How does React adhere to it ?


SOLID is an interesting topic in React. While React doesn’t force the principles onto you, at least it often allows you to follow them.

A famous quote about learning is :

That is what learning is. You suddenly understand something you’ve understood all your life, but in a new way. ”  

So, Let’s begin.


What does SOLID stand for?

SOLID is an acronym build by the first letter of 5 object oriented programming design principles. The basic idea is, if you follow these principles, your software gets better.

  • Single responsibility principle
  • Open/closed principle
  • Liskov substitution principle
  • Interface segregation principle
  • Dependency inversion principle


What do these principles imply and how does React adhere to it?


1. Single Responsibility Principle

What does it mean?

A class should only have a single responsibility.

How does React adhere to it?

React applications consist of components, which are classes that inherit from the React.Component class. You can start building your application as a component and if it gets too complex, you can split this component up into multiple smaller components.

React doesn’t force you to adhere to the principle, but you can split up your component classes into smaller components till you achieved single responsibility for all of your components.

For example, you could have a button component that just handles clicks and an input component that just handles user input. A level above you use a form component that uses multiple instances of the button and input component to get user credentials and above that a connection component that takes form data and sends it to a server.


2. Open Close Principle

What does it mean?

Software entities should be open for extension, but closed for modification. Which means you can extends it without modifying its source code.

How does React adhere to it?

Reacts component model is build around aggregation instead of inheritance. So you only extend the base React.Component and not its children. This prevents you from overriding behavior of existing components directly. The only way is to wrap it with your own component.

You could for example wrap a Button with a RedButton that always applies specific styles to the basic Button, but the Button is closed for modification.

This is less flexible than inheritance, but it also simplifies the API. While you don’t have direct access to the methods like in an extension, you only have to care about props in your aggregation.


3. Liskov Substitution Principle

What does it mean?

Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.

How does React adhere to it?

Well, it doesn’t use inheritance at all. Sure you extend React.Component, but this class is essentially treated as abstract in React applications, you never directly create an object from it, so you never have to replace it with a child-class later.

On the other hand, you find yourself writing aggregations that should act like their wrapped components rather often. Like the Button I mentioned before. You want that RedButton to be already styled, but you also want it to act like the Button, but since the API between components always is just props, it’s often simple to add something while your wrappers props are passed down to the wrapped component. Because everything is dynamic, your wrapper doesn’t even have to know everything about the data that would originally be passed down to the wrapped component, in the RedButton example it would just have to know about the style.


4. Interface Segregation Principle

What does it mean?

Many client-specific interfaces are better than one general-purpose interface.

How does React adhere to it?

Because React is written in JavaScript, it benefits from the dynamic nature of this language. There are no formal interfaces. If you don’t use refs, which allow you to directly call class methods of a component, the only interaction between components is via props and nobody forces you to use props you don’t need.

If you have a wrapper component that passes down an onClick handler that shows an alert with the wrapped components class name, you can use this wrapper to wrap all components that use this onClick prop and if they don’t, the handler is just ignored.

My experience with this fact was that it simplified many things, you wouldn’t get lost in defining many small interfaces beforehand. The drawback was that I often found me in situations where I passed down props the wrapped component did simply ignore silently. At least glamorous-native threw a few warnings when I tried to pass down unknown CSS attributes. For this it often helps to use PropTypes or something.


5. Dependency Inversion Principle

What does it mean?

One should depend upon abstractions, not concretions.

How does React adhere to it?

In practice, this principle is often followed by removing class names from other classes. Like, you could have a List that has Items, so you could get the idea to create your Item objects inside the List class, now you have your List tightly coupled with your Item. Somewhere in your List class is a new Item(...) or Item.create(...) etc.

React doesn’t strictly adhere to it, you can pass an array of string to your List component and create Item children from it no problem.

But you can also tell the List it should simply render out its children independent of what they are, maybe add some keys to it or justify them etc.

Now you can create an array of Items, sprinkle it with some HighlightItems, both created from different string arrays and put them inside your List who won’t be the wiser.

That’s all about in this article.


Conclusion

In this article, We understood What do SOLID principles imply and how does React adhere to it. We learnt that React doesn’t force the principles onto you, but at least it often allows you to follow them. Sometimes it gets easier because of JavaScript, sometimes JavaScript makes it harder, but overall it is possible to write SOLID applications with React..

Thanks for reading ! I hope you enjoyed and learned about SOLID imply and adhere concepts in React. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

ReactJS – A Overview of class components and functional components with Hooks

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about class components and functional components differences and which one is best use for Hooks. A famous quote about learning is :

The beautiful thing about learning is that nobody can take it away from you.”

So Let’s begin.

The simplest way to define a component in React is to write a JavaScript function that returns a React element:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

The Welcome component accepts props which is an object that contains data and returns a React element. We can then import and render this component in another component.

The class component uses a programming methodology called Encapsulation which basically means that everything relevant to the class component will live within it. Life-cycle methods (constructorscomponentDidMount()render, and so on) give components a predictable structure.

Encapsulation is one of the fundamentals of OOP (Object-Oriented Programming). It refers to the bundling of data within the methods that operate on that data, and is used to hide the values or state of a structured data object inside a class — preventing unauthorized parties’ direct access to them.

With Hooks, the composition of a component changes from being a combination of life-cycle Hooks — to functionalities with some render at the end.

Function Component

The example below shows how custom Hooks can be used in a functional component (without showcasing what the body is). However, what it does or can do is not limited. It could be instantiating state variables, consuming contexts, subscribing the component to various side effects — or all of the above if you’re using a custom hook!

function {
  useHook{...};
  useHook{...};
  useHook{...};
  return (
    ...
  );
}

Class Component

class component requires you to extend from React.Component and create a render function which returns a React element. This requires more code but will also give you some benefits.

class {
  constructor(props) {...}
  componentDidMount() {...}
  componentWillUnmount() {...}
  render() {...}
}

So, Which one is best for Hooks ?

The Answer is :

There are some benefits you get by using functional components in React:

  1. It will get easier to separate container and presentational components because you need to think more about your component’s state if you don’t have access to setState() in your component.
  2. Functional components are much easier to read and test because they are plain JavaScript functions without state or lifecycle-hooks.
  3. You end up with less code.
  4. The React team mentioned that there may be a performance boost for functional components in future React versions.

This leads to the first best practice when using React Hooks.

That’s all about in this article.

Conclusion

In this article, We understood the Class component and functional component differences and benefits in Hooks with Which one is best for Hooks.

Thanks for reading ! I hope you enjoyed and learned about React class components and functional components differences and which one is best use for Hooks. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

ReactJS – Fundamental Best Practice And Tips

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about fundamental Best Practice and Tips in React Application. For any application development, fundamental best practice and tips are most important for developer who developed the application. We will discuss the below most fundamental of React best Practices one by one:

  1. Keep components small and function-specific
  2. Reusability
  3. Consolidate duplicate code – DRY your code
  4. Put CSS in JavaScript
  5. Comment only where necessary
  6. Name the component after the function
  7. Use capitals for component names
  8. Mind the other naming conventions
  9. Separate stateful aspects from rendering
  10. Code should execute as expected and be testable
  11. All files related to any one component should be in a single folder
  12. Use tools like Bit
  13. Use snippet libraries
  14. Write tests for all code
  15. Use ES Lint for better coding conventions.

A famous quote about learning is :

An investment in knowledge pays the best interest.”

So Let’s begin.

1. Keep components small and function-specific

As we all know, with React, it’s possible to have huge components that execute a number of tasks. But a better way to design components is to keep them small, so that one component corresponds to one function. Ideally, a single component should render a specific bit of your page or modify a particular behavior.

There are many advantages to this:

  • Function-specific components can be standalone, which makes testing and maintenance easier.
  • Each small component can be reused across multiple projects.
  • Components executing general functions can be made available to the community.
  • With smaller components, it’s easier to implement performance optimizations.
  • It’s easier to update smaller components.
  • Bigger components have to perform harder and may be difficult to maintain.

The balance between creating one concise component and creating multiple function-specific components can vary from organization to organization. After all, you can have as many components as you want, and recombine them in any way you want to achieve the same end result.

2. Reusability 

By sticking to the rule of one function = one component, you can improve the reusability of components. What this means is that you should skip trying to build a new component for a function if there already exists a component for that function.

Reusability is important, so keep creation of new components to the minimum required.

For example, you can even go further and create a Button component that can handle icons. Then, each time you need a button, you’ll have a component to use. Making it more modular will allow you to cover many cases with the same piece of code. You have to aim somewhere in the middle. Your components should be abstract enough, but shouldn’t be overly complex.

class IconButton extends React.Component {
  [...]
  render() {
    return (
      <button onClick={this.props.onClick()}>
        <i class={this.props.iconClass}></i>
      </button>
    );
  }
}

3. Consolidate duplicate code – DRY your code

A common rule for all code is to keep it as brief and concise as possible.

Here, React best practices also instruct you to keep code brief and precise. One way to do this is to avoid duplication – Don’t Repeat Yourself (DRY).

You can achieve this by scrutinizing the code for patterns and similarities. This relies heavily on the reusability principle in React. Let’s say you want to add multiple buttons that contain icons, instead of adding the markup for each button, you can simply use the IconButton component that we shown above. You could even go further by mapping everything into an array.

const buttons = ['facebook', 'twitter', 'youtube'];

return (
  <div>
    {
      buttons.map( (button) => {
        return (
          <IconButton
            onClick={doStuff( button )}
            iconClass={button}
          />
        );
      } )
    }
  </div>
);

4. Put CSS in JavaScript

When you start working on a project, it is a common practice to keep all the CSS styles in a single SCSS file. The use of a global prefix prevents any potential name collisions. However, when your project scales up, this solution may not be feasible.

There are many libraries that enable you to write CSS in JS. EmotionJS and Glamorous are the two most popular CSS in JS libraries.

5. Comment only where necessary

Attach comments to code only where necessary. This is not only in keeping with React best practices, it also serves two purposes at the same time:

  • It’ll keep code visually clutter free.
  • You’ll avoid a potential conflict between comment and code, if you happen to alter the code at some later point in time.

6. Name the component after the function

It’s a good idea to name a component after the function that it executes so that it’s easily recognizable.

For example, ProductTable – it conveys instantly what the component does. On the other hand, if you name the component based on the need for the code, it can confuse you at a future point of time.

One more example, it’s preferable to name a component Avatar so that it can be used anywhere – for authors, users or in comments. Instead, if we name the component AuthorAvatar in the context of its usage, we’d be limiting the utility of that component.

Besides, naming a component after the function makes it more useful to the community as it’s more likely to be discovered.

7. Use capitals for component names

If you’re using JSX (a JavaScript extension), the names of the components you create need to begin with uppercase letters. For instance, you’ll name components as SelectButton instead of selectbutton, or Menu instead of menu. We do this so that JSX can identify them differently from default HTML tags.

8. Mind the other naming conventions

When working with React, you are generally using JSX (JavaScript Extension) files. Any component that you create for React should therefore be named in upper camel case. This translates to names without spaces and the capitalizing the first letter of every word.

If you want to create a function that submits a form, you should name it SubmitForm in upper camel case, rather than submitFormsubmit_form, or submit_form. Camel case is also called Pascal case.

PascalCase is a naming convention in which the first letter of each word in a compound word is capitalized. Software developers often use PascalCase when writing source code to name functions, classes, and other objects.

PascalCase is similar to camelCase, except the first letter in PascalCase is always capitalized. Below are some examples.

  • PascalCase: NewObject;
  • camelCase: newObject;
  • PascalCase: LongFunctionName()
  • camelCase: longFunctionName()

Both PascalCase and CamelCase help developers distinguish words within names. For example, “LongFunctionName” is more readable than “longfunctionname.”

9. Separate stateful aspects from rendering

Components in React can be stateful or stateless.

Stateful components store information about the component’s state and provide the necessary context. In contrast, stateless components have no memory and cannot give context to other parts of the UI. They only receive props (inputs) from parent component and return you JSX elements. They are scalable and reusable, and similar to pure function in JavaScript.

One of React best practices is to keep your stateful data-loading logic separate from your rendering stateless logic. It’s better to have one stateful component to load data and another stateless component to display that data. This reduces the complexity of the components.

The later React versions v16.8 have a new feature – React Hooks, which write stateful function-related components. This may eventually eliminate the need for class-based components.

For example, your app is fetching some data on mount. What you want to do is manage the data in the main component and pass the complex render task to a sub-component as props.

import RenderTable from './RenderTable';

class Table extends Component {
  state = { loading: true };

  render() {
    const { loading, tableData } = this.state;
    return loading ? <Loading/> : <RenderTable data={tableData}/>;
  }

  componentDidMount() {
    fetchTableData().then( tableData => {
      this.setState( { loading: false, tableData } );
    } );
  }
}

10. Code should execute as expected and be testable

The code you write should behave as expected, and be testable easily and quickly. It’s a good practice to name your test files identical to the source files with a .test suffix. It’ll then be easy to find the test files.

In React to test component we use Jest and Enzyme. Jest was created by Facebook and is a testing framework to test javascript and React code. Together with Airbnb’s Enzyme, which is a testing utility, makes it the perfect match to easily test your React application.

11. All files related to any one component should be in a single folder

Keep all files relating to any one component in a single folder, including styling files.

If there’s any small component used by a particular component only, it makes sense to keep these smaller components all together within that component folder. The hierarchy will then be easy to understand – large components have their own folder and all their smaller parts are split into sub-folders. This way, you can easily extract code to any other project or even modify the code whenever you want.

For instance, for the Form component, all pieces such as CSS files, icons, images, tests and any other sub-components relating to Form should all reside in the same folder. If you name files sensibly, and keep related files together logically, you’ll not have any difficulty finding them later.

12. Use tools like Bit

One of React best practices that helps to organize all your React components is the use of tools like Bit.

These tools help to maintain and reuse code. Beyond that, it helps code to become discoverable, and promotes team collaboration in building components. Also, code can be synced across projects.

13. Use snippet libraries

Code snippets help you to keep up with the best and most recent syntax. They also help to keep your code relatively bug free, so this is one of the React best practices that you should not miss out on.

There are many snippet libraries that you can use, like, ES7 React, Redux, JS Snippets, etc.

14. Write tests for all code

In any programming language, adequate testing ensures that any new code added to your project integrates well with existing code and does not break existing functionality. It is a good idea to write tests for any new component that you create. As a good practice, you should create a __Test__ directory within your component’s directory to house all relevant tests.

You can broadly divide tests in React into two parts: testing the functionality of components using a React app, and tests on your complete application once it renders in the browser. You can use cross browser testing tools for tests in the latter category.

For the former, you can use a JavaScript test runner, Jest to emulate the HTML DOM using jsdom to test React components. While a completely accurate test is only possible in a browser on a real device, Jest provides a good approximation of the real testing environment during the development phase of your project.

15. Use ES Lint for better coding conventions

Linting is a process wherein we run a program that analyses code for potential errors.

Well run projects have clear consistent coding conventions, with automated enforcement. Besides checking style, linters are also excellent tools for finding certain classes of bugs, such as those related to variable scope. Assignment to undeclared variables and use of undefined variables are examples of errors that are detectable at lint time.

That’s all about React fundamental best practices and tips.

Conclusion

In this article, We understood the list of React fundamental best practices is going to help you put your projects on the right track, and avoid any potential problems later down the road.

Thanks for reading ! I hope you enjoyed and learned about React fundamental best practices list. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

JavaScript – 7 Quick Valuable Core Concepts Of Functional Programming

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about the functional programming core concepts in JavaScript which helps to improve your functional code tends to be more concise, more predictable, and easier to test. Functional programming has become a really hot topic in the JavaScript World.

A famous quote about learning is :

Try to learn something about everything and everything about something.


So Let’s begin.


What is Functional Programming ?

Functional Programming is :

  • The process of building software by composing pure functions, avoiding shared statemutable data, and side-effects
  • Declarative rather than imperative, and application state flows through pure functions.
  • A programming paradigm, meaning that it is a way of thinking about software construction based on some fundamental, defining principles.

In Contrast with object oriented programming, where application state is usually shared and colocated with methods in objects.

Other examples of programming paradigms include object oriented programming and procedural programming.

We can say that in functional programming, functional code tends to be more concise, more predictable, and easier to test than imperative or object oriented code.

After that, Second question is in our mind that :


Why is it most important in the JavaScript World ?

To understand the meaning and importance of the functional programming, we need to understand the below core concepts:

  • Pure functions
  • Function composition
  • Avoid shared state
  • Avoid mutating state
  • Avoid side effects
  • Reusability through Higher Order Functions
  • Declarative vs Imperative


1. Pure function :

A pure function is a function which :

  • Given the same inputs, always returns the same output, and 
  • Has no side-effects

Pure functions have lots of properties that are important in functional programming, including referential transparency (You can replace a function call with its resulting value without changing the meaning of the program). 


2. Functional Composition :

Functional composition is the process of combining two or more functions in order to produce a new function or perform some computation. For example, the composition f.g (the dot means “composed with”) is equivalent to f(g(x)) in JavaScript. Understanding function composition is an important step towards understanding how software is constructed using  the functional programming.


3. Avoid Shared State :

Shared state is any variable, object, or memory space that exists in a shared scope, or as the property of an object being passed between scopes. A shared scope can include global scope or closure scopes.

Often, in object oriented programming, objects are shared between scopes by adding properties to other objects.

For example, a computer game might have a master game object, with characters and game items stored as properties owned by that objects. Functional programming avoids shared state  instead relying on immutable data structures and pure calculations to derive  new data from existing data.

Here question comes in our mind, that Why avoid the shared state ?

So there is two common problems with shared state :

  • The first problem with shared state is that in order to understand the effects of a function, you have to know the entire history of every shared variable that the function uses or affects.
  • Another common problem associated with shared state is that changing the order in which functions are called can cause a cascade of failures because functions which act on shared state are timing dependent.

When you avoid shared state, the timing and order of function calls don’t change the result of calling the function. With pure functions, given the same input, you’ll always get the same output. This makes function calls completely independent of other function calls, which can radically simplify changes and refactoring. A change in one function, or the timing of a function call won’t ripple out and break other parts of the program.


4. Avoid mutating state :

An immutable object is an object that can’t be modified after it’s created. Conversely, a mutable object is any object which can be modified after it’s created.

Immutability is a central concept of functional programming because without it, the data flow in your program is lossy. State history is abandoned, and strange bugs can creep into your software.

So here question comes in our mind, Why we talk about immutability or an immutable object ? but here topic heading is avoid mutating state.

So, to understand avoid mutating state concept, we need to first understand An immutable object or Immutability concept.

In JavaScript, it’s important not to confuse const, with immutability. const creates a variable name binding which can’t be reassigned after creation. const does not create immutable objects. You can’t change the object that the binding refers to, but you can still change the properties of the object, which means that bindings created with const are mutable, not immutable.

Immutable objects can’t be changed at all. You can make a value truly immutable by deep freezing the object. JavaScript has a method that freezes an object one-level deep.But frozen objects are only superficially immutable.

Then one more question comes in our mind, How to implement deep frozen for object and which mechanism or data structure is used?

In many functional programming languages, there are special immutable data structures called trie data structures (pronounced “tree”) which are effectively deep frozen — meaning that no property can change, regardless of the level of the property in the object hierarchy.

Tries use structural sharing to share reference memory locations for all the parts of the object which are unchanged after an object has been copied by an operator, which uses less memory, and enables significant performance improvements for some kinds of operations.

For example, you can use identity comparisons at the root of an object tree for comparisons. If the identity is the same, you don’t have to walk the whole tree checking for differences.

There are several libraries in JavaScript which take advantage of tries, including Immutable.js and more.


5. Avoid side effects :

A  side effect is any application state change that is observable outside the called function other than its return value. 

Side effects include : 

  • Modifying any external variable or object property (e.g., a global variable, or a variable in the parent function scope chain)
  • Logging to the console
  • Writing to the screen
  • Writing to a file
  • Writing to the network
  • Triggering any external process
  • Calling any other functions with side-effects

Side effects are mostly avoided in functional programming, which makes the effects of a program much easier to understand, and much easier to test. Haskell and other functional languages frequently isolate and encapsulate side effects from pure functions using  monads.

If you keep your side effects separate from the rest of your program logic, your software will be much easier to extend, refactor, debug, test, and maintain.

This is the reason that most front-end frameworks encourage users to manage state and component rendering in separate, loosely coupled modules.


6. Reusability through Higher Order Functions :

higher order function is any function which takes a function as an argument, returns a function, or both. Higher order functions are often used to :

  • Abstract or isolate actions, effects, or async flow control using callback functions, promises, monads, etc…
  • Create utilities which can act on a wide variety of data types
  • Partially apply a function to its arguments or create a curried function for the purpose of reuse or function composition
  • Take a list of functions and return some composition of those input functions

Functional programming tends to reuse a common set of functional utilities to process data. JavaScript has first class functions, which allows us to treat functions as data — assign them to variables, pass them to other functions, return them from functions, etc…


7. Declarative vs Imperative :

Functional programming is a declarative paradigm, meaning that the program logic is expressed without explicitly describing the flow control.

The two difference between Declarative and Imperative programs are :

  • Imperative programs spend lines of code describing the specific steps used to achieve the desired results — the flow control: How to do things. Where as Declarative programs abstract the flow control process, and instead spend lines of code describing the data flow: What to do. The how gets abstracted away.
  • Imperative code frequently utilizes statements. A statement is a piece of code which performs some action. Examples of commonly used statements include for, if, switch, throw, etc… where as Declarative code relies more on expressions. An expression is a piece of code which evaluates to some value. Expressions are usually some combination of function calls, values, and operators which are evaluated to produce the resulting value. 

That’s all about in this article.


Conclusion

In this article, We understood the functional programming core concepts in JavaScript. In Summary, Functional Programming favors :

  • Pure functions instead of shared state & side effects
  • Immutability over mutable data
  • Function composition over imperative flow control
  • Lots of generic, reusable utilities that use higher order functions to act on many data types instead of methods that only operate on their colocated data
  • Declarative rather than imperative code (what to do, rather than how to do it)
  • Expressions over statements
  • Containers & higher order functions over ad-hoc polymorphism

Thanks for reading ! I hope you enjoyed and learned about the functional programming core concepts in JavaScript. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???


JavaScript – S.O.L.I.D – The Five Principles Of Object Oriented Design

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about the Javascript 5 SOLID Principles. The SOLID principles are a set of software design principles, that help us to understand how we can structure our code in order to be robust, maintainable and flexible as much as possible.

“JavaScript is a loosely typed language, some consider it a functional language, others consider it an object oriented language, some think its both, and some think that having classes in JavaScript is just plain wrong. — Dor Tzur.”

From my experience, we’ll rarely want to use classes and long inheritance chains in JavaScript. But still, SOLID principles are pretty solid.

SOLID principles are the basic pillars of OOP set forward by our beloved Uncle Bob.

A famous quote about learning is :

” Live as if you were to die tomorrow. Learn as if you were to live forever. “

So Let’s begin.


What is S.O.L.I.D. ?

S.O.L.I.D. stands for :

  • S — Single responsibility principle
  • O — Open closed principle
  • L — Liskov substitution principle
  • I — Interface segregation principle
  • D — Dependency Inversion principle

Let’s see them one by one.


1. Single Responsibility Principle

“A class should have one and only one reason to change, meaning that a class should only have one job.”

For example, say we have some shapes and we wanted to sum all the areas of the shapes. 

const circle = (radius) => {
  const proto = { 
    type: 'Circle',
    //code 
  }
  return Object.assign(Object.create(proto), {radius})
}
const square = (length) => {
  const proto = { 
    type: 'Square',
    //code 
  }
  return Object.assign(Object.create(proto), {length})
}

First, we create our shapes factory functions and setup the required parameters.

so, What is a factory function ?

“In JavaScript, any function can return a new object. When it’s not a constructor function or class, it’s called a factory function.”

Next, we move on by creating the areaCalculator factory function and then write up our logic to sum up the area of all provided shapes.

const areaCalculator = (s) => {
  const proto = {
    sum() {
      // logic to sum
    },
    output () {
     return `
       <h1>
         Sum of the areas of provided shapes:
         ${this.sum()} 
       </h1>
    }
  }
  return Object.assign(Object.create(proto), {shapes: s})
}

To use the areaCalculator factory function, we simply call the function and pass in an array of shapes, and display the output at the bottom of the page.

const shapes = [
  circle(2),
  square(5),
  square(6)
]
const areas = areaCalculator(shapes)
console.log(areas.output())

The problem with the output method is that the areaCalculator handles the logic to output the data. Therefore, what if the user wanted to output the data as json or something else ?

All of the logic would be handled by the areaCalculator factory function, this is what ‘Single Responsibility principle’ frowns against; the areaCalculator factory function should only sum the areas of provided shapes, it should not care whether the user wants JSON or HTML.

So, to fix this you can create an SumCalculatorOutputter factory function and use this to handle whatever logic you need on how the sum areas of all provided shapes are displayed.

The sumCalculatorOutputter factory function would work liked this:

const shapes = [
  circle(2),
  square(5),
  square(6)
]
const areas  = areaCalculator(shapes)
const output = sumCalculatorOputter(areas)
console.log(output.JSON())
console.log(output.HAML())
console.log(output.HTML())
console.log(output.JADE())

Now, whatever logic you need to output the data to the users is now handled by the sumCalculatorOutputter factory function.


2. Open-Closed Principle

“Objects or entities should be open for extension, but closed for modification.”

Open for extension means that we should be able to add new features or components to the application without breaking existing code. Closed for modification means that we should not introduce breaking changes to existing functionality, because that would force you to refactor a lot of existing code — Eric Elliott”

In simpler words, means that a class or factory function in our case, should be easily extendable without modifying the class or function itself. Let’s look at the areaCalculator factory function, especially it’s sum method.

sum () {
 
 const area = []
 
 for (shape of this.shapes) {
  
  if (shape.type === 'Square') {
     area.push(Math.pow(shape.length, 2)
   } else if (shape.type === 'Circle') {
     area.push(Math.PI * Math.pow(shape.length, 2)
   }
 }
 return area.reduce((v, c) => c += v, 0)
}

If we wanted the sum method to be able to sum the areas of more shapes, we would have to add more if/else blocks and that goes against the open-closed principle.

A way we can make this sum method better is to remove the logic to calculate the area of each shape out of the sum method and attach it to the shape’s factory functions.

const square = (length) => {
  const proto = {
    type: 'Square',
    area () {
      return Math.pow(this.length, 2)
    }
  }
  return Object.assign(Object.create(proto), {length})
}

The same thing should be done for the circle factory function, an area method should be added. Now, to calculate the sum of any shape provided should be as simple as:

sum() {
 const area = []
 for (shape of this.shapes) {
   area.push(shape.area())
 }
 return area.reduce((v, c) => c += v, 0)
}

Now we can create another shape class and pass it in when calculating the sum without breaking our code. However, now another problem arises, how do we know that the object passed into the areaCalculator is actually a shape or if the shape has a method named area ?

Coding to an interface is an integral part of S.O.L.I.D., a quick example is we create an interface, that every shape implements.

Since JavaScript doesn’t have interfaces, So how can we achieved this, in the lack of interfaces ?

Function Composition to the rescue !

First we create shapeInterface factory function, as we are talking about interfaces, our shapeInterface will be as abstracted as an interface, using function composition.

const shapeInterface = (state) => ({
  type: 'shapeInterface',
  area: () => state.area(state)
})

Then we implement it to our square factory function.

const square = (length) => {
  const proto = {
    length,
    type : 'Square',
    area : (args) => Math.pow(args.length, 2)
  }
  const basics = shapeInterface(proto)
  const composite = Object.assign({}, basics)
  return Object.assign(Object.create(composite), {length})
}

And the result of calling the square factory function will be the next one:

const s = square(5)
console.log('OBJ\n', s)
console.log('PROTO\n', Object.getPrototypeOf(s))
s.area()

// output
OBJ
 { length: 5 }
PROTO
 { type: 'shapeInterface', area: [Function: area] }
25

In our areaCalculator sum method we can check if the shapes provided are actually types of shapeInterface, otherwise we throw an exception:

sum() {
  const area = []
  for (shape of this.shapes) {
    if (Object.getPrototypeOf(shape).type === 'shapeInterface') {
       area.push(shape.area())
     } else {
       throw new Error('this is not a shapeInterface object')
     }
   }
   return area.reduce((v, c) => c += v, 0)
}

and again, since JavaScript doesn’t have support for interfaces like typed languages the example above demonstrates how we can simulate it, but more than simulating interfaces, what we are doing is using closures and function composition.


3. Liskov Substitution Principle

“Let q(x) be a property provable about objects of x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T.”

All this is stating is that every subclass/derived class should be substitutable for their base/parent class.

In other words, as simple as that, a subclass should override the parent class methods in a way that does not break functionality from a client’s point of view.

Still making use of our areaCalculator factory function, say we have a volumeCalculator factory function that extends the areaCalculator factory function, and in our case for extending an object without breaking changes in ES6 we do it by using Object.assign() and the Object.getPrototypeOf():

const volumeCalculator = (s) => {
  const proto = {
    type: 'volumeCalculator'
  }
  const areaCalProto = Object.getPrototypeOf(areaCalculator())
  const inherit = Object.assign({}, areaCalProto, proto)
  return Object.assign(Object.create(inherit), {shapes: s})
}

For Another example, if we want to implement classes for a bunch of shapes, we can have a parent Shape class, which are extended by all classes by implementing everything in the Shape class.

We can write the following to implement some shape classes and get the area of each instance:

class Shape {
  get area() {
    return 0;
  }
}
class Rectangle extends Shape {
  constructor(length, width) {
    super();
    this.length = length;
    this.width = width;
  }
  get area() {
    return this.length * this.width;
  }
}
class Square extends Shape {
  constructor(length) {
    super();
    this.length = length;
  }
  get area() {
    return this.length ** 2;
  }
}
class Circle extends Shape {
  constructor(radius) {
    super();
    this.radius = radius;
  }
  get area() {
    return Math.PI * (this.radius ** 2);
  }
}
const shapes = [
  new Rectangle(1, 2),
  new Square(1, 2),
  new Circle(2),
]
for (let s of shapes) {
  console.log(s.area);
}

Since we override the area getter in each class that extends Shape , we get the right area for each shape since the correct code is run for each shape to get the area.


4. Interface Segregation Principle

“A client should never be forced to implement an interface that it doesn’t use or clients shouldn’t be forced to depend on methods they do not use.”

Continuing with our shapes example, we know that we also have solid shapes, so since we would also want to calculate the volume of the shape, we can add another contract to the shapeInterface:

const shapeInterface = (state) => ({
  type: 'shapeInterface',
  area: () => state.area(state),
  volume: () => state.volume(state)
})

Any shape we create must implement the volume method, but we know that squares are flat shapes and that they do not have volumes, so this interface would force the square factory function to implement a method that it has no use of. 

Interface segregation principle says no to this, instead we could create another interface called solidShapeInterface that has the volume contract and solid shapes like cubes etc. can implement this interface.

const shapeInterface = (state) => ({
  type: 'shapeInterface',
  area: () => state.area(state)
})
const solidShapeInterface = (state) => ({
  type: 'solidShapeInterface',
  volume: () => state.volume(state)
})
const cubo = (length) => {
  const proto = {
    length,
    type   : 'Cubo',
    area   : (args) => Math.pow(args.length, 2),
    volume : (args) => Math.pow(args.length, 3)
  }
  const basics  = shapeInterface(proto)
  const complex = solidShapeInterface(proto)
  const composite = Object.assign({}, basics, complex)
  return Object.assign(Object.create(composite), {length})

This is a much better approach, but a pitfall to watch out for is when to calculate the sum for the shape, instead of using the shapeInterface or a solidShapeInterface.

We can create another interface, maybe manageShapeInterface, and implement it on both the flat and solid shapes, this is way we can easily see that it has a single API for managing the shapes, for example:

const manageShapeInterface = (fn) => ({
  type: 'manageShapeInterface',
  calculate: () => fn()
})
const circle = (radius) => {
  const proto = {
    radius,
    type: 'Circle',
    area: (args) => Math.PI * Math.pow(args.radius, 2)
  }
  const basics = shapeInterface(proto)
  const abstraccion = manageShapeInterface(() => basics.area())
  const composite = Object.assign({}, basics, abstraccion)
  return Object.assign(Object.create(composite), {radius})
}
const cubo = (length) => {
  const proto = {
    length,
    type   : 'Cubo',
    area   : (args) => Math.pow(args.length, 2),
    volume : (args) => Math.pow(args.length, 3)
  }
  const basics  = shapeInterface(proto)
  const complex = solidShapeInterface(proto)
  const abstraccion = manageShapeInterface(
    () => basics.area() + complex.volume()
  )
  const composite = Object.assign({}, basics, abstraccion)
  return Object.assign(Object.create(composite), {length})
}

As we can see until now, what we have been doing for interfaces in JavaScript are factory functions for function composition.

And here, with manageShapeInterface what we are doing is abstracting again the calculate function, what we doing here and in the other interfaces (if we can call it interfaces), we are using “high order functions” to achieve the abstractions.


5. Dependency Inversion Principle

“Entities must depend on abstractions not on concretions. It states that the high level module must not depend on the low level module, but they should depend on abstractions.”

As a dynamic language, JavaScript doesn’t require the use of abstractions to facilitate decoupling. Therefore, the stipulation that abstractions shouldn’t depend upon details isn’t particularly relevant to JavaScript applications. The stipulation that high level modules shouldn’t depend upon low level modules is, however, relevant.

From a functional point of view, these containers and injection concepts can be solved with a simple higher order function, or hole-in-the-middle type pattern which are built right into the language.”

This principle allows for decoupling. And we have made it before, let’s review our code with the manageShapeInterface and how we accomplish the calculate method.

const manageShapeInterface = (fn) => ({
  type: 'manageShapeInterface',
  calculate: () => fn()
})

What the manageShapeInterface factory function receives as the argument is a higher order function, that decouples for every shape the functionality to accomplish the needed logic to get to final calculation, let see how this is done in the shapes objects.

const square = (radius) => {
  // code
 
  const abstraccion = manageShapeInterface(() => basics.area())
 
 // more code ...
}
const cubo = (length) => {
  // code 
  const abstraccion = manageShapeInterface(
    () => basics.area() + complex.volume()
  )
  // more code ...
}

For the square what we need to calculate is just getting the area of the shape, and what we need is summing the area with the volume and that is everything need to avoid the coupling and get the abstraction.

For Another example, we analyse that the Http Request depends on the setState function, which is a detail. These code violates the Dependency Inversion principle.

http.get("http://address/api/examples", (res) => {
 this.setState({
  key1: res.value1,
  key2: res.value2,
  key3: res.value3
 });
});

The correct code is :

//Http request
const httpRequest = (url, setState) => {
 http.get(url, (res) => setState.setValues(res))
};

//State set in another function
const setState = {
 setValues: (res) => {
  this.setState({
    key1: res.value1,
    key2: res.value2,
    key3: res.value3
  })
 }
}

//Http request, state set in a different function
httpRequest("http://address/api/examples", setState);

That’s all about in this article.


Conclusion

In this article, We understood about the Javascript 5 SOLID Principles. The main goal of the SOLID principles is that any software should tolerate change and should be easy to understand. We conclude that SOLID is very useful for write code :

  • Easy to understand
  • Where things are where they’re supposed to be
  • Where classes do what they were intended to do
  • That can be easily adjusted and extended without bugs
  • That separates the abstraction from the implementation
  • That allows to easily swap implementation (Db, Api, frameworks, …)
  • Easily testable

Thanks for reading !! I hope you enjoyed and learned about SOLID Principles Concept in javascript. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

Exit mobile version