JavaScript – How Are Javascript Equality Operators Useful For Comparison ?

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about how are Javascript Equality Operators useful for Comparison. Comparing any two values for equality/inequality is one of the basic functionalities provided by any programming language. Each programming language provides some operators to compare all kinds of operands. JavaScript also inherits and extends the same concept. It provides two variants of operators for comparing whether two operands are equal. This article will show the following Javascript Equality Operators for Comparison with the example as below:

  • Equality (==) Operator
  • Strict Equality (===) Operator
  • InEquality (! =) Operator
  • Strict InEquality (! ==) Operator

A famous quote about learning is :

” We now accept the fact that learning is a lifelong process of keeping abreast of change. And the most pressing task is to teach people how to learn. “

So Let’s begin.


1. Equality (==) Operator

In Javascript, the ‘==’ operator is also a loose equality operator that mainly compares two values on both sides, and then return true or false.

Syntax:

operand1 == operand2

It is type coercionwhich means that the two values are compared only after attempting to convert them into the same type. If there is a type mismatch between the operands, it first converts the operands to the same type if they are not of the same type, then applies strict comparison. If both operands are objects, in this case,  JavaScript carries out a comparison of internal references, which are equal when operands refer to the same object in memory.


Equality (==) Operator–Example 1

let var1 = 5;let var2 = 5;document.write(var1 == var2);//Output will be true

In the above example, we have taken variables that are of both number type. When we compare them using the “==” operator, JavaScript will just compare the values directly and will not do any type of conversion.


Equality (==) Operator–Example 2

let var1 = 5;let var2 = '5';document.write(var1 == var2);//Output will be true

In the above example, var1 is of number type, and var2 is of string type. Before comparing both the variables, JavaScript will first convert the types of variables, so both the variables have the same type. In this example, it will convert the string variable to a number and then will make the comparison of both the numbers. So, ideally, it just compares the values of the variables and not the data type of the variable.


2. Strict Equality (===) Operator

In Javascript, the ‘===’ operator is also a triple equals or strict equality or identity operator.

Syntax:

operand1 === operand2

The result of the identity operator is true if the operands are strictly equal with no type-conversion. During this comparison, the compiler doesn’t convert the value implicitly; instead of this, it will compare both the value and data type of the operands.


Strict Equality (===) Operator–Example 1

let var1 = 5;let var2 = 5;document.write(var1 === var2);//Output will be true

In the above example, we have taken variables, both variable “var1″ and var2” of number types. Here, as both the values of variables and their data type are the same, JavaScript will return the result of comparison true.


Strict Equality (===) Operator–Example 2

let var1 = 5;let var2 = '5';document.write(var1 === var2);//Output will be false

In the above example, we have taken var1 is of number type, and var2 is of string type. Here, === operator is not only checking the value but also the data type, and as the data type of both the variables is not the same, the output will be false.


3. InEquality (! =) Operator

In Javascript, the ‘! =’ operator is known as a loose inequality operator, which mainly compares two values on both sides and then returns true if the values are not equal and false if the values are equal.

Syntax:

operand1 != operand2

Similar to the Equality operator, this operator also converts the type of both the operands if needed. If there is a type mismatch between the operands, it first converts the operands to the same type and then applies comparison.


InEquality (! =) Operator–Example 1

let var1 = 5;let var2 = 3;document.write(var1 != var2);//Output will be true

In the above case, we have taken variables, both of which are of number type. When we compare them using the “! =” operator, JavaScript will just compare the operands based on their values. In this scenario, no type-conversion happens, as both the operands are of the same type.


InEquality (!=) Operator–Example 2

let var1 = 5;let var2 = '5';document.write(var1 != var2);//Output will be false

In the above example, var1 is of number type, and var2 is of string type. Before comparing both the variables, JavaScript will first convert the data type of variables, so that both the variables have the same data type. In this example, it will convert the string variable to the number and then will make the comparison of both the numbers. So, ideally, it just compares the values of the variables and not the data type of the variable. As the value of both the variables is 5, so the “! =” operator will return result as false.


4. Strict InEquality (! ==) Operator

In Javascript, the ‘!==’ operator is known as a not double equals or strict inequality operator. If the operands are strictly unequal with no type-conversion then the identity operator results true. During this comparison, the compiler doesn’t convert the data type of operands implicitly. Instead of this, it will compare both the values as well as the data type of operands.

Syntax:

operand1 !== operand2


Strict InEquality (! ==) Operator – Example 1

let var1 = 5;let var2 = 5;document.write(var1 !== var2);//Output will be false

In the above example, we have taken variables, both variable “var1″ and var2” of number types. Here, as both the values of variables and their data type are the same, JavaScript will return, the result of the comparison is false.


Strict InEquality (! ==) Operator–Example 2

let var1 = 5;let var2 = '5';document.write(var1 !== var2);//Output will be true

In the above example, we have taken var1 is of number type, and var2 is of string type. Here, ! == operator is not only checking the value but also the data type, and as the data type of both the variables is not the same, the output will be true.

That’s all about in this article.


Conclusion

In this article, we understood about how are Javascript Equality Operators useful for Comparison. We conclude that :

  • The Equality (==) and InEquality (! =) Operators compares the operands only based on their values and ignores the data types of the operands.
  • The Strict Equality (===) and Strict InEquality (! ==) Operators compare the operands based on both values as well as data types of the operands.

Thanks for reading !! I hope you enjoyed and learned about Equality Operators 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 support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow other useful website as below links :

The Modern JavaScript Tutorial

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 Promises In JavaScript

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about promises in javascript. A promise in real life is just an assurance about ‘something.’ So what happens when somebody makes a promise to us? They give us a guarantee based on which we can plan something. Now, the promise can either be kept or broken. So, when we keep a promise, we expect something out of that promise. We can make use of the output of a promise for our further actions or plans. But, when a promise breaks, we would like to know why the person who made the promise was not able to keep up his side of the bargain. JavaScript provides a kind of similar concept of “Promises” for handling the asynchronous calls.

In this article, we will discuss the below items to understand the concepts of promises in JavaScript:

  • What are Promises in JavaScript?
  • When to use Promises in JavaScript?
  • How Promises works in JavaScript?
  • Create a Promise in JavaScript
  • How to consume a Promise in JavaScript?

A famous quote about learning is :

” I am always ready to learn although I do not always like being taught. “

So Let’s begin.


What are Promises in JavaScript?

Promise in JavaScript is an object that holds the future value of an asynchronous operation.

For example, if we are requesting some data from a server, the promise promises us to get that data that we can use in the future.

A promise object can have the following states:

  • Pending: it is an initial state, where the result is not ready, and it is waiting for the asynchronous operation to get finished.
  • Resolved/Fulfilled: it means that performed action completed successfully. i.e., Function returned promised value.
  • Rejected: it means that performed action failed or an error occurred. i.e., function did not return the promised value.


When to use Promises in JavaScript?

Now let’s understand what was the need for the promise in JavaScript, as the async operations would have handled using the callbacks itself. Callback function is used to handle asynchronous execution. A callback function indicates the operation which JavaScript should execute once an asynchronous operation finishes.

Here is the simplest example of a callback function as below:

<html>

	<body> Demonstrating callback in javascript:</br>
    	<script type="text/javascript">
    		function i_take_1_sec() {
                return setTimeout(() => {
                    document.write('I was no: 2 and I take 1 second</br>')
                }, 1000);
            }
            function i_take_10_sec(callback) {
                return setTimeout(() => {
                    document.write('I was no: 1 and I take 10 seconds</br>')
                    callback()
                }, 10000);
            }
            function run (){
                i_take_10_sec(i_take_1_sec);
            }
            run();
        </script>
    </body>

</html>

The output of the above callback function example is :


How Promises works in JavaScript?

To understand how exactly promises works, let us take the example, Consider we are making a promise to our mother saying that we are going to clean up our room by the end of the day. So two possible things can happen either we will be going to clean the room, or we are going not to clean the room and break our promise. Let’s write that promise in the JavaScript.

let promiseCleanRoom = new Promise(function(resolve,reject){
    cleanRoom = true;
    if(cleanRoom){
      resolve('Cleaned the Room');
    }else{
      reject('Broke the promise');
    }
});

The above code block shows how to create the promise. i.e., when this promise executes, then it will give either resolve status or reject status based on the cleanRoom value.

We can call or use the above-created promise as:

 promiseCleanRoom.then((result)=>{
      console.log(result)
  })

In the above snippet, it shows how to utilize the created promise, and there is “.then,” a method that will perform some of the action only when a given promise is fulfilled or resolved. In this case, it will print the result sent by promise when it resolves, i.e., Cleaned the Room.

There is one more case that will happen if the promise got broken or some error occurred in that case. Then we can use the “.catch ” block that will allow handling the broken or instances of error.

promiseCleanRoom.then((result)=>{
      console.log(result)
}).catch((result)=>{
   console.log(result) //will execute if promise is rejected or errored out
})

Suppose, if the promise breaks, then it will execute the catch block by skipping the then block, and output will be “Broke the promise”.


Create a Promise in JavaScript

As we discussed above, A Promise in JavaScript is an object representing the eventual completion or failure of an asynchronous operation. Its syntax looks like below:

const promise = new Promise(function(resolve,reject){

     //do something

});

Here we create a new promise using the Promise constructor, which takes a single argument, a callback function, also known as executor function, which in turn takes two callbacks functions, resolve, and reject

The executor function immediately executes when a promise creates. The promise resolves by calling the resolve() method and is rejected by calling the reject() method.

Let’s try to understand the usage and working of Promise in JavaScript with the help of following code snippet.

<html>

<body> Demonstrating promise in javascript:</br>
    <script type="text/javascript">

    	function i_take_10_sec()
    	{
    	 	return new Promise((resolve, reject)=>{
    	 	 	setTimeout(() => { 
    	 			resolve('I was no: 1 and I take 10 seconds');
    	 		}, 10000);
			})
    	}

    	function i_take_1_sec()
    	{ 
    		return new Promise((resolve, reject)=>{
    			setTimeout(() => { 
    				resolve('I was no: 2 and I take 1 second');
    			}, 1000);
    		}) 
    	}

    	function i_take_5_sec(callback) 
    	{ 
    		return new Promise((resolve, reject)=>{
    		 	setTimeout(() => { 
    				resolve('I was no: 3 and I take 5 second')
    			}, 5000); 
    		})
    	}

    	function i_take_7_sec(callback) 
    	{ 
    		return new Promise((resolve, reject)=>{
    			setTimeout(() => { 
    				resolve('I was no: 4 and I take 7 second')
    			}, 7000);
    		}) 
    	}

    
    	function run()
    	{
    		i_take_10_sec()
    		.then((result) => {
            console.log(result);
        		return i_take_1_sec()
   		})
    		.then((result) => {
            console.log(result);
        		return i_take_5_sec()
    		})
    		.then((result) => {
            console.log(result);
        		return i_take_7_sec()
    		})
    		.then((result)=>{
            console.log(result);
          })
    	}

    	run();

    </script>
</body>

</html>

The Developer Tools output of the above example code snippet is :

As seen in the above example, each of the functions returns a promise that chains to the next using “.then().” The code flow appears much prettier and understandable in this case.

Now consider a scenario that one of the promises rejects. So, in that scenario, it will raise an error and will not invoke the other chained function calls.

<html>

<body> Demonstrating promise in javascript:</br>
    <script type="text/javascript">

    	function i_take_10_sec()
    	{
    	 	return new Promise((resolve, reject)=>{
    	 	 	setTimeout(() => { 
    	 			resolve('I was no: 1 and I take 10 seconds');
    	 		}, 10000);
			})
    	}

    	function i_take_1_sec()
    	{ 
    		return new Promise((resolve, reject)=>{
    			setTimeout(() => { 
    				resolve('I was no: 2 and I take 1 second');
    			}, 1000);
    		}) 
    	}

    	function i_take_5_sec(callback) 
    	{ 
    		return new Promise((resolve, reject)=>{
    		 	setTimeout(() => { 
    				reject('I was no: 3 and I take 5 second')
    			}, 5000); 
    		})
    	}

    	function i_take_7_sec(callback) 
    	{ 
    		return new Promise((resolve, reject)=>{
    			setTimeout(() => { 
    				resolve('I was no: 4 and I take 7 second')
    			}, 7000);
    		}) 
    	}

    
    	function run()
    	{
    		i_take_10_sec()
    		.then((result) => {
            console.log(result);
        		return i_take_1_sec()
   		})
    		.then((result) => {
            console.log(result);
        		return i_take_5_sec()
    		})
    		.then((result) => {
            console.log(result);
        		return i_take_7_sec()
    		})
    		.then((result)=>{
            console.log(result);
          })
    	}

    	run();

    </script>
</body>

</html>

The Developer Tools output of the above example code snippet is :

As we can see from the above screenshot that JavaScript raised an “Uncaught” error after invoking the method “i_take_5_sec,” and no further code statements execute. So, this confirms that, once the promise is “rejected,” it will lead to failure of all the further chained commands.


How to consume a promise in JavaScript?

Promises consume by registering functions using .then, .catch, and .finally methods. A Promise object serves as a link between the executor and the consuming functions, which will receive the result or error, and the consuming functions can use any of the .then, .catch, or .finally methods. Let’s see the usage of all these methods in the below sections:


How to use .then() as a consumer function?

The .then() method invokes when a promise is either resolved or rejected. Its syntax looks like below:

.then(function(result){
        //statements when the promise is resolved successfully
    }, function(error){
        //statements when the prmise was rejected or raised an error
    })

We can understand the primary usage of the “.then()” method with the help of the following figure:

Let comprehend in this way, assume an if-else statement where code in if block will execute when the given condition is true; otherwise, it will execute the else block. Similarly, the “then” method will take two functions as parameters where the first function will run when a promise resolves successfully, or it will execute the second method when a promise rejects or raise an error.

Let’s understand the usage and implementation of the “.then() consumer method,” by modifying the above-written program as follows:

<html>

<body> Demonstrating promise consumer using .then()  method in javascript:</br>
    <script type="text/javascript">

    	function i_take_10_sec()
    	{
    	 	return new Promise((resolve, reject)=>{
    	 	 	setTimeout(() => { 
    	 			resolve('I was no: 1 and I take 10 seconds');
    	 		}, 10000);
			})
    	}

    	function i_take_5_sec(callback) 
    	{ 
    		return new Promise((resolve, reject)=>{
    		 	setTimeout(() => { 
    				reject('I was no: 3 and I take 5 second')
    			}, 5000); 
    		})
    	}
    
    	function run()
    	{
    		i_take_10_sec()
    		.then((result) => {
                        console.log(result);
        		return i_take_5_sec()
   		})
    		.then((result)=>{
                   console.log(result);
                 },()=>{
                    console.log('Error Raised')
                 })
    	}

    	run();

    </script>
</body>

</html>

The Developer Tools output of the above example code snippet is :

We can see from the above screenshot that, as the “i_take_5_sec()” method resulted in the promise to be rejected, so the call flow in the run method invoked the second function, instead of the first function. So, in this way, a user can control the flow of program execution using the “.then()” method depending on the expected outputs of the promise.

But passing two functions as parameters for then method looked somewhat confusing. Therefore, to overcome this, the “.catch” block or function was introduced where the catch block will explicitly handle when there is rejection, or some error has occurred.


How to use .catch() as a consumer function?

The .catch() method invokes when a promise rejects, or some error occurs in the execution. Its syntax looks like below:

Syntax:

.catch(function(error){
        //Statements to handle error raised
    })

The basic usage of the “.catch()” method can be understood with the help of the following figure:

As is evident from the above image, in case of .catch() method specified, it will invoke the “.catch” block when the promise gets rejected.

Lets understand the usage and implementation of the “.catch() consumer method,” by modifying the above-written program as follows:

<html>

<body> Demonstrating promise consumer using .catch() method in javascript:</br>
    <script type="text/javascript">

    	function i_take_10_sec()
    	{
    	 	return new Promise((resolve, reject)=>{
    	 	 	setTimeout(() => { 
    	 			resolve('I was no: 1 and I take 10 seconds');
    	 		}, 10000);
			})
    	}

    	function i_take_5_sec(callback) 
    	{ 
    		return new Promise((resolve, reject)=>{
    		 	setTimeout(() => { 
    				reject('I was no: 3 and I take 5 second')
    			}, 5000); 
    		})
    	}
    
    	function run()
    	{
    		i_take_10_sec()
    		.then((result) => {
                        console.log(result);
        		return i_take_5_sec()
   		})
    		.then((result)=>{
                    console.log(result);
                }).catch(()=>{
                   console.log('Error Raised')
               })
    	}

    	run();

    </script>
</body>

</html>

The Developer Tools output of the above example code snippet is :

We can see from the above screenshot that, as the “i_take_5_sec()” method resulted in the promise to be rejected, so the call flow raised the exception, which happened in the .catch() block. Also, as the exception occurred properly, it didn’t block the call flow and still executed the next part in the .then() part resulting from the printing of “Done.”  It makes it clear that using the .catch() block ensures that the further chained calls will still execute, even though one of the intermediate calls resulted in an error or exception.


How to use .finally() as a consumer function?

As we used to have the finally block in a regular try{…} catch{…} of exception handling, there’s finally in promises also. This consumer function always executes when the promise settles: be it resolve or reject. The finally block a good handler for performing cleanup actions, which we always expect to execute. Its syntax looks like below:

.finally(() => {
 // Statements which are expected to be executed always
})

The basic usage of the “.catch()” method can be understood with the help of the following figure:

As we can see from the above picture, the “finally” block will always execute, no matter whether the promise has been resolved or rejected.

Let’s understand the usage and implementation of the “.finally() consumer method,” by modifying the above-written program as follows:

<html>

<body> Demonstrating promise consumer using .finally() method in javascript:</br>
    <script type="text/javascript">

    	function i_take_10_sec()
    	{
    	 	return new Promise((resolve, reject)=>{
    	 	 	setTimeout(() => { 
    	 			resolve('I was no: 1 and I take 10 seconds');
    	 		}, 10000);
			})
    	}

    	function i_take_5_sec(callback) 
    	{ 
    		return new Promise((resolve, reject)=>{
    		 	setTimeout(() => { 
    				reject('I was no: 3 and I take 5 second')
    			}, 5000); 
    		})
    	}
    
    	function run()
    	{
    		i_take_10_sec()
    		.then((result) => {
            console.log(result);
        		return i_take_5_sec()
   		})
    		.then((result)=>{
            console.log(result);
          }).catch(()=>{
             console.log('Error Raised')
          }).finally(()=>{
             console.log('Completed Execution')
          })
    	}

    	run();

    </script>
</body>

</html>

The Developer Tools output of the above example code snippet is :

We can see from the above screenshot that, as the “i_take_5_sec()” method resulted in the promise to be rejected, due to which the exception raised and the next .then() method of the “Done” block was not executed. But still, we can see from the output that the finally() block executed. So, it makes it clear that, whether the promise returns a resolved, rejected or and error state, the “finally()” block will always be executed.


How to use Promise.all() as a consumer function?

If we want to execute multiple promises in parallel and want to wait for the completion of all the promises before proceeding further, we can use the “.all” function provided by the Promises in JavaScript. It takes an array of promises function and executes all functions simultaneously / parallelly and wait until all promises are either resolve or reject. Its syntax looks like below:

Promise.all([array of promises]);

Let’s understand the usage of “Promise.all” with the help of the following example:

<html>

<body> Demonstrating promise all() method in javascript:</br>
    <script type="text/javascript">

    	function i_take_10_sec()
    	{
    	 	return new Promise((resolve, reject)=>{
    	 	 	setTimeout(() => { 
               console.log('I was no: 1 and I take 10 second')
    	 			resolve('I was no: 1 and I take 10 seconds');
    	 		}, 10000);
			})
    	}

    	function i_take_5_sec(callback) 
    	{ 
    		return new Promise((resolve, reject)=>{
    		 	setTimeout(() => { 
               console.log('I was no: 2 and I take 5 second')
    				resolve('I was no: 2 and I take 5 second')
    			}, 5000); 
    		})
    	}

      function i_take_7_sec(callback) 
    	{ 
    		return new Promise((resolve, reject)=>{
    		 	setTimeout(() => { 
               console.log('I was no: 3 and I take 7 second')
    				resolve('I was no: 3 and I take 7 second')
    			}, 7000); 
    		})
    	}
    
    	function run()
    	{
    		Promise.all([i_take_10_sec(),i_take_5_sec(),i_take_7_sec()]).then(()=>{
             console.log("All finished");
          })
    	}

    	run();
    </script>
</body>

</html>

The Developer Tools output of the above example code snippet is :

As we can see that all the promises are executing simultaneously and will wait until all promises either resolve or reject.

we aware that Promise.all() doesn’t ensure any ordering of promises. It just executes all of the promises in parallel.


How to use Promise.race() as a consumer function?

If we want to execute multiple promises in parallel but don’t want to wait for the completion of all the promises before proceeding further, we can use the “.race” function provided by the Promises in JavaScript. It just waits for completion of any one promise, which returns first. It will take an array of promises function and execute all functions simultaneously and wait until any one of the promises is either resolve or reject. Its syntax looks like below:

Promise.race([array of promises])

Let’s understand the usage of “Promise.race” with the help of the following example:

<html>

<body> Demonstrating promise race() method in javascript:</br>
    <script type="text/javascript">

    	function i_take_10_sec()
    	{
    	 	return new Promise((resolve, reject)=>{
    	 	 	setTimeout(() => { 
               console.log('I was no: 1 and I take 10 second')
    	 			resolve('I was no: 1 and I take 10 seconds');
    	 		}, 10000);
			})
    	}

    	function i_take_5_sec(callback) 
    	{ 
    		return new Promise((resolve, reject)=>{
    		 	setTimeout(() => { 
               console.log('I was no: 2 and I take 5 second')
    				resolve('I was no: 2 and I take 5 second')
    			}, 5000); 
    		})
    	}

      function i_take_7_sec(callback) 
    	{ 
    		return new Promise((resolve, reject)=>{
    		 	setTimeout(() => { 
               console.log('I was no: 3 and I take 7 second')
    				resolve('I was no: 3 and I take 7 second')
    			}, 7000); 
    		})
    	}
    
    	function run()
    	{
    		Promise.race([i_take_10_sec(),i_take_5_sec(),i_take_7_sec()]).then(()=>{
             console.log("All finished");
          })
    	}

    	run();
    </script>
</body>

</html>

The Developer Tools output of the above example code snippet is :

In the above example, we can see that as soon as one promise(i_take_5 sec) resolves, it exits from then function.

That’s all about in this article.


Conclusion

In this article, We understood about Promises in JavaScript. We conclude that :

  • Promises can handle the asynchronous calls in JavaScript.
  • A promise will be “pending” when executed and will result in “resolved” or “rejected,” depending on the response of the asynchronous call.
  • Promises avoid the problem of “callback hell,” which happens due to nested callback functions.

Thanks for reading !! I hope you enjoyed and learned about Promises 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 !!???

JavaScript – How To Pass Arbitrary Parameters To A Function In JavaScript ?

Hello Readers, CoolMonkTechie heartily welcomes you in this article (How To Pass Arbitrary Parameters To A Function In JavaScript ?).

In this article, we will learn how to pass arbitrary parameters to a function using Rest Parameters and Spread Operator in JavaScript. All the programming languages provide different ways to pass an arbitrary, indefinite number of parameters to a function. Javascript has also provided concepts that make the “passing of arbitrary parameters” to a function very easy. We will also understand how to handle the arbitrary parameters using the “Rest parameter” in JavaScript.

In this article, we will discuss the below items to understand the concepts of handling the arbitrary parameters:

  • Handle arbitrary parameters using the “arguments” variable in JavaScript
  • Handle the arbitrary parameters using the “rest parameter” in JavaScript
  • Expand iterable objects using the “spread operator” in JavaScript

A famous quote about learning is :

” There is no end to education. It is not that you read a book, pass an examination, and finish with education. The whole of life, from the moment you are born to the moment you die, is a process of learning.”

So Let’s begin.


Handle arbitrary parameters using the “arguments” variable in JavaScript

Arguments are a special type of in-built variable available in JavaScript, which can handle an arbitrary number of parameters in a function. Consider a scenario where the function definition doesn’t accept any parameters, but at run time, the caller wants to pass some parameters. Such kind of parameters can be accessed in the function definition using the arguments variable. One can access the arguments with the help of the index of the arguments variable.

Let’s understand the usage of “arguments” with the help of the following example:

<html>
 
   <body>  
 
      Demonstrating arguments keyword in javascript </br> </br>
 
      <script type='text/javascript'>
 
        function display(){
 			document.write(arguments[0] + " " + arguments[1]);
 		}
 
        display("Blog","Coolmonktechie");
 
      </script>   
 
   </body>
 
</html>

In the above example, We can see that the display method doesn’t have any parameters. Still, while calling, we are sending two parameters, and we can access it by using the arguments variable with the help of the index.

Even though the “arguments” variable is both array-like and iterable, it’s not an array. Additionally, it does not support array methods, so we can’t call arguments.map(...) for example.


Handle arbitrary parameters using the “rest parameter” in JavaScript

The “rest parameter” is the advanced way provided by JavaScript to handle the arbitrary number of parameters. Its syntax looks like below:

function functionName(...args){

//Statements need to get executed

}

Let’s try to understand the details and usage of the rest parameter with the help of the following example:

Consider a case where we need to perform a multiplication operation; the function will look like:

function multiply(variable1, variable2){

    return variable1*variable2;

}

Now, the above code perfectly works when there are only 2 arguments, But imagine there is a situation where we need to multiply n number of variables, and n can be different for each time one invokes the function. In this case, the number of arguments entirely depends on the caller.

To achieve this, we can use the rest parameter, as shown below:

Example: when the function just accepts the “rest” parameter

<html>

   <body>  

      Demonstrating rest operator in javascript

   </br>

   </br>

      <script type='text/javascript'>

        function multiply(...variables){

           var output =1;

           for(x of variables){

               output*=x;

           }

           return output;

        }

        document.write("Multiplication of 2 variables 3 and 5 is "+multiply(3,5));

        document.write("</br>");

        document.write("Multiplication of 3 variables 3,2 and 5 is "+multiply(3,2,5));

        document.write("</br>");

        document.write("Multiplication of 0 variables is "+multiply());

      </script>   

   </body>

</html>

In the above example, we can see that there is only one multiply function, but it can take n number of variables, and the caller will decide these variables. The “rest” parameter is being specified by the “...variables” in the multiply method, and it can accept zero or more parameters.

The “rest” parameter can be combined with other parameters of the function as well, but it will always be the last parameter of the function. Let’s understand the same with the help of the following example:

Example: when the function accepts named parameters with the rest parameter

Let’s consider an example that takes two mandatory parameters, and the last variable is a “rest” parameter. The following code snippet shows the usage of the “rest” parameter as the last parameter of the function:

<html>

   <body>  

      Demonstrating rest operator in javascript

   </br>

   </br>

      <script type='text/javascript'>

        function multiply(var1,var2,...variables){

           document.write(var1 +" "+var2);

           document.write("</br>");

           var output =1;

           for(x of variables){

               output*=x;

           }

           return output;

        }

        document.write("Multiplication of 2 variables 3 and 5 is "+multiply("Blog","Testing",3,5));

        document.write("</br>");

        document.write("Multiplication of 3 variables 3,2 and 5 is "+multiply("Java","Script",3,2,5));

        document.write("</br>");

        document.write("Multiplication of 0 variables is "+multiply("Blog","Output"));

      </script>   

   </body>

</html>

As we can see in the above code snippet, the multiple functions are accepting var1 and var2 as mandatory parameters, and the last parameter “…variables” is the “rest” parameter. The user can invoke the function by passing the two necessary parameters and the rest parameters as any arbitrary number of parameters.


Expand iterable objects using the “spread operator” in JavaScript

Till now, we have seen how to get an array from the list of parameters. But sometimes we need to do precisely the reverse.

For example, the built-in function Math.max that returns the greatest number from a list:

Math.max(3, 5, 1) // Returns 5

Now let’s say we have an array [3,5,1]. How do we call “Math.max” with it? Passing it “as is” won’t work, because “Math.max” expects a list of numeric arguments and not a single array object:

let arr = [3, 5, 1];

Math.max(arr); // NaN

And surely we can’t manually list items in the code Math.max(arr[0], arr[1], arr[2]), because we may be unsure how many parameters are there. When the function invokes, there could be a lot, or there could be no parameters.

The spread syntax can handle such a scenario. It appears similar to rest parameters, also uses “” but does quite the opposite. When “…arr” is used in the function call, it “expands” an iterable object “arr” into the list of arguments. Its syntax looks like below:

Syntax:

var array=[va1,val2,val3…,valN];

callingFunction(...array); //...variablename convert array to list of arguments

For “Math.max” it will look like:

let arr = [3, 5, 1];

Math.max(...arr); // 5 (spread turns array into a list of arguments)

We also can pass multiple iterable objects this way:

let arr1 = [1, -2, 3, 4];
let arr2 = [8, 3, -8, 1];

Math.max(...arr1, ...arr2); // 8

We can even combine/ join the spread syntax with normal values:

let arr1 = [1, -2, 3, 4];
let arr2 = [8, 3, -8, 1];

Math.max(1, ...arr1, 2, ...arr2, 25); // 25

Let’s understand the detailed usage of the “spread” syntax with the help of the following example:

Example:

<html>

   <body>  

      Demonstrating spread operator in javascript

   </br>

   </br>

      <script type='text/javascript'>

        function display(...args){//This is rest operator

         document.write("Total number of parameters are "+args.length);

         document.write("</br>");

           for(x of args){

              document.write(x+" ");

           }

        }

        var data = ["Blog","CoolmonkTechie","JavaScript","Tutorial"];

        display(...data);//This is spread operator

       

      </script>   

   </body>

</html>

As we can see in the above example,  we are passing data array to the “display” function with the help of the spread operator, and the data array converts to a list of arguments.

That’s all about in this article.


Conclusion

In this article, We understood how to pass arbitrary parameters to a function using Rest Parameters and Spread Operator in JavaScript. We conclude that :

  • The “arguments” is a special array-like object that contains all the parameters passed by their index.
  • The “rest” parameters pass and handle an arbitrary number of arguments. 
  • The “spread” operator is used to convert the iterable objects like an array to a list of independent parameters.

Thanks for reading !! I hope you enjoyed and learned about Rest Parameters and Spread Operator 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.

You can find Other articles of CoolmonkTechie as below link :

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 Let vs Var vs Const Concepts

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, We will learn about most popular basic fundamental Variables concepts Lets, Var and Const from JavaScript. Let, Var, and Const are the various ways that JavaScript provides for declaration of JavaScript Variables. Var is an old way of declaring variables. Whereas, Let Const came into the picture from the ES6 version. Before starting the discussion about JavaScript let Vs var Vs const, let’s understand what ES is?

ES stands for Ecma Script, which is a scripting language specification specified by ECMA international. It standardized various implementations of JavaScript.

In this article, we will discuss differences of following ways of declaring a variable concerning their scope, use, and hoisting:

  • Var keyword: What, How, and Where?
  • Let keyword: What, How, and Where?
  • Const keyword: What, How, and Where?

A famous quote about learning is :

” Education is not the filling of a pail, but the lighting of a fire. “


Var keyword: What, How, and Where?

What is a “var” keyword ?

The “var” keyword is one of the ways using which we can declare a variable in JavaScript. Before the advent of ES6, var was the only way to declare variables. In other words, out of JavaScript let Vs var Vs const, var was the sole way to declare variables. Its syntax looks like below: 

Syntax:

var variable = value;

Scope of var:

The scope specifies where we can access or use the variables. When we declare a variable outside a function, its scope is global. In other words, it means that the variables whose declaration happens with “var” outside a function (even within a block) are accessible in the whole window. Whereas, when the declaration of a variable occurs inside a function, it is available and accessible only within that function.

It is illustrated with the help of following code snippet:

<html>

<body> Demonstrating var scopes in javascript:</br>
    <script type="text/javascript">
        var globalVariable = 5;
        document.write("The value of global variable outside block is: ", globalVariable, "</br>");
        if (globalVariable == 5) 
        { 
            globalVariable = 10; 
            var localBlockVariable = 15;
            document.write("The value of global variable inside block is: ", globalVariable, "</br>"); 
        }
        document.write("The value of global variable outside block is: ", globalVariable, "</br>");
        document.write("The value of block local variable outside block is: ", localBlockVariable, "</br>");

        function updateVariables() {
            globalVariable = 20; 
            localBlockVariable = 25;
            var localFunctionVariable = 30;
            document.write("The value of global variable inside function is: ", globalVariable, "</br>"); 
            document.write("The value of block local variable inside function is: ", localBlockVariable, "</br>");
        }

        updateVariables();
        document.write("The value of global variable outside function is: ", globalVariable, "</br>");
        document.write("The value of block local variable outside function is: ", localBlockVariable, "</br>");
        // This following statement will give error, as the local function variable can't be accessed outside
        // document.write("The value of function local variable outside function is: ", localFunctionVariable, "</br>");

    </script>
</body>

</html>

As is evident in the above code snippet, the variables declared in global and block scope are accessible in the whole window. In contrast, variables declared inside in the function can just be accessed within that function only.

Re-declaration of “var” variables:

The variables declared using var can be re-declared within the same scope also, and it will not raise any error.

Let’s understand it with the help of following code snippet:

<html>

<body> Demonstrating var scopes in javascript:</br>
    <script type="text/javascript">
        var globalVariable = 5;
        document.write("The value of global variable outside block is: ", globalVariable, "</br>");
        if (globalVariable == 5) 
        { 
            var globalVariable = 10; // Re-declare in block
            document.write("The value of global variable inside block is: ", globalVariable, "</br>"); 
        }
        var globalVariable = 15;  // Re-declare in same scope
        document.write("The value of global variable outside block is: ", globalVariable, "</br>"); 

    </script>
</body>

</html>

As is clear from the above code snippet, the same variable “globalVariable” has been declared multiple times without any error.

Hoisting of var:

Hoisting is a JavaScript mechanism where variables and function declarations move to the top of their scope before code execution.

For Example, Let see below code snippet :

document.write(variable1);
var variable1 = "Hello World"

Here, JavaScript will interpret it as:

var variable1;
document.write(variable1); // variable1 will be undefined
variable1 = "Hello World"

So var variables hoist to the top of its scope and initialize with a value of undefined. If we access it before its declaration, the value of a variable declared using var is printed as “undefined,” .


Let keyword: What, How, and Where?

What is the “let” keyword?

In ES 2015 release, ES released one more keyword for declaration of variables, which is known as the “let“. Its syntax looks like below: 

Syntax:

let variable = value;

Scope of let:

let is block scoped. A block is a chunk of code bounded by {}. Moreover, a variable that one declares in a block with the “let” is only available for use within that block only.

Let’s try to understand the same with the help of following code snippet:

<html>

<body> Demonstrating let scopes in javascript:</br>
    <script type="text/javascript">
        let globalVariable = 5;
        document.write("The value of global variable outside block is: ", globalVariable, "</br>");
        if (globalVariable == 5) 
        { 
            globalVariable = 10; 
            let localBlockVariable = 15;
            document.write("The value of global variable inside block is: ", globalVariable, "</br>"); 
        }
        document.write("The value of global variable outside block is: ", globalVariable, "</br>");
        // This following statement will give error, as the local block variable can't be accessed outside
        // document.write("The value of block local variable outside block is: ", localBlockVariable, "</br>");

        function updateVariables() {
            globalVariable = 20; 
            localBlockVariable = 25; // This will raise error
            let localFunctionVariable = 30;
            document.write("The value of global variable inside function is: ", globalVariable, "</br>"); 
            // This following statement will give error, as the local block variable can't be accessed outside
            // document.write("The value of block local variable inside function is: ", localBlockVariable, "</br>");
        }

        updateVariables();
        document.write("The value of global variable outside function is: ", globalVariable, "</br>");
        // This following statement will give error, as the local block variable can't be accessed outside
        // document.write("The value of block local variable outside function is: ", localBlockVariable, "</br>");
        // This following statement will give error, as the local function variable can't be accessed outside
        // document.write("The value of function local variable outside function is: ", localFunctionVariable, "</br>");

    </script>
</body>

</html>

The above code snippet clearly understands that the variables declared using “let” are block-scoped and can’t access outside the block in which the declaration happens.

Re-declaration of “let” variables:

The variable declared using let can’t be re-declared.

It can be demonstrated easily with the help of following code snippet:

<html>

<body> Demonstrating let re-declare in javascript:</br>
    <script type="text/javascript">
        let globalVariable = 5;
        document.write("The value of global variable outside block is: ", globalVariable, "</br>");
        if (globalVariable == 5) 
        { 
            // The following statement will raise an error
            // let globalVariable = 10;
            document.write("The value of global variable inside block is: ", globalVariable, "</br>"); 
        }

        // The following statement will raise an error
        // let globalVariable = 15;  // Re-declare in same scope
        document.write("The value of global variable outside block is: ", globalVariable, "</br>"); 

    </script>
</body>

</html>

The above code snippet clearly shows that the variables using let can’t be re-declared.

Hoisting of let:

Just like var, let declarations hoist to the top. But, unlike var, which initializes as undefined, the let keyword does not initialize. So if you try to use a let variable before the declaration, you’ll get a “Reference Error.

Consider the below code snippet to validate the same:

<html>

<body> Demonstrating let hoisting in javascript:</br>
    <script type="text/javascript">
    	document.write("The value of let variable is: ", letVariable, "</br>");

    	let letVariable = 5; // let variable declared later on
    	</script>
</body>

</html>

As is evident from the above code snippet, JavaScript raises “Uncaught ReferenceError if we access the variable as let before its declaration.


Const keyword: What, How, and Where?

What is the “const” keyword?

Variables declared with the “const” keyword maintain constant values and can’t change their values during the scope. Its syntax looks like below:

Syntax:

const variable = value1;

Scope of const:

Similar to let, the scope of the const variables is also blocked.

The following code snippet will help us understand it better:

<html>

<body> Demonstrating const scopes in javascript:</br>
    <script type="text/javascript">
        const globalVariable = 5;
        document.write("The value of global variable outside block is: ", globalVariable, "</br>");
        if (globalVariable == 5) 
        { 
            // This following statement will give error, as const can't be assigned a new value
            // globalVariable = 10; 
            const localBlockVariable = 15;
            document.write("The value of global variable inside block is: ", globalVariable, "</br>"); 
            document.write("The value of block local variable inside block is: ", localBlockVariable, "</br>");
        }
        document.write("The value of global variable outside block is: ", globalVariable, "</br>");
        // This following statement will give error, as the local block variable can't be accessed outside
        // document.write("The value of block local variable outside block is: ", localBlockVariable, "</br>");

        function updateVariables() {
            // This following statement will give error, as const can't be assigned a new value
            //globalVariable = 20; 
            const localBlockVariable = 25; // This will be considered a new variable
            const localFunctionVariable = 30; 
            document.write("The value of global variable inside function is: ", globalVariable, "</br>"); 
            document.write("The value of block local variable inside function is: ", localBlockVariable, "</br>");
        }

        updateVariables();
        document.write("The value of global variable outside function is: ", globalVariable, "</br>");
        // This following statement will give error, as the local block variable can't be accessed outside
        // document.write("The value of block local variable outside function is: ", localBlockVariable, "</br>");
        // This following statement will give error, as the local function variable can't be accessed outside
        // document.write("The value of function local variable outside function is: ", localFunctionVariable, "</br>");

    </script>
</body>

</html>

The above code snippet depicts that const variables are block-scoped and can’t update with a new value.

Re-declaration of const variables:

Similar to let variables, the variable declared using const can’t be re-declared.

We can easily demonstrate it with the help of following code snippet:

<html>

<body> Demonstrating const re-declare in javascript:</br>
    <script type="text/javascript">
        const globalVariable = 5;
        document.write("The value of global variable outside block is: ", globalVariable, "</br>");
        if (globalVariable == 5) 
        { 
            // The following statement will raise an error
            // const globalVariable = 10;
            document.write("The value of global variable inside block is: ", globalVariable, "</br>"); 
        }

        // The following statement will raise an error
        // const globalVariable = 15;  // Re-declare in same scope
        document.write("The value of global variable outside block is: ", globalVariable, "</br>"); 

    </script>
</body>

</html>

The above code snippet makes it clear that the const variables can’t re-declare.

Hoisting of const:

Just like “let,” “const” declarations hoist to the top but don’t initialize.

Consider the below code snippet to validate the same:

<html>

<body> Demonstrating const hoisting in javascript:</br>
    <script type="text/javascript">
    	document.write("The value of const variable is: ", varVariable, "</br>");

    	const constVariable = 5; // const variable declared later on
    	</script>
</body>

</html>

As is evident from the above code snippet, JavaScript raises “Uncaught ReferenceError” if we access a variable that we declare as const before its declaration.


Conclusion

In this article, We understood the Javascript Variables Let,Var and Const Concepts . We conclude that :

  • If you declare a variable using the “var” keyword, it will be in the global scope(accessible to the whole program) if declared outside all functions. It will have a local scope(accessible within the function only) if defined inside a function.
  • If you declare a variable using the “let” keyword, it will be blocked scope, i.e., any variable declared using let, will be accessible with the surrounding curly brackets ({ }) only.
  • If you declare a variable using the “const” keyword, you will not be able to change its value later on. As per scope, it will be the same as variables declared using the “let” keyword.

Thanks for reading ! I hope you enjoyed and learned about JavaScript different types of Variable Concepts. 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 – 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 !!???

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