Blog

  • 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.

  • JavaScript – Upload Files

    We all know that there is a common task in web development which is uploading files to a server. Even though the most common way to submit files is using forms, there are various methods as well. In this chapter we will cover three main approaches given below −

    • Using FormData with fetch or $.ajax
    • Using XMLHttpRequest
    • Using a Plugin for Simplified Upload

    Let us discuss above approaches in detail in the below section.

    Using FormData with Fetch or $.ajax

    The FormData object can be utilized to create a collection of key-value pairs that can be transmitted using network queries (like get or $.ajax). As it allows file uploading without the need for an HTML form, FormData is flexible and useful for many kinds of applications.

    // Create a new FormData objectvar formData =newFormData();// Append the file to the FormData object
    formData.append('pictureFile', pictureInput.files[0]);// Use $.ajax to send the file
    $.ajax({// URL of the server to upload to 
       url:'upload.php',        
       type:'POST',// Necessary for file upload 
       processData:false,       
       contentType:false,// Expected response format
       dataType:'json',// FormData containing the file
       data: formData            
    });

    Output

    If the file has been uploaded successfully si the server will return a JSON object with details like −

    {
       "status": "success",
       "message": "File uploaded successfully.",
       "filePath": "uploads/picture.jpg"   
    }
    

    If something goes wrong (such as if the file is too large or is not in the correct format), the server may send an error JSON object like this −

    {
       "status": "error",
       "message": "File upload failed. Please try again."
    }
    

    Using XMLHTTPRequest

    Another way to upload files without using forms is with XMLHTTPRequest. The file data can be sent directly using the POST request body. This more “manual” technique gives you more control.

    // Get the form element var form = document.getElementById('the-form');
    
    form.onsubmit=function(){var formData =newFormData(form);// Append file to the FormData
       formData.append('file', file);var xhr =newXMLHttpRequest();// Set up request
       xhr.open('POST', form.getAttribute('action'),true);// Send the formData with the file
       xhr.send(formData);// Prevent actual form submissionreturnfalse;}

    Output

    If the upload is successfully processed, the server can reply with something like this −

    {
       "status": "success",
       "message": "File uploaded successfully.",
       "filePath": "/uploads/myfile.jpg" 
    }
    

    The server will respond with the following if there is a problem (for example, an invalid file type or a very large file size) −

    {
       "status": "error",
       "message": "File upload failed. Please try again."
    }
    

    Using a Simple Upload Plugin

    The simpleUpload plugin uses a jQuery-based method that makes file uploading very easy. This plugin handles all the setup so you can focus on the upload behavior and server-side handling.

    <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>File Upload</title><!-- Include jQuery --><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script><!-- Use simpleUpload plugin --><script src="path/to/jquery.simpleUpload.js"></script></head><body><h2>Upload a File</h2><!-- File input field --><input type="file" name="file" id="simpleUpload" multiple><!-- Button to trigger upload --><button type="button" id="upload">Upload</button><script>
          // JavaScript to handle the file upload
          $(document).ready(function() {
             $('#simpleUpload').simpleUpload({
                // Server endpoint
                url: 'upload.php',            
                trigger: '#upload',            
                
                // Success handler
                success: function (data) {     
                   alert('Successfully Uploaded');
                },
                // Optional error handler
                error: function (error) {      
                   alert('Upload failed. Please try again.');
             }
          });
       });
       </script></body></html>

    Output

    On success the page will display −

    Successfully Uploaded
    

    On failure the page will display −

    Upload failed. Please try again.
    

    Summary

    Each of these methods offers a unique way to upload files without a form. FormData that uses $.ajax or fetch is easy to use and works with modern JavaScript. XMLHTTPRequest provides more control but requires more setup. With just jQuery and the plugin, the SimpleUpload Plugin is simple to use. As each method can be used in a number of contexts so you can select the one that best suits your requirements of the project.

  • JavaScript – Truthy/Falsy Values

    Truthy & Falsy Values

    In JavaScript, true and false values are related to boolean evaluation. Every value in JavaScript has an inherent boolean “truthiness” or “falsiness,” which means it can be determined as true or false in boolean contexts like conditional expressions and logical operators.

    • Truthy Values: When a value is converted to a boolean it returns true. Truthy values are non-empty strings, non-zero numbers, arrays, objects and functions.
    • False values: These are defined as those that are not true. For example, 0, null, undefined, NaN, false (a boolean value) and a blank string (“”).

    Example

    Let us use a scenario and a simple JavaScript method to see if a user has a valid subscription. We assume that only new users have the subscriptionDays field. This field is not available to old users, but it can be set to 0 by new users to indicate that their subscription has expired.

    Here is the code −

    // old user without subscriptionDaysconst userOld ={
       name:"Alisha",
       email:"[email protected]"};// new user with active subscriptionconst userNewWithSubscription ={
       name:"Shital",
       email:"[email protected]",
       subscriptionDays:30};// new user with expired subscriptionconst userNewWithoutSubscription ={
       name:"Chetan",
       email:"[email protected]",
       subscriptionDays:0};functiondisplaySubscriptionStatus(user){// Explicitly check if subscriptionDays is not undefinedif(user.subscriptionDays !==undefined){if(user.subscriptionDays >0){
             console.log(`User has ${user.subscriptionDays} days of subscription left.`);}else{
          console.log("User's subscription has expired.");}}else{
          console.log("User does not have a subscription.");}}displaySubscriptionStatus(userOld);displaySubscriptionStatus(userNewWithSubscription);displaySubscriptionStatus(userNewWithoutSubscription);

    Output

    This will generate the below result −

    User does not have a subscription.
    User has 30 days of subscription left.
    User's subscription has expired.
    

    Truthy vs Falsy Values in JavaScript

    In addition to a type each value has an underlying Boolean value, which is generally classified as true or false. Some of the rules defining how non-Boolean values are translated to true or false values are unusual. Knowing the principles and their impact on comparison is helpful while debugging JavaScript applications.

    Below are the values that are always falsy −

    • false
    • 0 (zero)
    • -0 (minus zero)
    • 0n (BigInt zero)
    • ”, “”, “ (empty string)
    • null
    • undefined
    • NaN

    And everything else is truthy. Which includes −

    • ‘0’ (a string containing a single zero)
    • ‘false’ (a string containing the text false)
    • [] (an empty array)
    • {} (an empty object)
    • function(){} (an empty function)

    As a result only one value can be used within the conditions. For example −

    if(value){// value is truthy}else{// value is falsy// it can be false, 0, '', null, undefined or NaN}

    Dealing with Truthy or Falsy Values

    Even for experienced programmers, it can be difficult to figure out what is true or false in code. It will be very challenging for beginners and those switching from another programming language! But you can find the most difficult errors while working with true and false numbers by following three simple steps. Let’s discuss each step separately in the below section −

    Avoid Direct Comparisons

    Comparing two truthy and falsy values is rarely required because one value is always equivalent to true or false −

    // instead ofif(a ==false)// runs if x is false, 0, '', or []// use the below codeif(!x)// ...// runs if x is false, 0, '', NaN, null or undefined

    Use === Strict Equality

    When comparing values you can use the === strict equality (or!== strict inequality) comparison to prevent type conversion problems −

    // instead ofif(a == b)// runs if x and y are both truthy or both falsy// e.g. x = null and y = undefined// useif(a === b)// runs if x and y are identical...// except when both are NaN

    Converting to Actual Boolean Values

    In JavaScript, you can use a double-negative!! or the Boolean constructor to change any value into an actual Boolean value. This allows you to be positive that only false, 0, “”, null, undefined, and NaN will produce a false −

    // instead ofif(x === y)// This will run if x and y are same...// except when both are NaN// useif(Boolean(x)===Boolean(y))// orif(!!x ===!!y)// This will run if x and y are same...// including when either or both are NaN

    When a truthy value is given to the Boolean constructor, it returns true; when a falsy value is passed, it returns false. When paired with an iteration method, this can be helpful. For example −

    const truthy_values =[false,0,``,'',"",null,undefined,NaN,'0','false',[],{},function(){}].filter(Boolean);// Filter out falsy values and log remaining truthy values
    console.log(truthy_values);

    Summary

    Truthy and falsy values allow you to write ternary operators and simple JavaScript conditions. But never forget about the edge cases. A single empty array or NaN variable could lead to many hours of troubleshooting!

  • JavaScript – tRPC Library

    tRPC is a type-safe TypeScript module that uses the RPC API design to process API requests and return results.

    RPC refers to Remote Procedure Call. The tRPC builds on RPC. RPC is an architectural method for creating REST-like APIs. RPC replaces the Fetch and REST APIs.

    What is tRPC?

    As the name suggests, tRPC adds a type-safe layer to the RPC architectural framework. Traditionally, we used RESTful APIs. It supports GET, POST, PULL, and other request types. The tRPC has no request types.

    Every request to the tRPC back end passes through a query system, which returns a response based on the input and query.

    However, tRPC and react-query provide built-in functions for processing requests. Each request is processed the same. It depends on whether the API endpoint accepts an input, throws an output or modifies it.

    When using REST you create a main folder called /API and then route files within it. There is no requirement for a folder with a large number of files with tRPC. You will need a few built-in functions and a simple react-query system.

    You do not need to call retrieve() process the output and so forth. As you will see tRPC uses URLs to describe individual queries.

    Need of tRPC

    The tRPC library makes RPC types secure. It implies that your client cannot send data that the server cannot accept. I cannot assign a string to a number-based property.

    If the client tries to do so you will immediately receive an error message stating “Invalid Type”. If the data types do not match the IDE and browsers will generate problems.

    JavaScript applications rely significantly on type safety. So tRPC takes advantage of TypeScript. This reduces route building and back-end processes.

    The tRPC requires the Zod library. It helps tRPC construct the data schema for each route. A schema is an object that contains properties and their matching data types.

    For example, if an API route needed the user’s information you would create an object on the back end and provide a datatype to each property with Zod.

    On the front end tRPC will ensure that the data provided by the user or API request matches the data types recorded at the back end. The tRPC makes use of this type of secure integration between the front and back ends.

    Usage of tRPC

    It only takes a few seconds to launch an Express server and start creating tRPC routes and queries. Traditionally the client-side (front-end) and server-side (back-end) were separate. So we follows that separation for this example. Let’s start by creating the client side with React and connecting it to the server side with Express via CORS.

    Folder Structure

    First, set up a directory called tRPC Demo. Inside this directory, set up a new directory called trpclibrary to divide up the client and server sides, which will be executed as a library later.

    Your server (Express) and client (React) will be placed under the trpclibrary directory soon.

    Insert a package.json file into the tRPC Demo root directory with the following code to connect all of the folders and run the client and server-side with a single command.

    {"name":"trpclibrary","version":"1.0.0","main":"index.js","license":"MIT","private":true,"scripts":{"start":"concurrently \"wsrun --parallel start\""},"workspaces":["trpclibrary/*"],"devDependencies":{"concurrently":"^5.2.0","wsrun":"^5.2.0"}}

    After completing the package.json in the root directory, you can set up your Express server in the trpclibrary folder.

    Use cd <folder_name> to go to a folder in the terminal and execute instructions. In this case, you are at the root directory. So, cd.\trpclibrary can help you. You can also use the Visual Studio Code terminal.

    You can use the npx create-mf-app starter command to launch your server using a pre-defined template, saving you time.

    PSC: \Users\abc\Desktop\tRPC-Demo\trpclibrary> npx create-mf-app
    ? Pick the name of your app: server-side
    ? Project Type:API Server
    ? Port number:3005? Template: express
    Your 'server-side' project is ready to go.
    
    Next steps:
    
     cd server-side
     npm install
     npm start
    

    You may see errors indicating that you do not have Express or other libraries installed. Relax because you can install all of the necessary libraries.

    After we have created the server, let us create the client with React and the same command in the same trpclibrary directory.

    PSC: \Users\abc\Desktop\tRPC-Demo\trpclibrary> npx create-mf-app
    ? Pick the name of your app: client-side
    ? Project Type: Application
    ? Port number:3000? Framework: react
    ? Language: typescript
    ?CSS: Tailwind
    ? Bundler: Webpack
    Your 'client-side' project is ready to go.
    
    Next steps:
    
     cd client-side
     npm install
     npm start
    

    Your React client-side is ready now. But you can feel overwhelmed by the number of errors related to modules and packages. So, let us start by downloading them.

    I am using yarn, and I encourage that you do the same. In the trpcDemo root directory, run the yarn command.

    Also use the cd.. command to exit the current directory and enter the outside one.

    The TS Configuration file may not exist on either the server or the client side. So I recommend using the npx tsc –init command in both directories.

    PS C: \Users\abc\Desktop\tRPC-Demo\trpclibrary> npx tsc --init         
    
    Created a new tsconfig.json with:                                                                                       
                                    TS 
      target: es2016
      module: commonjs
      strict: true
      esModuleInterop: true
      skipLibCheck: true
      forceConsistentCasingInFileNames: true
    
    You can learn more at https://aka.ms/tsconfig
    

    You must now install tRPC, CORS, and Zod on your project’s server side.

    PSC: \Users\abc\Desktop\tRPC-Demo\trpclibrary> yarn add @trpc/server zod cors 
    yarn add v1.22.22[1/4] Resolving packages...[2/4] Fetching packages...[3/4] Linking dependencies...
    "workspace-aggregator-b6ab05ef-dbef-4a8e-831d-1f0ec5e2a670 > server-side > ts-node@1
    warning pes/node@*".[4/4] Building fresh packages...
    success Saved lockfile.
    success Saved 3newdependencies. info Direct dependencies
    info All dependencies
    @trpc/[email protected]
    [email protected]
    [email protected]
    Done in15.15s.

    Next, install @trpc/client, @trpc/react-query, @tanstack/react-query, @trpc/server, and Zod for the client. You will use the same “yarn add <package_names>” command.

    This time, I will not share the screenshot. Refer to the previous procedures and try to download them.

    We have finished most of the installations and setups. Your folder structure should look like this:

    tRPC-Demo
     trpclibrary
        client-side (React App Folder)
        server-side (Express Server Folder)
     package.json