Blog

  • JavaScript – Graph Algorithms

    A graph is a data structure which consist nodes and edges. The node are simply vertices and the lines which connect them are edges. Graph is non-linear data structure.

    A Graph algorithms in JavaScript are used to solve the graph problems. These algorithms are used to traverse the graph, find the shortest path, etc. We can use these algorithms to solve the problems like finding the shortest path, finding the connected components, etc.

    Types of Graph

    Before dwelling deep into this chapter let’s learn about types of graphs.

    • Directed Graph : Directed graph is a graph in which the edges have a direction. In other word, we can call it a Digraph. These edges may be one way or two ways and also it may have loops. Arrow is used for representing the direction of the edges.
    • Undirected Graph: Undirected graph are exactly opposite of directed graph. Means, in this graph edges does not have any direction. We can also call it simple graph.
    • Weighted Graph: Weighted graph means the graph edges have some weight it means value. It help us to define the cost, distance, etc. between the vertices.
    • Unweighted Graph: Unweighted graph is opposite of weighted graph. It means the graph edges does not have any weight at all.

    Graph Representation

    There are two ways to represent the graph:

    • Adjacency Matrix: In this representation, we use a 2D array to represent the graph. The elements of the array are 0 or 1. If there is an edge between two vertices then we put 1 otherwise 0.
    • Adjacency List: In this representation, we use an array of linked list to represent the graph. Each element of the array represents a vertex and the linked list represents the edges of that vertex.

    Graph Algorithms

    When we talk about graph algorithms, there are plenty of the algorithms available. We mostly use these algorithms to solve the graph problems. We have listed some of them below:

    • Breadth First Search (BFS)
    • Depth First Search (DFS)
    • Topological Sorting

    Breadth First Search (BFS) Algorithm

    This algorithm we can use for traversing the graph. It is very useful for resolving many problems. In this algorithm, we start our traversal from the root node and then we go one level down, traverse all the nodes at that level and then move to the next level. We use queue data structure to implement this algorithm.

    Algorithm

    We can implement the BFS using the below steps given:

    • First, we need to create a queue and add the root node to the queue.
    • Then we will create a visited array and mark the root node as visited.
    • Then loop through the queue until it is empty.
    • Then we will dequeue the node from the queue and print it.
    • After that, get all the adjacent nodes of the dequeued node and if they are not visited then mark them as visited and enqueue them.
    • Repeat the above steps until the queue is empty.

    Implementation

    Following is the implementation of BFS algorithm in JavaScript:

    functionBFS(graph, root){let visited =[];let queue =[];
       queue.push(root);while(queue.length >0){let node = queue.shift();if(!visited[node]){
             console.log(node);// Process the node
             visited[node]=true;}// Ensure neighbours is definedconst neighbours = graph[node]||[];for(let i =0; i < neighbours.length; i++){let neighbour = neighbours[i];if(!visited[neighbour]){
                queue.push(neighbour);}}}}let graph =[[1,2],[3,4],[5],[6],[6],[7],[8],[]];BFS(graph,0);

    Following is the output of the above program −

    Following is the output of above code

    0
    2
    5
    7
    1
    4
    6
    8
    3
    

    Depth First Search (DFS) Algorithm

    Similar to BFS, this algorithm is also used for traversing the graph but in different way. In this algorithm, we start from the root node then move to left child or right child go to in-depth until we reach to leaf node then we backtrack and move to the next child.

    Algorithm

    We can implement the DFS using the below steps given:

    • First, we need to create a stack and add the root node to the stack.
    • Then we will create a visited array and mark the root node as visited.
    • Then loop through the stack until it is empty.
    • Then we will pop the node from the stack and print it.
    • After that, get all the adjacent nodes of the popped node and if they are not visited then mark them as visited and push them to the stack.
    • Repeat the above steps until the stack is empty.

    Implementation

    Following is the implementation of DFS algorithm in JavaScript:

    functionDFS(graph, root){let visited =[];let stack =[];
       stack.push(root);while(stack.length >0){let node = stack.pop();if(!visited[node]){
             console.log(node);
             visited[node]=true;}// Set a default value if graph[node] is undefinedconst neighbours = graph[node]||[];for(let i =0; i < neighbours.length; i++){let neighbour = neighbours[i];if(!visited[neighbour]){
                stack.push(neighbour);}}}}let graph =[[1,2],[3,4],[5],[6],[6],[7],[8],[]];DFS(graph,0);

    Output

    Following is the output of above code

    0
    2
    5
    7
    1
    4
    6
    8
    

    Topological Sorting Algorithm

    Using this algorithm we can actually sort the vertices of the graph in such a way that for every edge from vertex u to vertex v, u comes before v in the ordering.

    Algorithm

    We can implement the Topological Sorting using the below steps given:

    • We will create a visited array and mark all the vertices as not visited.
    • Then, we will create a stack to store the vertices.
    • Then we will loop through all the vertices and call the recursive function.
    • Then we will create a recursive function and mark the current node as visited.
    • Then we will loop through all the adjacent nodes of the current node and if they are not visited then call the recursive function.
    • Then push the current node to the stack.
    • Repeat the above steps until all the vertices are visited.
    • Finally, print the stack.

    Implementation

    Following is the implementation of Topological Sorting algorithm in JavaScript:

    functiontopologicalSort(graph){let visited =[];let stack =[];for(let i =0; i < graph.length; i++){if(!visited[i]){topologicalSortUtil(graph, i, visited, stack);}}while(stack.length >0){
          console.log(stack.pop());}}functiontopologicalSortUtil(graph, node, visited, stack){
       visited[node]=true;const neighbours = graph[node]||[];for(let i =0; i < neighbours.length; i++){let neighbour = neighbours[i];if(!visited[neighbour]){topologicalSortUtil(graph, neighbour, visited, stack);}}
       stack.push(node);}// Valid DAGlet graph =[[1,2],// Node 0 -> 1, 2[3],// Node 1 -> 3[3,4],// Node 2 -> 3, 4[],// Node 3 -> No outgoing edges[5],// Node 4 -> 5[]// Node 5 -> No outgoing edges];topologicalSort(graph);

    Output

    Following is the output of above code

    0
    1
    2
    3
    4
    5
    6
    7
    8
    
  • JavaScript – Get the Current URL

    In JavaScript, we can get the current URL of the page using the window.location object. The window.location object contains information about the current URL of the page.

    We can get URL from another method also, which is document.URL. Another method is document.documentURI which returns the location of the document as a string.

    Using window.location

    The window.location object can be used to get the current URL. The window.location.href property returns the href (URL) of the current page. We can also use window.location or location in place of window.location.href.

    Example

    In this example we will use window.location.href to get the current URL. In below example you can try using window.location or location in place of window.location.href.

    <html><body><p id="demo"></p><script>let currentURL = window.location.href;
       document.getElementById("demo").innerHTML = currentURL;</script></body></html>

    Output

    We execute the code online. When you run the above code, You will able to see console message with the current URL.

    https://www.tutorialspoint.com/javascript/javascript_get_current-url.php
    

    Using document.URL

    We could also use document.documentURI and document.URL properties. The document.URL returns the URL of the document as a string.

    Example

    In this example, we will use the document.URL to get the current URL of the document.

    <html><body><p id="demo"></p><script>let currentURL = document.URL;
       document.getElementById("demo").innerHTML = currentURL;</script></body></html>

    Output

    When you execute the above code, In console the current URL will be displayed.

    https://www.tutorialspoint.com/javascript/javascript_get_current_url.php
    

    Using document.documentURI

    The document.documentURI returns the location of the document as a string.

    Example

    In this example, we will use the document.documentURI to get the current URL of the document.

    <html><body><p id="demo"></p><script>let currentURL = document.documentURI;
       document.getElementById("demo").innerHTML = currentURL;</script></body></html>

    Output

    When you execute the above code, In console you will be able to see the current URL of the document.

    https://www.tutorialspoint.com/javascript/javascript_get_current_url.php
  • JavaScript – Null Checking

    In this chapter, we will learn how to check the null values in JavaScript. The null value indicates the intentional absence of any object value. It is a JavaScript primitive value that is false when used in Boolean operations.

    This distinguishes null from the related primitive value undefined, which is an unintended absence of any object value. This is because a variable that has been declared but not given a value is undefined rather than null.

    We can take an example of a box that has nothing in it, nothing at all. We can say that the box is null. Similarly, in JavaScript, we can say that a variable is null when it has no value.

    Checking Null Values

    We can check the null values in javascript using quite a few methods. Let’s see them one by one.

    • Using the Strict equality operator (===)
    • Using the typeof operator
    • Using Object.js method

    Using the Strict equality operator (===)

    In this method, we will see how we can check null values using the strict equality operator (===). The strict equality operator compares two values for equality. It returns true if the values are equal and false otherwise. It is a strict equality operator, which means it checks both the type and the value of the variable.

    Syntax

    The syntax for checking null values using the strict equality operator is given below.

    let result =( v ===null);

    Example

    Below is the example of checking null values in JavaScript.

    <!DOCTYPE html><html><head><title>Check fornull values in JavaScript</title></head><body><h2>Check fornull values using the strict equality operator.</h2><div id="output"></div><script>let output = document.getElementById("output");var v =null;if(v ===null){
       output.innerHTML ="Value is null";}else{
       output.innerHTML ="Value is not null";}</script></body></html>

    In the above output, the variable is being checked for null and the value is being executed in the if-block that the variable contains a null value.

    Using the typeof operator

    The typeof operator may be used to determine the data type of a JavaScript variable. Here we use the typeof operator with the null operator. The (!variable) means the value is not null and if it is checked with the typeof operator variable which has the data type of an object then the value is null.

    Syntax

    Following is the syntax to typeof operator

    typeofvar;

    Here var is the variable whose data type is to be checked and is used as a parameter.

    Example

    In this example, we use the JavaScript typeof operator to check whether the values of a given variable are equal to null or not.

    <!DOCTYPE html><html><head><title>Check fornull values in JavaScript</title></head><body><h2>Check fornull values using the typeof operator.</h2><div id="output"></div><script>let output = document.getElementById("output");var v =null;if(!v &&typeof v ==="object"){
       output.innerHTML ="Value is null";}else{
       output.innerHTML ="Value is not null";}</script></body></html>

    The variable is tested for null in the above output, and the value is executed in the if-block that the variable has a null value.

    Using Object.js method

    The Object.is() function in JavaScript that compares two values to see whether they are the same. A boolean value indicates if the two parameters in the function have the same value. Two values could be the same if both the values are null.

    Syntax

    Following is the syntax to Object.is() method

    Object.is( q,null);

    Parameters

    The parameters used in the Object.is() method are as follows

    • q The first value to compare.
    • null The second value to compare.

    Example

    In the program below, we use the Object.is() function to check for null values

    <!DOCTYPE html><html><head><title>Check fornull values in JavaScript</title></head><body><h2>Check fornull values using the Object.is() method.</h2><div id="output"></div><script>let output = document.getElementById("output");var v =null;if(Object.is(v,null)){
       output.innerHTML ="Value is null";}else{
       output.innerHTML ="Value is not null";}</script></body></html>

    Output

    Following is the output of the above program.

    Value is null
    

    In the above output, the variable is being checked for null and the value is being printed with a true statement that the variable contains a null value.

    Conclusion

    In this chapter, we have learned how to check null values in JavaScript using the strict equality operator, typeof operator, and Object.is() method. We have also seen the syntax and examples of each method.

  • JavaScript – Nested Loop

    In JavaScript, a loop inside another loop is called a nested loop. We need nested loop when we iterate over multi-dimension array or matrix. When we have to perform repeated actions on each element of an array we do use nested array.

    Nested loops in JavaScript

    Let’s say we have two arrays, one is an array of rows and another is an array of columns. We can use nested loop to iterate over each element of the array of rows and then iterate over each element of the array of columns.

    Syntax of Nested Loop

    Below is the syntax of nested loop in JavaScript.

    for(let i =0; i < rows.length; i++){for(let j =0; j < columns.length; j++){// code block to be executed}}

    Nested Loop Using for Loop

    In the following code snippet that demonstrates how we can use nested for loops.

    let rows =[1,2,3];let columns =[4,5,6];for(let i =0; i < rows.length; i++){for(let j =0; j < columns.length; j++){
          console.log(rows[i]+" "+ columns[j]);}}

    Output

    1 4
    1 5
    1 6
    2 4
    2 5
    2 6
    3 4
    3 5
    3 6
    

    We have two arrays, one is an array of rows and another is an array of columns. We are using nested loop to iterate over each element of the array of rows and then iterate over each element of the array of columns.

    Nested Loop Using while Loop

    We can use while loop same as for loop to iterate through the array elements. Below is the code snippet that shows how we can use nested while loops.

    let rows =[1,2,3];let columns =[4,5,6];let i =0;while(i < rows.length){let j =0;while(j < columns.length){
          console.log(rows[i]+" "+ columns[j]);
          j++;}
       i++;}

    Output

    1 4
    1 5
    1 6
    2 4
    2 5
    2 6
    3 4
    3 5
    3 6
    

    We have two arrays, one is an array of rows and another is an array of columns. We are using nested loop to iterate over each element of the array of rows and then iterate over each element of the array of columns.

  • JavaScript – Linked List

    Linked List is an ordered collection of data elements. In linked list the data will be represented in Nodes. Node has two parts, the first part will be holding the data of the element and second part of the node (pointer) will store the address of the very next node. In linked list elements are stored in a sequential manner.

    Node: This represents each element in the linked list. It consists of 2 parts, data and next.

    Head: The reference to the first element is called a head.

    Next: This is the pointer that points to the next node in the linked list.

    Linked List

    Types of Linked List

    There are three types of linked list:

    • Singly Linked List: In this type of linked list, each node in the list is connected only to the next node in the list.
    • Doubly Linked List: In this type of linked list, each node in the list is connected to the next and the previous node.
    • Circular Linked List: In this type of linked list, the last node is connected to the first node.

    Implementations of Linked List

    Defining node class and liked list class, this is basically the prerequisite in order to implement a linked list in JavaScript. In this step, 2 classes namely one for the nodes and the other for the linked list need to be created.

    The Node class represents a single node in the linked list. It has two properties which are data and next. The data property is used to store the actual data of the node, whereas the next property is a reference to the next node in the list. The Node class consists of a constructor that initializes the data and next property when creating a new Node.

    classNode{constructor(data){this.data = data;this.next =null;}}

    The LinkedList class is a representation of the linked list itself. It has a head property that refers to the first node in the list. The LinkedList class also has a constructor that initializes the head property when creating a new LinkedList.

    classLinkedList{constructor(){this.head =null;this.tail =null;this.length =0;}}

    The LinkedList class also consists of a method that allows you to insert, delete, and search for nodes in the list while simultaneously allowing other operations like printing the list, counting the elements, reversing the list and so on.

    Inserting a Node

    To insert a node in the linked list, we need to create a new node first and need to assign the data to it. Then we need to check if the head is null, if it is null then we need to assign the new node to the head. If the head is not null, then we need to traverse the list till the last node and assign the new node to the next of the last node.

    insert(data){let node =newNode(data);if(!this.head){this.head = node;this.tail =this.head;}else{this.tail.next = node;this.tail = node;}this.length++;returnthis;}

    Searching a Node

    If there is a need to search a element in the linked list we can simply traverse the linked list and check if current node data is equal to the data we are searching for. If we find the data we are searching for, we can return the node.

    search(data){let current =this.head;while(current){if(current.data === data){return current;}
          current = current.next;}returnnull;}

    Deleting a Node

    If we want to delete a node from the linked list, let’s say you have node prev and node current and you want to delete the node current . You can simply assign the next of the prev to the next of the current and the node current will be deleted.

    delete(data){if(!this.head)returnnull;if(this.head.data === data){this.head =this.head.next;this.length--;returnthis;}let current =this.head;let prev =null;while(current){if(current.data === data){
             prev.next = current.next;this.length--;returnthis;}
          prev = current;
          current = current.next;}returnnull;}

    Printing the Linked List

    You can print the elements of a linked list by traversing through the list and printing the data of each node.

    print(){let current =this.head;while(current){
          console.log(current.data);
          current = current.next;}}

    Code Example

    Following is an example of a linked list implementation in JavaScript.

    <!DOCTYPE html><head><title>Linked List</title></head><body><p id ="demo"></p><script>classNode{constructor(data){this.data = data;this.next =null;}}classLinkedList{constructor(){this.head =null;this.tail =null;this.length =0;}insert(data){let node =newNode(data);if(!this.head){this.head = node;this.tail =this.head;}else{this.tail.next = node;this.tail = node;}this.length++;returnthis;}search(data){let current =this.head;while(current){if(current.data === data){return current;}
             current = current.next;}returnnull;}delete(data){if(!this.head)returnnull;if(this.head.data === data){this.head =this.head.next;this.length--;returnthis;}let current =this.head;let previous =null;while(current){if(current.data === data){
                previous.next = current.next;this.length--;returnthis;}
             previous = current;
             current = current.next;}returnnull;}print(){let current =this.head;let output ="";while(current){
              output += current.data +" ";
              current = current.next;}
          document.getElementById("demo").innerHTML = output;}}let list =newLinkedList();
    list.insert(1);
    list.insert(2);
    list.insert(3);
    list.insert(4);
    list.insert(5);
    list.print();</script></body></html>

    Output

    Following is the output of the above code.

    1 2 3 4 5
    

    In the above example, we have created a linked list with elements 1, 2, 3, 4, and 5. We have inserted these elements into the linked list and printed the list.

  • JavaScript – Lazy Loading

    In JavaScript, there is way to make website faster. Means, we can only load what we need first like images, videos,etc. The file or data which is not needed at the moment that can be loaded later when it needed this is called lazy loading.

    For example, When you open the Instagram app, It only loads the images and videos you are able to see on current screen frame. But when you scroll down, you will see more images and videos are loading. Instagram uses lazy loading for making better user experience and faster loading of the app.

    Why do we need Lazy Loading

    Following are the uses of lazy loading:

    • Lazy loading is useful when you have a lot of images and files on your website.
    • Lazy loading is also useful for improving the performance of the website.
    • Lazy loading is also used for improving the user experience.
    • Lazy loading is also used for reducing the loading time of the website.

    Example of Lazy Loading

    Following is the code snippet for lazy loading in JavaScript:

    const images = document.querySelectorAll("[data-src]");functionpreloadImage(img){const src = img.getAttribute("data-src");if(!src){return;}
       img.src = src;
       img.removeAttribute("data-src");}const imgOptions ={
       threshold:0,
       rootMargin:"0px 0px 300px 0px"};const imgObserver =newIntersectionObserver((entries, imgObserver)=>{
       entries.forEach(entry=>{if(!entry.isIntersecting){return;}else{preloadImage(entry.target);
             imgObserver.unobserve(entry.target);}});}, imgOptions);
    images.forEach(image=>{
        imgObserver.observe(image);});

    This code snippet is all about making images load when they are in the viewport. It finds images with the attribute data-src (it is like a placeholder) and it sets up a “watcher” for each image.

    The watcher(IntersectionObserver) will check if the image is in the viewport and if it found that it is, it will load the actual image and remove the data-src attribute. Then it will stop watching that image so it doesn’t laod again. This way page dosen’t load everything at once.

  • JavaScript – Insertion Sort Algorithm

    The Insertion Sort is a sorting algorithm that works very similar to the way we sort the playing cards when we play. The arrangement of elements in a sorted manner is done through insertion sort.

    In this algorithm, the array will be divided virtually into two parts which are sorted and unsorted parts. The values present in unsorted part will be picked and placed at the correct position where it satisfies the sorting order.

    The Insertion sort is simple algorithm having simple implementation. Generally, this algorithm is efficient for smart data values. This is suitable for data sets which are already partly sorted.

    How Insertion Sort Works?

    Consider an array having some elements in it in a random order which are not sorted. Here we can sort the elements by performing insertion sort. So, Lets check the scenario below.

    Input: [24, 22, 26, 10, 12]; 
    Output: [10, 12, 22, 24, 26];
    

    To know how the insertion sort is working, lets assume an array arr=[24, 22, 26, 10, 12].

    Insertion Sort Algorithm

    First Pass

    • At first in insertion sort, the initial two elements in the array are compared first.
    • 22 is less than 24 here, thus they are not in ascending order and 24 is not in a correct position. So swap 22 and 24. And for now 24 is stored in a sub array.
    Insertion Sort Algorithm

    Second Pass

    • Now, compare the next two elements in the array.
    Insertion Sort Algorithm
    • Here, both the elements 24 and 26 are in ascending order as 26 is greater than 24. Thus no swapping will be occurred.
    • 24 is also stored in the sub array along with 22.

    Third Pass

    • Present there are two elements 22 and 24 are in sub-array.
    • Now compare the next two elements 10 and 26.
    Insertion Sort Algorithm
    • As 10 is smaller than 26, Swap both the values.
    Insertion Sort Algorithm
    • Even after swapping 10 and 24 are sorted, thus swap again.
    Insertion Sort Algorithm
    • Again 10 and 22 are not sorted, so swap again.
    Insertion Sort Algorithm
    • Now, 10 is at correct position.

    Fourth Pass

    • Currently, the elements in the sorted sub array are 10, 22 and 24.
    • Comparing the next two elements 26 and 12.
    Insertion Sort Algorithm
    • As they are not sorted, swap both the values.
    Insertion Sort Algorithm
    • Now, 12 is smaller than 24. Thus swap them.
    Insertion Sort Algorithm
    • Here 12 is smaller than 22 and they are not sorted, so swap them.
    Insertion Sort Algorithm
    • Now, 12 is at correct position and the array is perfectly sorted.

    Alogrithm

    To sort an array sized n in ascending order using insertion sort algorithm.

    • If it is the first element, it is already sorted. return 1;
    • Pick next element
    • Compare with all elements in the sorted sub-list
    • Shift all the elements in the sorted sub-list that is greater than the value to be sorted
    • Insert the value
    • Repeat until list is sorted

    Insertion Sort Implementation

    Following is an example of insertion sort

    <!DOCTYPE html><html><head><title>Insertion Sort Algorithm</title></head><body><p id ="demo"></p><script>functioninsertionSort(arr){let n = arr.length;for(let i =1; i < n; i++){let current = arr[i];let j = i-1;while((j >-1)&&(current < arr[j])){
                      arr[j+1]= arr[j];
                      j--;}
                   arr[j+1]= current;}return arr;}let arr =[24,22,26,10,12];
             document.getElementById("demo").innerHTML =insertionSort(arr);</script></body>

    Output

    Lets see the output of the above code snippet.

    [10, 12, 22, 24, 26]
  • JavaScript – HTTP Requests

    Http is a protocol, stands for hypertext transfer protocol. The http requests are used to communicate with web servers. It allow us to send requests to a server and get responses. These can be used to fetch data, submit forms, upload file and more.

    HTTP Methods

    These are the most commonly used HTTP methods:

    • GET:This method is used to get information from a server that we need. We can think of it like asking for a piece of information without sending anything extra to server.
    • POST:This method is used to send data to a server which stores that data. Usually when submitting a form, we store information onto the server.
    • PUT: This is method is used for updating the data which is already available onto the server. For example, in the code Snippet, you filled the form with incorrect information and have to make it correct.
    • DELETE: This method is used to delete something that you don’t need anymore, you can delete that from server.
    • PATCH: This method helps while updating partial information. In the code snippet, if you made typos in forms, you can update them with PATCH.

    Ways to Make HTTP Requests in JavaScript

    There are ways to make http requests in javascript those are below:

    • Using XMLHttpRequest (XHR)
    • Using Fetch API

    Using XMLHttpRequest (XHR)

    XMLHttpRequest is an old built-in browser object that help us to make http requests in javascript. It is used to get data from the server and send data to the server.

    Code Snippet

    Below code snippet shows you how we can make request using XMLHttpRequest

    // Create a new XMLHttpRequest objectvar xhr =newXMLHttpRequest();// Configure it: GET-request for the URL /article/.../load
    xhr.open('GET','/article/.../load',true);// Send the request over the network
    xhr.send();

    This is how we can make a very simple GET request using XMLHttpRequest. We can also make POST, PUT, DELETE requests using the same XMLHttpRequest.

    Using Fetch API

    The Fetch API is a new modern way to make a http requests in JavaScript. It helps us to grab data from the server, and send data to the server. It is built-in the browsers, which means that you would not need any extra libraries to use it.

    Code Snippet

    Below code snippet shows you how we can make request using Fetch API

    // Make a requestfetch('/article/.../load').then(response=> response.json()).then(data=>alert(data.title)).catch(error=>alert(error));

    This is how we can make a simple and easy GET request using Fetch API. We can also make POST, PUT, DELETE requests using Fetch API as well.

    Conclusion

    HTTP requests are mostly used to communicate with web servers. We do have several methods to make request. We can use these requests to fetch data, submit forms, upload files and many more. There are two ways to make http requests in javascript, those are using XMLHttpRequest and Fetch API.

  • JavaScript – Generate Colors

    Generating colors are quite handy while working on web development projects. For beautiful UI, we need to use different colors. In this chapter, we will learn how to generate colors in JavaScript.

    Generating Random Hex Color

    The Hex (Hexadecimal) code is a six-digit code and a three-byte hexadecimal number that is used to represent the colors.

    These three bytes represent RGB which means the amount of red, green, and blue in a particular shade of a color. Each byte will represent a number in the range 00 to FF (Hexadecimal notation) or 0 to 255 in decimal notation. This indicates the intensity of each of the color components from 0 to 255.

    The following are the functions to be used for generating random hex codes

    Math.random()

    This function is used to get the number randomly in the range 0 to less than 1 including the decimal.

    functionrandom_num(maximum){return Math.floor(Math.random()* maximum);}
    document.write(random_num(5));// output: 0, 1 or 2

    In the above snippet, we gave input as 5 as maximum value. Whenever we try to execute the program, it will print the output in between 0 to 4.

    document.write(random_num());// output: 0 to 1

    In this case, as we didnt have any input value as the maximum value, it prints a random number between 0 to 1 whenever we run the program. So, this is how the Math.random() function works.

    Math.floor()

    This is a function that will round off the number downwards to the nearest integer.

    document.write(Math.floor(1.95));// output: 1

    Here, we can see the output is printed as 5. So, the value is rounded downwards to the nearest integer.

    document.write(Math.floor(1));// output: 1

    If the value passed is a perfect integer without any floating (decimal) points, it will be rounded off.

    Now, lets combine these functions to generate the random hex numbers.

    We use math.random() to generate a random number and multiply it with 16777215 as this number is the decimal representation of fffff (Highest in the hex code).

    Math.random()*16777215
    

    This will return a random number like 12421420.464841081 with decimals, Now we use math.floor() to remove the decimals and return a whole number.

    Math.floor(Math.random()*16777215)
    

    Now, we include toString() method to convert the number into a string. We have passed 16 as a parameter because Base 16 is hexadecimal. The value of 16 will return hex-code (with numbers and letters).

    Math.floor(Math.random()*16777215).toString(16);
    

    Example

    Now, its time to generate the random hex color code. We will use the above code snippet to generate the random hex color code.

    <!DOCTYPE html><html><title>Generating random hex color</title><head><h3><div id="demo">Mouse-over on this box to getnewrandom color</div><p id="color"></p></h3><style>
          body {
             height:100vh;
             padding:1rem;
             display: grid;
             place-items: center;
             font-family: verdana;}
          h3 {
             background: white;
             padding:1rem 1rem;
             text-align: center;
             border-radius:5px 20px 5px;}
          p {
             display: block;
             padding:1px;
             font-size:20px;
             font-weight: lighter;
             font-family: verdana;}</style></head><body><script>functionhex(){const RanHexColor ='#'+ Math.floor(Math.random()*16777215).toString(16);
             document.body.style.backgroundColor = RanHexColor;
             color.innerHTML = RanHexColor;}
          demo.addEventListener("mouseover", hex);hex();</script></body></html>

    In the output, whenever you mouse over the box which is in middle it will generate the random hex colors on the background.

    Generating random RGB color

    For generating random RGB color in JavaScript, we use same trick as we used for hex color. We will generate random numbers for red, green, and blue and then combine them to get the RGB color.

    Example

    Below is the code snippet for generating random RGB color:

    <!DOCTYPE html><html><title>Generating random RGB color</title><head><h3><div id="demo">Mouse-over on this box to getnewrandom color</div><p id="color"></p></h3><style>
          body {
             height:100vh;
             padding:1rem;
             display: grid;
             place-items: center;
             font-family: verdana;}
          h3 {
             background: white;
             padding:1rem 1rem;
             text-align: center;
             border-radius:5px 20px 5px;}
          p {
             display: block;
             padding:1px;
             font-size:20px;
             font-weight: lighter;
             font-family: verdana;}</style></head><body><script>functionrgb(){const RanRGBColor ='rgb('+ Math.floor(Math.random()*256)+','+ Math.floor(Math.random()*256)+','+ Math.floor(Math.random()*256)+')';
             document.body.style.backgroundColor = RanRGBColor;
             color.innerHTML = RanRGBColor;}
          demo.addEventListener("mouseover", rgb);rgb();</script></body></html>

    Output

    In the output, whenever you mouse over the box which is in middle it will generate the random RGB colors on the background.

  • JavaScript – Filter Method

    JavaScript – Filter Method

    In JavaScript, the filter() method is used to create a new array with elements that pass a certain condition. It takes a callback function as its argument which is executed for each and every element in the array. If the callback function returns true, the element is added to the new array or else it is filtered out.

    This method does not change or modify the original array. Also, it does not execute the callback function for empty elements.

    Syntax

    Following is the syntax of JavaScript Array.filter() method −

    array.filter(callback(element, index, array), thisArg)

    Parameters

    This method accepts two parameters. The same is described below −

    • thisArg (optional) It specifies a value passed to the function to be used as its this value.
    • callback This is a callback function that will be called once for each element in the array. It further takes three arguments:
    • element:The current element being processed in the array.
    • index: The index of the current element being processed.
    • array: The array of the current element.

    Return Value

    This method returns a new array containing the elements for which the callback function returned true.

    Example

    In the following example, the provided callback function checks each element in the numbers array and returns a new array, “result”, containing all the elements that are greater than 30.

    <html><body><script>const numbers =[10,20,30,40,50];const result = numbers.filter(function(number){return number >30;});
             document.write(result);</script></body></html>

    Output

    Following is the output of the above program.

    40,50
    

    Filter method on Typed Arrays

    Typed arrays are array-like objects that provide a mechanism for reading and writing raw binary data.We can use filter() method on typed arrays as well.

    Example

    If all elements in the typed array pass the callbackFn test, a new typed array is returned that contains only those elements that pass the test.

    In the following example, we use the JavaScript TypedArray filter() method to filter out all the odd elements from the given typed array [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. We create a function named isOdd() that checks for odd values, and passes it as an argument to the filter() method.

    <html><head><title>JavaScript TypedArray filter() Method</title></head><body><script>functionisOdd(element, index, array){return element %2!=0;}const T_array =newInt8Array([1,2,3,4,5,6,7,8,9,10]);
          document.write("The typedArray elements are: ", T_array);//create new empty typed arraylet odd_t_array =([]);//using filer() method
          odd_t_array = T_array.filter(isOdd);
          document.write("<br>New typed array(containing only odd elements): ", odd_t_array);</script></body></html>

    Output

    Following is the output of the above program.

    The typedArray elements are: 1,2,3,4,5,6,7,8,9,10
    New typed array(containing only odd elements): 1,3,5,7,9
    

    Filter method on Map

    We can use filter() method on Map as well. Everything is similar to normal array, means we can filter out elements in same way as we do with arrays.

    Example

    If all elements in the map pass the callbackFn test, a new map is returned that contains only those elements that pass the test.

    In the following example, we use the JavaScript Map filter() method to filter out all the elements from the given map that are greater than 30. We create a function named isGreater() that checks for values greater than 30, and passes it as an argument to the filter() method.

    <html><head><title>JavaScript Map filter() Method</title></head><body><script>functionisGreater(value, key, map){return value >30;}const map =newMap([[1,10],[2,20],[3,30],[4,40],[5,50]]);
       document.write("The map elements are: ");for(let[key, value]of map){
          document.write(key +" => "+ value +",");}//create new empty maplet new_map =newMap();//using filer() method
       new_map =newMap([...map].filter(([key, value])=>isGreater(value, key, map)));
       document.write("<br>New map(containing only elements greater than 30): ");for(let[key, value]of new_map){
          document.write(key +" => "+ value +",");}</script></body></html>

    Output

    Following is the output of the above program.

    The map elements are: 1 => 10,2 => 20,3 => 30,4 => 40,5 => 50
    New map(containing only elements greater than 30): 4 => 40,5 => 50