Category: JavaScript Advanced Chapters

https://zain.sweetdishy.com/wp-content/uploads/2026/01/js-1.png

  • 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
  • JavaScript – Date Validation

    In JavaScript, we can validate the date. A date should be in a particular format or it should be in a particular range and should be valid.

    Why we validate a date ?

    Lets understand why we need to validate the date in JavaScript by example. Suppose, you have developed an application that takes some information in the submission form from the user. Users can make a mistake. What if they enter the wrong date in the input box? In such a case, developers need to validate the date.

    Here, we have three different ways to validate the date in JavaScript.

    • Using getTime() method
    • Using the isFinite() Method
    • Using Moment.js isValid() method
    • Check the Date Format using Regular Expression

    Using getTime() method

    In JavaScript, we can create the new date by creating the object of the Date() class. We can apply different methods of Date class to the date object. We will use the getTime() method of date class in this approach to validate the date.

    We will check for the type of the variable. If the variables are of Date object type, we will check whether the getTime() method for the date variable returns a number or not. The getTime() method returns the total number of milliseconds since 1, Jan 1970. If it doesnt return the number, it means the date is not valid.

    Syntax

    Users can follow the below syntax to validate the date using the getTime() method.

    if(Object.prototype.toString.call(date)==="[object Date]"){if(!isNaN(date.getTime())){// date is valid}else{//Date is not valid}}else{// date is not valid}

    Parameters

    Users can follow the below parameters to validate the date using the getTime() method.

    • date:It is a date variable and always required.

    Example

    In the below example, we have created one valid and another invalid date. We have created the isValid() function to validate the date. In the function, we are checking whether the object type is a Date or not. Also, we are checking whether the getTime() method returns a number or not using the isNaN() method.

    <html><head></head><body><h2> check whether a JavaScript date is valid.</h2><h4> Validate the date object using <i>getTime()</i> method.</h4><p id ="validate"></p><script>let validate = document.getElementById("validate");functionisValid(date){if(Object.prototype.toString.call(date)==="[object Date]"){if(!isNaN(date.getTime())){
             validate.innerHTML += date +" is valid. <br/> ";}else{
             validate.innerHTML += date +" is not valid. <br/> ";}}else{
          validate.innerHTML += date +" is not valid. <br/> ";}}let date =newDate("No date");isValid(date);
    date =newDate();isValid(date);</script></body></html>

    Using the isFinite() Method

    In JavaScript, the instanceof operator allows us to check whether the variable is an instance of the Date() class or not. We will check for that first, and if it is, we will check if the getTime() method returns the finite number of milliseconds.

    If the date variable is not the Date object type or the getTime() method returns a different value rather than a number, it returns false.

    Syntax

    Users can follow the below syntax to validate date using the isFinite() method

    if( date instanceofDate&&isFinite(date)){// date is valid}else{// date is not valid}

    Example

    In the following example, we have used the instanceof operator to check weather the type of variable is date or not in the if-else condition. Also, we have used the isFinite() method to check the number of milliseconds is finite. We have tested for various dates, and users can see the result in the output of the below example.

    <html><head></head><body><h2> check whether a JavaScript date is valid.</h2><h4> Validate the date object using <i>isFinite()</i> method.</h4><p id ="validate"></p><script>let validate = document.getElementById("validate");functionisValid(date){if( date instanceofDate&&isFinite(date)){
          validate.innerHTML += date +" is valid. <br/> ";}else{
          validate.innerHTML += date +" is not valid. <br/> ";}}let date =newDate("No date");isValid(date);
    date =newDate();isValid(date);</script></body></html>

    Check the Date Format using Regular Expression

    In JavaScript, we can validate the date format using the regular expression. We can check whether the date is in the format of YYYY-MM-DD or not. We can use the test() method of the regular expression to check the date format.

    Syntax

    Users can use the below syntax to validate the date format using the regular expression.

    let date ="2022-07-32";let reg =/^\d{4}-\d{2}-\d{2}$/;let valid = reg.test(date);

    Example

    In the following example, we have created the regular expression to check the date format. We have created the two dates, one is in the correct format, and another is in the wrong format. We are using the test() method of the regular expression to validate the date format.

    <html><head></head><body><h2> check whether a JavaScript date is valid.</h2><h4> Validate the date object using <i>Regular Expression </i> method.</h4><p id ="validate"></p><script>let validate = document.getElementById("validate");let date ="2022-07-32";let reg =/^\d{4}-\d{2}-\d{2}$/;let valid = reg.test(date);if(valid){
       validate.innerHTML += date +" is valid. <br/> ";}else{
       validate.innerHTML += date +" is not valid. <br/> ";}
    date ="2022-07-31";
    valid = reg.test(date);if(valid){
       validate.innerHTML += date +" is valid. <br/> ";}else{
       validate.innerHTML += date +" is not valid. <br/> ";}</script></body></html>

    Conclusion

    In this tutorial, we have learned how to validate the date in JavaScript. We have used different methods to validate the date. We have used the getTime() method, isFinite() method, Moment Js isValid() method, and regular expression to validate the date. We have also seen the example of each method to validate the date.

  • JavaScript – Current Date/Time

    Date and time are the most common things we often need to use in applications. In javascript, we can use Date object to get the current date and time.

    To solve all the problems, we will just create an object of date class and will use its various methods to get the current date and time.

    • Date object
    • toLocaleString() method

    Current Date and Time using Date Object

    The Date class contains several methods in which we can fetch the current date, day, and time by. Also, it includes hundreds of different methods that programmers can use according to their requirements.

    Syntax

    Below is the syntax given to get the current date and time using the Date object.

    var date =newDate();

    Using the below syntax users can get the year, month and date.

    var date =newDate();var year = date.getFullYear();var month = date.getMonth();var day = date.getDate();

    Using the below syntax users can get hours, minutes, and second.

    var date =newDate();var hours = date.getHours();var minutes = date.getMinutes();var seconds = date.getSeconds();

    Example

    Following example explains how to use the above methods to get the date and time from the Date object. Also, we have added +1 to the returned value from the month as it returns values between 0 and 11.

    <html><body>< p id ="demo"></p><script>var date =newDate();var year = date.getFullYear();var month = date.getMonth()+1;var day = date.getDate();var hours = date.getHours();var minutes = date.getMinutes();var seconds = date.getSeconds();
    document.getElementById('demo').innerHTML ='Current Date and Time: '+ day +'-'+ month +'-'+ year +' '+ hours +':'+ minutes +':'+ seconds;</script></body></html>

    Output

    Following is the output of the above program.

    Current Date and Time: 15-12-2024 12:30:45
    

    In the above output, users can see that we are getting the current date and time according to the local time zone.

    Using toLocaleString() method

    Here, we will use the Date object the same way as the above approach, But now we will use the toLocalString() method. It takes two parameters, one is locale, and another is options.

    Locale means the local zone or region for which you want to take data and options is the object which contains many properties.

    Syntax

    Below is the syntax given to get the current date and time using the toLocaleString() method.

    var date =newDate();var current_date_and_time = date.toLocaleString();var current_time = date.toLocaleTimeString();var current_date = date.toLocaleDateString();

    Users can follow the below syntax, if they want to get date and time for any local region.

    var date =newDate();var current_date_and_time = date.toLocaleString('en-US',{ timeZone:'America/New_York'});var current_time = date.toLocaleTimeString('en-US',{ timeZone:'America/New_York'});var current_date = date.toLocaleDateString('en-US',{ timeZone:'America/New_York'});

    Parameters

    • locale : The local parameter represents the Unicode for the local region. If you want to get the current date and time of India, you should pass en-IN, for the US users can pass the en-US.
    • options : The options parameters includes a lots of properties to format the date and time. For example, in above syntax we have written that return the year and day in the numeric format and return the weekday and month in the long format.

    Example

    The below example demonstrate to use the toLocaleString() method to get the get and time for any specific region.

    <html><body><script>var date =newDate();var current_date_and_time = date.toLocaleString();var current_time = date.toLocaleTimeString();var current_date = date.toLocaleDateString();
    document.write('Current Date and Time: '+ current_date_and_time +'<br>');
    document.write('Current Time: '+ current_time +'<br>');
    document.write('Current Date: '+ current_date +'<br>');</script></body></html>

    Output

    Following is the output of the above program.

    Current Date and Time: 12/15/2024, 12:30:45 PM
    Current Time: 12:30:45 PM
    Current Date: 12/15/2024
    

    In the above output, users can see that we are getting the current date and time according to the local time zone.

    The Date class contains many advanced methods to get the date and time. However, users can get the whole date and time string using the built-in methods.

    Users can get date and time information according to their requirements using various methods of date class. Also, toLocaleString() methods allow you to get regional dates and times. Furthermore, it will enable you to format the date and time according to your need by passing the options object as a parameter.

  • JavaScript – Callback Function

    In JavaScript, functions are considered as objects, which means they can be used just like any other value we pass to the function. So, we can pass them as parameters to other functions just like we do with variables or objects. When you pass a function as a parameter, it will be called or even executed within the other function.

    This makes it really flexible because you can decide later what function should be run. When a function is passed like this and then it gets called inside the other function, its known as a callback function. Its basically a way to control when and how a certain piece of code should run.

    Why do we need Callback Functions?

    • Callback functions are really useful when we have to run certain piece of code after some other function execution or middle of any other function’s working. You can simply run after specific task is done as per your need.
    • They come in handy for handling things that dont happen right away, which takes time like loading data from a server or waiting for user input. In JavaScript, these are called asynchronous operations, and callback functions are often used to manage these asynchronous function.
    • Callback function are also used to handle events. For example, you have a function that should run when a user clicks a button or when a page is loaded. You can pass that function as a callback to the event listener, and it will be executed when the event occurs.
    • Callback allow you to use the same function in different situations. which makes easy to handle various tasks without repeating the same code again and again.

    Example of Callback Function

    Following is an example of callback function in JavaScript. In this example, we are passing a function as a parameter to another function and then calling it after 5 seconds.

    <html><head><script>varcallback=function(myCallback){setTimeout(function(){myCallback();},5000);};
             
             document.write("First is displayed");
             document.write("<br>Second is displayed");callback(function(){
                document.write("This is Callback function");});
             document.write("<br>Last is displayed");</script></head></html>

    Output:

    First is displayed
    Second is displayed
    Last is displayed
    

    After 5 seconds, the callback function will be executed and the output will be:

    First is displayed
    Second is displayed
    This is Callback function
    Last is displayed
    

    Callback Function with Parameters

    Following is an example of callback function with parameters in JavaScript. In this example, we are passing a message to the callback function and then displaying it.

    <html><head><script>varcallback=function(myCallback){setTimeout(function(){myCallback("Hello, World!");},5000);};
             
             document.write("First is displayed");
             document.write("<br>Second is displayed");callback(function(message){
                document.write("<br>"+ message);});
             document.write("<br>Last is displayed");</script></head>

    Output

    Following is the output of the above code:

    First is displayed
    Second is displayed
    Last is displayed
    

    After 5 seconds, the callback function will be executed and the output will be:

    First is displayed
    Second is displayed
    Hello, World!
    Last is displayed
    

    What is Callback Hell?

    When you nest too many function inside other functions, The code becomes messy and hard to read and maintain. It happens when you have multiple level of nested callbacks to handle a task one after another this is called as Callback Hell.

    Example of Callback Hell

    Following is an example of callback hell in JavaScript:

    functionstep1(callback){setTimeout(function(){
          console.log("Step 1");callback();},1000);}functionstep2(callback){setTimeout(function(){
          console.log("Step 2");callback();},1000);}functionstep3(callback){setTimeout(function(){
          console.log("Step 3");callback();},1000);}step1(function(){step2(function(){step3(function(){
             console.log("Done!");});});});

    Output

    Following is the output of the above code:

    Step 1
    Step 2
    Step 3
    Done!
  • JavaScript – Base64 Encoding

    Encoding is the process of converting text from one data format to another. In computer science terms,encoding is the process of converting a text into a cipher text. Encoding is different from the Encryption process.

    Base64 encoding is generally used for encoding binary data, such as images, audio, video, etc. It is a group for binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation.

    Base64 encoding is used in many applications, such as email via MIME, and storing complex data in XML or JSON.

    String to Base64 Encoding using btoa()

    A string in base-64 is encoded into Base64-encoded ASCII string using the btoa() function. The syntax for btoa() method is

    btoa(string)
    

    Where, the parameter string is the string to be encoded. The return value is an encoded string.

    Example

    This is an example program to encode a string using btoa() method.

    <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title> Encoding a string in JavaScript.</title></head><body><p id="encode"></p><script>var str ="Tutorials point";
    document.getElementById('encode').innerHTML ='The encoded string for "Tutorials point" is '+window.btoa(str);</script></body></html>

    Output

    Following is the output of the above program.

    The encoded string for "Tutorials point" is VHJ1c3Rpb25zIHBvaW50
    

    You may get different output as the encoded string is different for different strings.

    Base64 Decoding using atob()

    Decoding is the way which can be used to convert the encoded string back to the original string. atob() is an easy method to decode the Base64 encoded string. The syntax for atob() method is

    atob(encodedString)
    

    Where, the parameter encodedString is to be decoded. The return value is the original string.

    Example

    This is an example program to decode a string using atob() method.

    <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title> Decoding a string in JavaScript.</title></head><body><p id="decode"></p><script>var str ="VHV0b3JpYWxzIHBvaW50";
    document.getElementById('decode').innerHTML ='The decoded string for "VHV0b3JpYWxzIHBvaW50" is '+window.atob(str);</script></body></html>

    Output

    Following is the output of the above program.

    The decoded string for "VHV0b3JpYWxzIHBvaW50" is Tutorials point
    

    You may get different output as the decoded string is different for different strings.

  • JavaScript – Data Structures

    Data Structures are the programming constructs which are used to store and organize data. We can write effective efficient programs using these, while performing data operations. JavaScript provides various data structures for different operations. In this tutorial, we will learn about the different data structures in JavaScript.

    Data Structures in JavaScript

    We have the following data structures in JavaScript.

    • Arrays
    • Object
    • Map
    • Set
    • WeakMap
    • WeakSet
    • Stack
    • Queue
    • Linked List

    Arrays

    The array is the most common data structure in every other programming language. In JavaScript, array is a collection of elements. It is not necessary that all elements in the array should be of the same type. We can store different types of data in the array. We can store the number, string, boolean, object, and even another array in the array.

    Example

    Below is the example code given, that shows how to create an array in JavaScript.

    <html><body><p id="output"></p><script>var arr =[1,'John',true,{name:'John', age:25},[1,2,3]];
          document.getElementById('output').innerHTML = arr;</script></body></html>

    Output

    1,John,true,[object Object],1,2,3
    

    Object

    Object is another data structure in JavaScript. It is a pair of two things, key and its value. We can store the data in the form of key-value pairs. We can store the number, string, boolean, object, and even another object in the object.

    Example

    Below is the example code given, that shows how to create an object in JavaScript.

    <html><body><script>var obj ={name:'John', age:25, isMarried:true, address:{city:'New York', country:'USA'}};
          document.write(JSON.stringify(obj));</script></body></html>

    Output

    {"name":"John","age":25,"isMarried":true,"address":{"city":"New York","country":"USA"}}
    

    Map

    Map is a collection of elements and each element is stored as a key-value pair. The key can be of any type, and the value can be of any type. We can store the number, string, boolean, object, and even another map in the map.

    The only difference between map and object in JavaScript is that a map doesn’t support the JSON format, keys in objects have only one type which is string but map supports any type as a key or value, while map maintains order, where as object doesn’t follow any order.

    Example

    Below is the example code given, that shows how to create a map in JavaScript.

    <html><body><p id="output"></p><script>var map =newMap();
          map.set('name','John');
          map.set('age',25);
          map.set('isMarried',true);
          map.set('address',{city:'New York', country:'USA'});let content ='';
          map.forEach((value, key)=>{if(typeof value ==='object'){
                content += key +' : '+JSON.stringify(value)+'<br>';}else{
                content += key +' : '+ value +'<br>';}});
          document.getElementById('output').innerHTML = content;</script></body></html>

    Output

    name : John
    age : 25
    isMarried : true
    address : {"city":"New York","country":"USA"}
    

    Set

    Set is a collection of elements where each element should be different than other (every element should be unique). We can store the number, string, boolean, object, and even another set in the set.

    Example

    Below is the example code given, that shows us how to create a set in JavaScript.

    <html><body><p id="output"></p><script>var set =newSet();
          set.add(1);
          set.add('John');
          set.add(true);let content ='';
          set.forEach(value=> content += value +'<br>');
          document.getElementById('output').innerHTML = content;</script></body></html>

    Output

    1
    John
    true
    

    WeakMap

    WeakMap is a collection of elements where each element is stored as a key-value pair. The key can be of any type, and the value can be of any type. We can store the number, string, boolean, object, and even another weak map in the weak map. The main difference between the map and weak map is that the key of the weak map is weakly held. It means that if the key is not used anywhere else, it will be collected by the garbage collector.

    Example

    Below is the example code given, that shows how to create a weak map in JavaScript.

    <html><body><p id="output"></p><script>var object =[];var weakMap =newWeakMap();var key ={name:'John'};
       weakMap.set(key,25);
       object.push(key);let content ='';
       object.forEach(value=> content += value.name +" "+ weakMap.get(value));
       document.getElementById('output').innerHTML = content;</script></body></html>

    Output

    John 25
    

    WeakSet

    WeakSet is a collection of elements similar to Set, where each element is unique. We can store the number, string, boolean, object, and even another weak set in the weak set. The main difference between the set and weak set is that the elements of the weak set are weakly held. It means that if the element is not used anywhere else, it will be even collected by the garbage collector.

    Example

    Below is the example code given, that shows how to create a weak set in JavaScript.

    <html><body><p id="output"></p><script>var object =[];var weakSet =newWeakSet();var obj ={name:'John'};
       weakSet.add(obj);
       object.push(obj);let content ='';
       object.forEach(value=> content += value.name +'');
       document.getElementById('output').innerHTML = content;</script></body></html>

    Output

    John
    

    Stack

    Stack is a collection of elements where the elements are stored in the order and that order is LIFO(last in first out). We can store the number, string, boolean, object, and even another stack in the stack.

    Example

    Below is the example code given, that shows how to create a stack in JavaScript.

    <html><body><script>classStack{constructor(){this.items =[];}push(element){this.items.push(element);}pop(){if(this.items.length ===0){return'Underflow';}returnthis.items.pop();}}var stack =newStack();
          stack.push(1);
          stack.push(2);
          stack.push(3);
          document.write(stack.pop()); 
          document.write(stack.pop());
          document.write(stack.pop());</script></body></html>

    Output

    321
    

    Queue

    Queue is a collection of elements where the elements are stored in the First In First Out (FIFO) order. We can store the number, string, boolean, object, and even another queue in the queue.

    Example

    Below is the example code given, that shows how to create a queue in JavaScript.

    <html><body><script>classQueue{constructor(){this.items =[];}enqueue(element){this.items.push(element);}dequeue(){if(this.items.length ===0){return'Underflow';}returnthis.items.shift();}}var queue =newQueue();
          queue.enqueue(1);
          queue.enqueue(2);
          queue.enqueue(3);
          document.write(queue.dequeue());
          document.write(queue.dequeue());
          document.write(queue.dequeue());</script></body></html>

    Output

    123
    

    Linked List

    Linked List is a collection of elements where each element is stored as a node. Each node has the data and the reference to the next node. We can store the number, string, boolean, object, and even another linked list in the linked list.

    Example

    Below is the example code given, that shows how to create a linked list in JavaScript.

    <html><body><script>classNode{constructor(element){this.element = element;this.next =null;}}classLinkedList{constructor(){this.head =null;this.size =0;}add(element){var node =newNode(element);var current;if(this.head ===null){this.head = node;}else{
                   current =this.head;while(current.next){
                      current = current.next;}
                   current.next = node;}this.size++;}printList(){var current =this.head;var str ='';while(current){
                   str += current.element +' ';
                   current = current.next;}
                document.write(str);}}var linkedList =newLinkedList();
          linkedList.add(1);
          linkedList.add(2);
          linkedList.add(3);
          linkedList.printList();</script></body></html>

    Output

    1 2 3
  • JavaScript – Recursion

    Recursion is a process in which a function calls itself. It helps when we need to solve a problem that can be break down into smaller problem of the same type.

    What is Recursion?

    The word recursion came from the recurring, meaning comes back to again and again. The recursion function is the function calling itself again and again by changing the input step by step. Here, changing the input by one step means decreasing or increasing the input by one step.

    Whenever a recursive function hits the base condition, the execution stops. Let’s understand what is the base condition by one example. Suppose, we need to find the factorial of a number. We call the factorial function by decreasing the input by 1, and we need to stop whenever the input reaches 1. So, here one works as a base condition.

    How Recursion Works?

    Recursion works on the concept of divide and conquer. It does means we divide the problem into smaller parts and solve them. The recursion function calls itself with the smaller input and solves the problem, and when the base condition is met recursion stops.

    Example of Recursion

    Let us understand how to write a recursive function to find the factorial of a number. The factorial of a positive number n is given as follows −

    Factorial of n (n!) = 1 * 2 * 3 * 4 *... * n
    

    The factorial of a negative number doesn’t exist. And the factorial of 0 is 1

    In the below example, we will demonstrate how to find the factorial of a number using recursion in JavaScript. We create a function fact() with a parameter b that takes a value from the main function as 6.

    • Firstly, we check if the number is equal to 0. If it is true then the program will return 1.
    • In the else-statement, we will check b*fact(b-1), which roughly translates to 6*(6-1).
    • In the next recursion, it will be 5*(5-1) and so on. In this way, the function will resume finding the factorial of a number.
    • The function then prints the value of the factorial of the number entered after the recursion ends.
    <html><body><h2> Factorial using JavaScript recursion </h2><script>// program to find the factorial of a numberfunctionfact(b){// if number is 0if(b ===0){return1;}// if number is positiveelse{return b *fact(b -1);}}const n =6;// calling factorial() if num is non-negativeif(n >0){let res =fact(n);
             document.write(`The factorial of ${n} is ${res}`);}</script></body></html>

    Output

    The factorial of 6 is 720
    

    In the above output, users can see that after recursion we find the factorial of the number to be 720.

  • JavaScript – Date Comparison

    We often need to compare dates in any programming language. In JavaScript the date is one of the data types, and it is common for developers to work with dates while building applications or, writing certain date based programs.

    Let’s understand the need to compare the date with a real-life example. Most of you are using the internet data, and the company sends a message like “2 days left for your data pack validity”. Also, users can see the same notification in the application of network provides. The number of days left is calculated using the date comparison, if we find the difference between the current date and the expiry date we will get the result.

    There are different ways to compare the date in JavaScript. We will discuss some of the methods to compare the date in JavaScript.

    • Using the getTime() method
    • Using the Moment.js diff() method

    Using the getTime() method

    In JavaScript date is represented by the class named Date. You can perform various operations on date objects using the methods of this class.

    To compare two date objects we can use the getTime() method. This method returns the total number of milliseconds from the Thursday 1 January 1970 00:00:00 (epoch time). We can invoke the getTime() method on the both date values and compare the results.

    Syntax

    Following code snippet demonstrates date comparison using the getTime() method −

    let date1 =newDate();let date2 =newDate(2012,11,21);// comparing the datesif( date1.getTime()< date2.getTime()){// date 1 is behind the date2}elseif( date1 > date2 ){// date1 is further to date2}else{// date1 and date2 is same}

    Example

    In the example below, we have created the two new date objects and compared the values (milliseconds) of these two dates since the epoch (,retrieved using the getTime() method) using the if-else statement. We can see the result of the comparison between various dates in the output.

    <html><head></head><body><h4> compare two date by <i> using total milliseconds </i>of both dates.</h4><p id ="output"></p><script>let output0 = document.getElementById("output");functioncompareDates(date1, date2){if( date1.getTime()< date2.getTime()){
                output0.innerHTML += date1 +" is behind the "+ date2 +" <br/> ";}elseif( date1 > date2 ){
                output0.innerHTML += date2 +" is behind the "+ date1 +" <br/> ";}else{
                output0.innerHTML += date1 +" is same as "+ date2 +" <br/> ";}}// calling the function for different expressions
          output0.innerHTML +="<br/>";let date =newDate();let date0 =newDate(2012,11,21);compareDates( date, date0 );
          output0.innerHTML +="<br/>";
          date0 =newDate();compareDates( date, date0 );</script></body></html>

    Using the Moment.js diff() method

    JavaScript contains various libraries; one of them is Moment.js which is also used to manage the date and time.

    This library has a method named diff(), which gives the difference between two dates in years, months, days, hours, minutes, seconds, milliseconds, etc. We can use the seconds to find the difference between the two dates.

    Note: Before using the Moment.js library, we need to add Moment.js library or just add CDN to the tag of the HTML code.

    Syntax

    Following is the syntax of the moment.diff() method −

    diff( date, unit );

    Where,

    • date: It is the date (object) which we need to compare with the current moment object.
    • unit: It is the unit in which we want to find the difference. It can be years, months, days, hours, minutes, seconds, milliseconds, etc.

    Example

    In the example below, we have created the two date objects using the moment library. We invoked the diff() method on these two objects, to compare them and render the message accordingly.

    <html><h4> compare two dates using<i>diff()</i> method of Moment.js.</h4><p id ="output"></p>let output = document.getElementById("output");functioncompareDates(date1, date2){if( date1.diff(date2,"seconds")<0){
                output.innerHTML += date1.format('yy-MM-DD, HH:mm:ss')+" is behind the "+ date2.format('yy-MM-DD, HH:mm:ss')+" <br/> ";}elseif( date1.diff(date2,"seconds")>0){
                output.innerHTML += date2.format('yy-MM-DD, HH:mm:ss')+" is behind the "+ date1.format('yy-MM-DD, HH:mm:ss')+" <br/> ";}else{
                output.innerHTML += date1.format('yy-MM-DD, HH:mm:ss')+" is same as "+ date2.format('yy-MM-DD, HH:mm:ss')+" <br/> ";}}// calling the function for different expressions
          output.innerHTML +="<br/>";let date1 =moment();let date2 =moment("2024-11-21");compareDates(date1, date2);
          output.innerHTML +="<br/>";
          date2 =moment();compareDates(date1, date2);</script></html>

    To run this program you need to include the following script in the code −

    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.30.1/moment.min.js"></script><script >

    Conclusion

    We have used the default Date() class to compare the dates in the first section of the tutorial. Also, we have used the Moment.js library method to make a comparison. The moment makes it easy for the developer to play with the dates.