Category: Advanced Chapters

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

  • SQL CRUD Operations

    This chapter will show the CRUD operations on a JavaScript object. The operations are Create, Read, Update, and Delete. We can create, modify, take input, and delete objects with these actions. A JavaScript object consists of a collection of keys, values, or properties/attributes, and entries. Values can be any type of data, including arrays, JavaScript functions, and more.

    CRUD Operations

    Create, read, update, and delete is what CRUD stands for. These are permanent storage’s four primary purposes. Also, any function that is carried out in relational database applications and translated to a typical HTTP method, SQL statement, or DDS action can be denoted by any letter in the acronym.

    • CREATE Operations: To create a new record, execute the INSERT statement.
    • READ the Steps: Uses the primary keynoted in the input parameter to read the table records.
    • UPDATE Procedures: Uses the primary key that has been specified for a record in the WHERE clause of the statement to execute a UPDATE statement on the table.
    • DELETE processes: Removes a specific WHERE clause row.

    Syntax

    Here is the syntax for using CRUD operations in JavaScript −

    // Creating an Objectconst circle ={
       radius:10,area:function(){return Math.PI*this.radius *this.radius;}};

    CREATE Operation

    This operation is the process of creating an object or giving it with a new property. The following methods can be used to generate the object:

    • Using Object Constructor: This function allows you to create and initialize an object. The return value is assigned to a variable. The variable has a reference to the new object.
    • Using object literals: Making use of object literals Use a list of key-value pairs separated by a comma (“,” to build an object).

    Syntax

    Here is the syntax for create operation in Javascript −

    // Using Object Constructorconst obj =newObject();// Using Object Literalsconst obj ={
       key1 : value1
    }

    Example

    In the below example we will create an object with the help of the above two methods.

    const box ={ 
       height:25, 
       breadth:20,volume:function(){returnthis.height *this.breadth;}};const cube =newObject(); 
    cube.edge =10; 
    cube.volume=function(){returnthis.edge *this.edge;}; 
    
    cube.edge =15; 
    console.log(box,"Volume of the box: "+ box.volume()); 
    console.log(cube,"Volume of the cube: "+ cube.volume());

    Output

    This will produce the below result −

    { height: 25, breadth: 20, volume: [Function: volume] } Volume of the box: 500
    { edge: 15, volume: [Function (anonymous)] } Volume of the cube: 225
    

    Read Operation

    The read operation is the process of reading and accessing the values and properties of an object. The methods listed below can be used −

    • Using Destructuring Assignment: To unpack object values and allocate them to other variables in JavaScript, use the syntax known as “using destructuring assignment.”
    • Using Dot Notations: Making use of Dot Notations this syntax makes it possible to access the object attributes and items by using a [dot] or “.” symbol.
    • Using Bracket Notation: The property name enclosed in brackets “[ ]” can be retrieved from the object property using Bracket Notation.

    Syntax

    Below is the syntax for Read operation in Javascript −

    // Using dot notation
    console.log(obj.prop1)// For Nested objects
    console.log(obj.prop1.subProperty)// Using Square Brackets 
    console.log(obj['prop2'])// Using Object Destructuringconst{ key1 }= obj1;                                      
    console.log(key1);

    Example

    In the below example we will use another methods for reading the object property values.

    // Creating a new object const box ={ 
       height:25, 
       width:20,volume:function(){returnthis.height *this.width;}};const{ height }= box; 
    console.log("Box height: "+ height); 
    console.log("Box width: "+ box['width']); 
    console.log("Box volume: "+ box.volume());

    Output

    This will generate the following output −

    Box height: 25
    Box width: 20
    Box volume: 500
    

    Update Operation

    It shows that you can see and change an object’s properties. These methods can be used −

    • Using Destructuring Assignment: To unpack object values and allocate them to other variables in JavaScript, use the syntax known as “using destructuring assignment.”
    • Using Dot Notations: Making Use of Dot Notations this syntax makes it possible to access the object attributes and items by using a [dot] or “.” symbol.

    Syntax

    Below is the syntax for Update operation in Javascript −

    // Using dot notation
    obj.prop1 ="newValue";// Using brackets
    obj['prop2']="value2";

    Example

    This example shows the manipulation of the Object properties and their related values.

    const box ={ 
       height:25, 
       depth:20,volume:function(){returnthis.height *this.depth;}};// Display Initial Volume 
    console.log("Initial Volume: "+ box.volume());// Update Values // Using dot notation 
    box.height =50;// Using brackets notation 
    box['depth']=40;// Display Updated Volume 
    console.log("Updated Volume: "+ box.volume());

    Output

    This will generate the below result −

    Initial Volume: 500
    Updated Volume: 2000
    

    Delete Operation

    A delete operation is the process of removing an object property. Below is one method for doing it −

    • Using the Delete operator: The Delete keyword is used to remove the object property that comes after it.
    • Using Destructuring Assignment: To unpack object values and allocate them to other variables in JavaScript, use the syntax known as “using destructuring assignment.”

    Syntax

    Here is the syntax for Delete operation in Javascript −

    // Using delete operatordelete obj.property  
    
    // Using destructuringconst{prop1, newObj}= oldObj;

    Example

    In this example we will describe the deletion of the Object and its associated properties and values.

    const person ={ 
       firstName:'Amit', 
       yearsOld:52, 
       location:'mumbai'};// Display original person object 
    console.log("Initial person object: ", person);// Using destructuring const{ yearsOld,...updatedPerson }= person; 
    console.log("New person object without yearsOld attribute: ", updatedPerson);// Using delete operator delete person.location; 
    console.log("Person object after removing location: ", person);

    Output

    This will create the below outcome −

    Initial person object:  { firstName: 'Amit', yearsOld: 52, location: 'mumbai' }
    New person object without yearsOld attribute:  { firstName: 'Amit', location: 'mumbai' }
    Person object after removing location:  { firstName: 'Amit', yearsOld: 52 }
  • SessionStorage

    Session Storage in JavaScript

    The JavaScript sessionStorage object is a window object property that appears in all current browsers. The page’s protocol, host-name and port are linked to any sessionStorage data. Each window contains its own session storage. The JavaScript sessionStorage method contributes to the reliable storage of user data.

    In JavaScript, we use the getItem() method to get elements that are always stored in the session storage attribute. The storage object includes a getItem() method. It could be a JavaScript session Storage object or a local Storage object.

    Syntax

    Below is the syntax of the JavaScript SessionStorage −

    window.sessionStorage;

    Methods of SessionStorage

    To get an element from JavaScript sessionStorage we have to create the element and save it to session storage. We can get it back later. The storage object has four methods: setItem(), getItem(), removeItem(), key() and clean().

    setItem()

    Used to save information in a session storage item. Here is how you can use it in your code −

    sessionStorage.setItem("key","value");

    getItem()

    Used to retrieve and display a session storage item. Following is way you can use it in your code −

    let lastname = sessionStorage.getItem("key");

    removeItem()

    Used to delete a specific item from session storage. The following is how you can utilize it in your code −

    sessionStorage.removeItem("key");

    key()

    Used to get the name of a data item in session storage. Here is how you can utilize it in your code −

    let keyName = sessionStorage.key(index);

    clear()

    Used to clear all items in session storage. Here’s how you can put it into your code −

    sessionStorage.clear();

    Why do use sessionStorage in JavaScript

    SessionStorage can be used in many different ways. And these are the most important ones:

    • The web-page interface can be saved in session storage.
    • When the user returns to the page later, you can use sessionStorage to restore the previously saves user interface.
    • SessionStorage can also be used to transmit data between pages instead of using hidden input fields or URL parameters.

    Key Features

    Below are some key features of JavaScript’s SessionStorage −

    • Temporary Storage: Data is only stored for the duration of the session.
    • Tab-specific: Data is only accessible in the same browser tab or window.
    • Simple API: Provides simple methods for configuring, retrieving, and removing items.
    • Persistent During Reloads: Data is preserved after a page reload within the same session.
    • Storage Limit: Typically gives about 5MB of storage per origin for session data.

    Examples

    Following are some examples of the session storage −

    Example 1

    The example below shows how to use JavaScript sessionStorage with the set and get items methods. A session storage object helps us to create arrays and set data. After that, display information by calling the object’s getItem() function.

    <html><head><title>Display Data Using sessionStorage in JavaScript</title></head><body style="text-align: center;"><h4>Display Data Using sessionStorage in JavaScript</h4><p id="displayStudent"></p><p id="displayTutorial"></p><script>  
       const studentInfo = {  
    
      name: 'Amit',  
      rollNumber: 41,  
      website: 'Tutorialspoint',  
      learningMode: 'online',  
      age: 20,  
      subject: 'JavaScript'  
    }; const tutorialInfo = {
      subject: 'JavaScript',  
      website: 'Tutorialspoint',  
      mode: 'online',  
      cost: 'Free',  
      targetAudience: 'students and beginners'  
    }; // Set and display studentInfo in sessionStorage sessionStorage.setItem("studentInfo", JSON.stringify(studentInfo)); console.log("Student info saved in sessionStorage."); let retrievedStudent = sessionStorage.getItem('studentInfo'); document.getElementById('displayStudent').innerHTML = retrievedStudent; // Set and display tutorialInfo in sessionStorage sessionStorage.setItem("tutorialInfo", JSON.stringify(tutorialInfo)); console.log("Tutorial info saved in sessionStorage."); let retrievedTutorial = sessionStorage.getItem('tutorialInfo'); document.getElementById('displayTutorial').innerHTML = retrievedTutorial; </script></body></html>

    Output

    This will generate the below result −

    Display Data Using sessionStorage in JavaScript
    
    {"name":"Amit","rollNumber":37,"website":"Tutorialspoint","learningMode":"online","age":19,"subject":"JavaScript"}
    
    {"subject":"JavaScript","website":"Tutorialspoint","mode":"online","cost":"Free","targetAudience":"students and beginners"}
    

    Example 2

    This example shows how to use JavaScript session storage with the set and get items methods. To display the date and time, we can use the object’s getItem() method. The array value use the get and set methods, whereas the date value writes data immediately.

    <html><head><title> Display Data Using sessionStorage in JavaScript </title></head><body style="text-align: center;"><h4> Display Data Using sessionStorage in JavaScript </h4><p id="displayStudentInfo"></p><p id="displayCurrentTime"></p><script>  
       const learnerDetails = {  
    
      name: 'Amit',  
      rollNumber: 52,  
      website: 'TutorialsPoint',  
      learningMode: 'online mode',  
      age: 22,  
      subject: 'JavaScript'  
    }; // Store student info in sessionStorage sessionStorage.setItem("learnerDetails", JSON.stringify(learnerDetails)); console.log("Learner details saved in sessionStorage."); // Retrieve and display student info let retrievedStudentInfo = sessionStorage.getItem('learnerDetails'); document.getElementById('displayStudentInfo').innerHTML = retrievedStudentInfo; // Store and display current date and time let currentDateTime = new Date(); sessionStorage.currentDateTime = currentDateTime; console.log("Current date and time saved in sessionStorage."); let retrievedDateTime = sessionStorage.getItem('currentDateTime'); document.getElementById('displayCurrentTime').innerHTML = retrievedDateTime; </script></body></html>

    Output

    This will lead to the following result −

    Display Data Using sessionStorage in JavaScript
    {"name":"Amit","rollNumber":52,"website":"TutorialsPoint","learningMode":"online mode","age":22,"subject":"JavaScript"}
    Fri Oct 25 2024 13:14:10 GMT+0530 (India Standard Time)
    

    Example 3

    Here is an example of using sessionStorage in an HTML file with JavaScript. The sessionStorage is used to save data for the life of the session and makes it available as long as the browser tab is open.

    <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Session Storage Example</title></head><body><h1>Session Storage Demo</h1><label for="name">Enter your name:</label><input type="text" id="name" /><button onclick="saveName()">Save Name</button><button onclick="showName()">Show Name</button><button onclick="clearName()">Clear Name</button><p id="result"></p><script>
       // Function to save name in sessionStorage
       function saveName() {
    
      let name = document.getElementById('name').value;
      sessionStorage.setItem('userName', name);
      document.getElementById('result').innerText = 'Name saved in session storage!';
    } // Function to show name from sessionStorage function showName() {
      let name = sessionStorage.getItem('userName');
      if (name) {
         document.getElementById('result').innerText = 'Stored Name: ' + name;
      } else {
         document.getElementById('result').innerText = 'No name found in session storage!';
      }
    } // Function to clear name from sessionStorage function clearName() {
      sessionStorage.removeItem('userName');
      document.getElementById('result').innerText = 'Name cleared from session storage!';
    } </script></body></html>

    Output

    So you have to open the file in a browser. Then enter a name and then click Save Name. After that you have to click Show Name to see the stored name. And click Clear Name to remove it from storage.

    Javascript SessionStorage

    Summary

    The sessionStorage allows you to store data just for a single session. When you close a browser tab or window, the sessionStorage data is automatically removed. As the sessionStorage is a Storage system object, you can handle its data using Storage-specific methods.

  • Selection API

    JavaScript Selection API allows us to access and change or modify the portion of a web page which is selected by the user.This includes selecting which text or elements to highlight and providing options for connecting with the selected item. But it should be noticed that the Selection API is not available in Web Workers so it can only be used in a web-page’s main thread.

    The JavaScript Selection API provides a variety of essential APIs that allow developers to access and modify certain portions of a document. These interfaces contain the Selection and Range objects, as well as a number of helpful events that occur all over the selection process.

    Selection Interface

    A Selection object shows the user-selected region of text or the cursor’s current position. Each document is given a unique selection object, which can be retrieved via document.getSelection(), or Window.getSelection() can then be examined and modified.

    A user can choose between left to right and right to left. The anchor is where the user began the selection, whereas the focus is where the user ends it. When you make a selection with a desktop mouse, the anchor is set where you pressed the mouse button and the focus is placed where you let go.

    Instance Properties

    Here is the table provided of instance properties you can use for you reference −

    PropertyDescription
    Selection.anchorNodeThis shows the part of the document where the selection starts. It will be empty if nothing was selected.
    Selection.anchorOffsetThis tells how far the starting point of the selection is from the beginning. If the selection starts in a piece of text, it shows the number of characters before it. If it starts in an element (like a paragraph or list), it shows the number of other elements before it.
    Selection.directionThis shows if the selection was made from left to right, or right to left.
    Selection.focusNodeThis shows the part of the document where the selection ends. It can also be empty if nothing was selected.
    Selection.focusOffsetSimilar to anchorOffset, this shows how far the ending point of the selection is from the beginning in the focusNode.
    Selection.isCollapsedThis is true if the selection has no length (meaning the start and end are the same point), and false if there is a range of selected text.
    Selection.rangeCountThis tells you how many separate selections are made.
    Selection.typeThis gives the type of selection. It can be “None” (no selection), “Caret” (a single point), or “Range” (a highlighted area).

    Instance Methods

    Here is the table below in which we have provided the list of instance methods of Selection Interface with its description.

    MethodsContent
    Selection.addRange()A Range object that will be added to the selection.
    Selection.collapse()Collapses the current selection to a single point.
    Selection.collapseToEnd()Collapses the selection to the end of the last range in the selection.
    Selection.collapseToStart()Collapses the selection to the start of the first range in the selection.
    Selection.containsNode()Indicates if a certain node is part of the selection.
    Selection.deleteFromDocument()Deletes the selection’s content from the document.
    Selection.empty()Removes all ranges from the selection, leaving the anchorNode and focusNode properties equal to null and nothing selected.
    Selection.extend()Moves the focus of the selection to a specified point.
    Selection.getComposedRanges() ExperimentalReturns an array of StaticRange objects, each that represents a selection that might cross shadow DOM boundaries.
    Selection.getRangeAt()Returns a Range object representing one of the ranges currently selected.
    Selection.modify()Changes the current selection.
    Selection.removeRange()Removes a range from the selection.
    Selection.removeAllRanges()Removes all ranges from the selection.
    Selection.selectAllChildren()Adds all the children of the specified node to the selection.
    Selection.setBaseAndExtent()Sets the selection to be a range including all or parts of two specified DOM nodes, and any content located between them.
    Selection.setPosition()Collapses the current selection to a single point.
    Selection.toString()Returns a string currently being represented by the selection object, i.e., the currently selected text.

    Document.getSelection()

    The getSelection() method of the Document interface returns the Selection object for this document which represents the user-selected text range or the caret’s current position. And it acts like the window.getSelection().

    Syntax

    Below is the syntax of the Document.getSelection() −

     document.getSelection()

    Parameters

    This method works without the need for any parameters.

    Return value

    This method basically returns a Selection object, or null if there is no browsing context (e.g., unattached <iframe>).

    Example

    Following is the example for showing the usage of Document.getSelection() object −

    <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document.getSelection Example</title></head><body><p>Select some text in this paragraph and check the console.</p><button onclick="getSelectedText()">Get Selected Text</button><script>
    
      function getSelectedText() {
         let selection = document.getSelection();
         if (selection.rangeCount &gt; 0) {
            document.write("Selected text: " + selection.toString());
         } else {
            document.write("No text selected.");
         }
      }
    </script></body></html>

    Output

    To view the messages use the browser’s developer tools (usually by pressing F12) and select the “Console” tab.

    Check the below message on the console after running the above code in browser −

    Selected text: paragraph and check
    

    Window.getSelection()

    The getSelection() method of the Window interface returns the Selection object connected with the window’s document which represents the range of text selected by the user or the caret’s current position.

    Syntax

    Below is the syntax of the Window.getSelection() −

     window.getSelection()

    Parameters

    This method does not require any parameters.

    Return value

    This method returns a Selection object or null if the connected document has browsing context (e.g. if the window is an unattached <iframe>).

    Firefox gives null when a <iframe> is not displayed (e.g., display: none), whereas other browsers provide a Selection object with Selection.type set to None.

    Example

    Here is the example for showing the usage of Window.getSelection() object −

    <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Window.getSelection Example</title></head><body><p>Select some text in this paragraph and check the console.</p><button onclick="getSelectedText()">Get Selected Text</button><script>
    
      function getSelectedText() {
         let selection = window.getSelection();
         if (selection.rangeCount &gt; 0) {
            document.write("Selected text: " + selection.toString());
         } else {
            document.write("No text selected.");
         }
      }
    </script></body></html>

    Output

    So when to run the above HTML code in your browser. There will be a text will be appear with a button “Get Selected Text”. So when you select some text and press the button then after inspecting the element you can see the below message on the console −

    Selected text: this paragraph
    

    Document: selectionchange event

    The Selection API’s selectionchange event is triggered when a Document’s current Selection is changed. This event cannot be canceled and will not bubble.

    The event can be handled by registering an event listener for selectionchange or by using the onselectionchange event handler.

    Syntax

    Use the event name in methods like addEventListener() or to set an event handler property.

    addEventListener("selectionchange",(event)=>{});onselectionchange=(event)=>{};

    Event type

    It is a generic Event.

    Example

    Here is the example of selectionchange event −

    <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Selection Change Example</title></head><body><h1>Text Selection Example</h1><p>Select some text in this paragraph to see the console messages about selection changes.</p><p>Try selecting different parts of this text to see how it updates!</p><script>
    
      // Using addEventListener to track selection changes
      document.addEventListener("selectionchange", () =&gt; {
         document.write("Selection has changed:", document.getSelection().toString());
      });
        
      // Using onselectionchange to handle selection changes
      document.onselectionchange = () =&gt; {
         document.write("Updated selection:", document.getSelection().toString());
      };
    </script></body></html>

    Output

    When you select any text in these paragraphs it will send messages to the console telling you that your selection has changed and displays the currently selected material.

    [Log] Selection has changed: - "" (example.html, line 16)
    [Log] Updated selection: - "" (example.html, line 21)
    [Log] Selection has changed: - "" (example.html, line 16)
    [Log] Updated selection: - "" (example.html, line 21)
    [Log] Selection has changed: - "" (example.html, line 16)
    [Log] Updated selection: - "" (example.html, line 21)
    [Log] Selection has changed: - "Selection" (example.html, line 16)
    [Log] Updated selection: - "Selection" (example.html, line 21)
    

    Node: selectstart event

    This event occurs when the user starts making a new selection. For example, they can click and drag to highlight text. Suppose the event has been canceled so the selection is not changed.

    Syntax

    Use the event name in methods such as addEventListener() or set an event handler property.

    addEventListener("selectstart",(event)=>{});onselectstart=(event)=>{};

    Event type

    It is also a generic Event.

    Example

    Here is the example of selectstart event −

    <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Select Start Example</title></head><body><h1>Text Selection Example</h1><p>Choose some text in this paragraph to check the console messages.</p><p>Try different parts of this text!</p><script>
    
      // Using addEventListener to track when text selection starts
      document.addEventListener("selectstart", () =&gt; {
         document.write("Selection started");
      });
      
      // Using onselectstart to handle when text selection starts
      document.onselectstart = () =&gt; {
         document.write("Selection started.");
      };
    </script></body></html>

    Output

    When you choose any text in these paragraphs, it will display “Selection started” and “Selection started.” on the terminal.

    [Log] Selection started (example.html, line 16)
    [Log] Selection started. (example.html, line 21)
    [Log] Selection started (example.html, line 16)
    [Log] Selection started. (example.html, line 21)
    [Log] Selection started (example.html, line 16)
    [Log] Selection started. (example.html, line 21)
    [Log] Selection started (example.html, line 16)
    [Log] Selection started. (example.html, line 21)
    [Log] Selection started (example.html, line 16)
    [Log] Selection started. (example.html, line 21)