Blog

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

  • 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;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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));&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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)=&gt;{if(typeof value ==='object'){
            content += key +' : '+JSON.stringify(value)+'&lt;br&gt;';}else{
            content += key +' : '+ value +'&lt;br&gt;';}});
      document.getElementById('output').innerHTML = content;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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=&gt; content += value +'&lt;br&gt;');
      document.getElementById('output').innerHTML = content;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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());&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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());&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    1 2 3
  • 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});}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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.

  • 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 +" &lt;br/&gt; ";}elseif( date1 &gt; date2 ){
            output0.innerHTML += date2 +" is behind the "+ date1 +" &lt;br/&gt; ";}else{
            output0.innerHTML += date1 +" is same as "+ date2 +" &lt;br/&gt; ";}}// calling the function for different expressions
      output0.innerHTML +="&lt;br/&gt;";let date =newDate();let date0 =newDate(2012,11,21);compareDates( date, date0 );
      output0.innerHTML +="&lt;br/&gt;";
      date0 =newDate();compareDates( date, date0 );&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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')+" &lt;br/&gt; ";}elseif( date1.diff(date2,"seconds")&gt;0){
            output.innerHTML += date2.format('yy-MM-DD, HH:mm:ss')+" is behind the "+ date1.format('yy-MM-DD, HH:mm:ss')+" &lt;br/&gt; ";}else{
            output.innerHTML += date1.format('yy-MM-DD, HH:mm:ss')+" is same as "+ date2.format('yy-MM-DD, HH:mm:ss')+" &lt;br/&gt; ";}}// calling the function for different expressions
      output.innerHTML +="&lt;br/&gt;";let date1 =moment();let date2 =moment("2024-11-21");compareDates(date1, date2);
      output.innerHTML +="&lt;br/&gt;";
      date2 =moment();compareDates(date1, date2);&lt;/script&gt;&lt;/html&gt;</pre>

    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.

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

  • 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);</pre>

    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!

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

    What is Throttling?

    Throttling is a technique that limits how many times a function can be called in a specific period of time. It improves the speed and responsiveness of web sites by implementing event listeners that do heavy or expensive tasks such as animations, scrolling, resizing, getting data, etc.

    For example, if you have a function that collects data from an API every time the user scrolls down the page, you can throttle it so that it only makes one request per second instead of hundreds as the user scrolls. This prevents you from overloading the server or browser with unnecessary queries, hence reducing bandwidth usage.

    Why use Throttling in JavaScript?

    JavaScript Throttling can increase application performance by setting a set rate of function execution.

    A Throttle function generates function calls at predefined intervals, keeping the program from lagging or becoming overloaded. As a result the server will handle requests in a certain order and at a predetermined time.

    Implement Throttling in JavaScript

    Here are the steps you can follow to create Throttling in JavaScript −

    • Create a Throttle Function: Define a function that accepts a callback and a delay to adjust the execution frequency over time.
    • Track Last Run Time: Save the timestamp from the last function called to see if the wait has been completed.
    • Check Time Interval: For each trigger, compare the current time to the last execution time; execute only if enough time has passed.
    • Return the Throttled Function: Create a new function that only executes the old callback when the specified time period is met.

    How Throttling work in JavaScript?

    Let us look at an example to better understand JavaScript and throttling. Consider this scenario: we have added a scroll event listener to a web page and configured it such that when the user scrolls, he sees the desired information.

    But if the user scrolls frequently, the web page will soon generate hundreds of events. To address this issue, we will throttle the event so that it is only triggered after a second of the previous event. This results in a single callback every second. The end user will see the same results, but they will be far more computationally efficient.

    Now Let us understand it with the help of the example below. In the following example, we will use the throttle mechanism to distinguish between throttling and non-throttling conditions.

    Without throttling Function

    Without throttling, a function can be called too quickly, causing performance issues, excessive resource usage and a possibly unpleasant user experience.

    Example

    In this example, we add an event listener to a button without throttling. Each click triggers the callback immediately and sending the message ‘button is clicked’ to the console with no rate limit.

    <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" 
       content="width=device-width, 
       initial-scale=1.0"><title>Document</title></head><body><button id="pressButton">Press Me</button><script>
    
      // Selected button with the given id
      const button = document.
      querySelector("#pressButton");
      
      // Add event listener to the button 
      // to listen to the click event
      button.addEventListener("click", () =&gt; {
         console.log("The button has been pressed");
      });
    </script></body></html>

    Output

    This will produce the below result −

    JavaScript Without Throttling

    With Throttling Function

    Throttling limits the number of function invocations. For example, you could choose to execute a function at most once per 1500 milliseconds. This prevents the function from being called too frequently, which results in smoother performance.

    Example

    In this example we throttle a button click event by limiting the ‘Button has been pressed!’ log to once per 1500 milliseconds, regardless of how quickly we click.

    Following is the simple demonstration with throttling function −

    <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" 
    
      content="width=device-width, 
      initial-scale=1.0"&gt;&lt;title&gt;Document&lt;/title&gt;&lt;/head&gt;&lt;body&gt;&lt;button id="pressButton"&gt;Press Me&lt;/button&gt;&lt;script&gt;
      const button = document.querySelector("#pressButton");
      // Throttling Function
      const limitFunctionCall = (callback, waitTime) =&gt; {
         // Previously called time of the function
         let lastCalled = 0;
         return (...args) =&gt; {
            // Current called time of the function
            let currentTime = new Date().getTime();
            // Logging the difference
            // between previously called and current called timings
            console.log("Time difference:", currentTime - lastCalled, "Wait time:", waitTime);
            // If the difference is greater than waitTime, call the function again
            if (currentTime - lastCalled &gt; waitTime) {
               lastCalled = currentTime;
               // Return the function 
               return callback(...args);
            }
         }
      }
      button.addEventListener("click",
         limitFunctionCall(() =&gt; {
         console.log("Button has been pressed!")
         }, 1500));
    &lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    This will generate the below result −

    [Log] Time difference: - 1729667433711 - "Wait time:" - 1500 (example.html, line 28)
    [Log] Button has been pressed! (example.html, line 41)
    [Log] Time difference: - 1016 - "Wait time:" - 1500 (example.html, line 28)
    [Log] Time difference: - 1599 - "Wait time:" - 1500 (example.html, line 28)
    [Log] Button has been pressed! (example.html, line 41)
    [Log] Time difference: - 416 - "Wait time:" - 1500 (example.html, line 28)
    [Log] Time difference: - 866 - "Wait time:" - 1500 (example.html, line 28)
    

    Use cases for Throttling

    A throttle function operates at a fixed rate to prevent the app from lagging or overwhelming the server when performing a time-consuming task or request. The following are some common applications for the throttle function.

    • In Gaming: In games, players press buttons to perform actions like punching and shooting. If they press too quickly we can use throttle to limit the frequency of activities like once per second.
    • Ads and Scrolling: When users scroll we regularly load and animate content. Scrolling too quickly can lead to the app to slow down. Throttling keeps things functioning smoothly by limiting actions.
    • Button Clicks:Some programs, like those used at ATMs, take longer to complete tasks. Throttling prevents users from pressing the button too quickly.
    • Pointer (Mouse) Events:Moving the mouse can lead to events to occur too frequently. Throttling controls how frequently these events occur to ensure that everything runs properly.
    • API Calls: If an app makes too many API requests quickly it can slow down loading. Throttling limits requests to prevent problems.

    Summary

    JavaScript Throttling is an approach that restricts function execution to a specific number of times. It ensures that a function is executed on a consistent basis, regardless of how many times it has been invoked.

  • Temporal Dead Zone

    The Temporal Dead Zone (TDZ) is a JavaScript concept which explains how variables behave when let and const are used. It means that before a variable can be used it needs to be defined. This takes place in between the declaration of the variable and the start of the block like a function or loop.

    Why Does Temporal Dead Zone Happen?

    When you declare a variable in JavaScript using let or const, a space is created for it. But until the variable is defined, it stays in the “dead zone.” If you try to use JavaScript before the declaration, it will raise an error.

    • Block scope: It applies to the let and const variables. This means they are only allowed in the block where they are declared.
    • Cannot Access: A variable cannot be accessed until it is declared in the same block. This prevents errors in your code.

    Examples of Temporal Dead Zone

    Following are some examples of Temporal Dead Zone −

    Example 1

    In this example, we will try to log myVar before it is declared. JavaScript throws a ReferenceError because myVar is inside the TDZ. You have to define myVar before you can use it.

    // This will throw an error
    console.log(myVar);let myVar =5;

    Output

    This will generate the below result −

    ReferenceError: Cannot access 'myVar' before initialization
    

    Example 2

    In the MyFunction function, we tried to log myNum before declaring it. Because myNum has not yet been defined it remains in the TDZ when we call the function which is causing an error.

    functionmyFunction(){// This will throw an error
       console.log(myNum);let myNum =10;}myFunction();

    Output

    As a result, the following will happen −

    ReferenceError: Cannot access 'myNum' before initialization
    

    Example 3

    In this example we try to log myConst before using it in an if block. As with let is the variable in the TDZ, which causes an error.

    if(true){// This will throw an error
       console.log(myConst);const myConst =20;}

    Output

    This will lead to the following result −

    ReferenceError: Cannot access 'myConst' before initialization
    

    How to avoid TDZ in JavaScript?

    Preventing TDZ issues needs declaring variables before trying to access them. By giving as a way to detect possibilities when a variable is accessed before it is declared, it promotes more easy and predictable code. Understanding TDZ reduces the possibility of JavaScript runtime errors and facilitates the development of code that follows best practices.

    For avoiding the Temporal Dead Zone (TDZ) in JavaScript you can follow the simple rules defined below −

    Declare Variables at the Beginning

    Declare your variables at the start of a block (like a function or an if statement) to be sure they are available when you need them. This keeps them outside of the TDZ.

    functionexampleFunction(){// Declare at the toplet count =0; 
       console.log("Initial count:", count); 
       count =5;
       console.log("Updated count:", count); 
       console.log("End of exampleFunction");}// Example usage:exampleFunction();

    Output

    This code will produce the following outcome −

    Initial count: 0
    Updated count: 5
    End of exampleFunction
    

    Avoid Using Variables Before Declaration

    An easy method to avoid TDZ refers to is to avoid using variables before they are defined. Check your code to ensure that no variables are called or recorded before they are specified as let or const.

    // Declare the variable firstlet num =10;// Now safe to use
    console.log(num);

    Output

    This will produce the following output −

    10
    

    Use var Only If Necessary

    Unlike let and const, variables declared using var are set to the top of their scope and initialized with undefined, so they do not have a TDZ. But it is preferable to use var only when absolutely necessary because it introduces additional defining issues that can make code difficult to understand.

    // No error, but outputs undefined
    console.log(a);var a =5;

    Output

    This will create the below outcome −

    undefined
    

    Organize Code to Minimize TDZ Errors

    To keep your code clean and organized you should place variable declarations at the beginning of your functions or blocks. This way, they are disclosed early and ready when you need them.

    functioncalculateArea(radius){
       console.log("Starting calculation...");if(radius >0){
    
      console.log("Radius is greater than 0, proceeding with calculation.");// Declare variables before using themlet pi =3.14;let area = pi * radius * radius;
      console.log("Calculated area:", area);return area;}else{
      console.log("Radius is not greater than 0, returning 0.");}return0;}// Example usagecalculateArea(5);calculateArea(-3);</pre>

    Output

    This will lead to the following outcome −

    Starting calculation...
    Radius is greater than 0, proceeding with calculation.
    Calculated area: 78.5
    Starting calculation...
    Radius is not greater than 0, returning 0.
  • Supercharged Sorts

    The Array.sort() method in JavaScript is an essential tool for any developer that works with data sets. While sorting a list of numbers or words is simple, sorting arrays of objects based on numerous criteria becomes more complicated. In this chapter, we will look at various ways for making full use of Array.sort() for creating complicated, multi-property sorts.

    Basics of Sorting

    Before we go into advanced methods, we will go over the fundamentals of how Array.sort() operates. The sort() method accepts an optional callback function that specifies the sorting order. This comparator function accepts two parameters (a and b) and returns a numerical value −

    • If the returned value is negative, sort a before b.
    • If the returned value is positive, sort b before a.
    • If the returned result is 0, the order of a and b is unaltered.

    Below is a very simple JavaScript example code for sorting an array of numbers in the ascending order −

    const numbers =[12,7,19,3,8,5,10,15];// Sorting the array in descending order
    numbers.sort((a, b)=> b - a);// Printing the sorted array
    console.log(numbers);

    Output

    This will generate the below result −

    [ 19, 15, 12, 10, 8,  7,  5,  3 ]
    

    The comparator (a, b) => a – b returns a negative value when a < b, a positive value whenever a > b, and 0 when a === b, which fulfills the contract Array.sort() requires.

    Chaining Multiple Sort Criteria

    Things become more interesting when we have to sort an array of objects based on multiple properties. Look at an array of items.

    const products =[{ name:'Smartphone', price:699.99, rating:4.7},{ name:'Headphones', price:129.99, rating:4.3},{ name:'Tablet', price:399.99, rating:4.1},{ name:'Smartwatch', price:199.99, rating:4.5},];

    Assume we want to arrange these products by price in ascending order, followed by rating in descending order as a tiebreaker for items with identical prices. We can chain the comparators together using the boolean OR operator (||) −

    products.sort((a, b)=> 
       a.price - b.price || b.rating - a.rating
    );

    Here’s how it works −

    • The first comparator, a.price minus b.price, is evaluated. If the prices differ, it yields a non-zero value and the || short-circuits, resulting in price sorting.
    • If the prices are the same, a.price – b.price equals 0. The || then evaluates the second comparator, b.rating – a.rating, and sorts by descending rating.

    This pattern allows us to chain as many comparators as we need −

    products.sort((a, b)=> 
       a.price - b.price || 
       b.rating - a.rating ||
       a.name.localeCompare(b.name));

    Items with the same price and rating are now sorted alphabetically by name to determine the final tiebreaker.

    Creating Reusable ‘sortBy’ Functions

    While the chained comparator approach is effective, it can result in difficult-to-read and code that is repetitive if we need to sort by the same criteria multiple times. We can make our code more modular by introducing generic “sortBy” functions for each property −

    constbyPrice=(a, b)=> a.price - b.price;constbyRating=(a, b)=> b.rating - a.rating;constbyName=(a, b)=> a.name.localeCompare(b.name);
    
    products.sort((a, b)=>byPrice(a, b)||byRating(a, b)||byName(a, b));

    This improves the sort chain’s readability and allows each comparator to be reused. But we are still writing some repetitive code for each property. Let’s see if we can improve.

    Higher-Order ‘sortBy’ Function

    To increase re-usability, we can define a higher-order ‘sortBy’ function that accepts a property name and returns a comparator function −

    functionsortBy(prop){return(a, b)=> 
    
    a[prop]&lt; b[prop]?-1:
    a[prop]&gt; b[prop]?1:0;}const byPrice =sortBy('price');constbyRating=(a, b)=&gt;sortBy('rating')(b, a);const byName =sortBy('name');</pre>

    The sortBy function is considered higher-order because it returns another function. It uses the closure method to capture the prop argument within the scope of the returning comparator.

    This approach allows us to simply develop comparators for any property. To sort in descending order, the byRating comparator reverses the usual (a, b) order.

    Here is the complete ES6 version with the help of arrow functions −

    constsortBy=(prop)=>(a, b)=>
      a[prop]< b[prop]?-1: 
      a[prop]> b[prop]?1:0;
    
    products.sort((a, b)=>sortBy('price')(a, b)||sortBy('rating')(b, a)||sortBy('name')(a, b));

    Summary

    In this chapter, we went over numerous ways for improving your JavaScript sorting skills.Combining several sort criteria with boolean OR logic.Refactoring Comparators into Reusable "sortBy" Functions.Developing a higher-order "sortBy" function to maximize versatility.Understanding and following these patterns will allow you to efficiently sort arrays of objects based on many properties while writing clean and maintainable code.