Category: Miscellaneous

  • Shallow Copy

    Shallow Copy

    In JavaScript, a shallow copy is a duplication of an array or object that replicates its top-level elements, but not its nested structures. When creating a shallow copy of an array, common methods include using the spread operator ([…]), Array.from(), or the slice() method.

    For objects, the spread operator ({…}) and Object.assign() are commonly used. It is important to note that while the top-level statements are being duplicated, any nested object or arrays that are within the original structure are not cloned, instead their references are retained in the shallow copy.

    Consequently, modifications to nested structures in the copied version affect the original and vice versa. For deep cloning, where nested structures are also duplicated, alternative techniques or libraries such as lodash’s _.cloneDeep are required.

    Deep Copy vs. Shallow Copy

    Two methods exist for duplicating objects or arrays: deep copying and shallow copying. Deep copying creates an entirely independent duplicate even including nested structures; conversely, shallow copying only replicates top-level elements while maintaining references to the nested ones.

    While deep copying guarantees complete independence, shallow copy proves more memory-efficient and faster but at a cost: modifications in nested structures impact both original and copied objects. Task requirements dictate the choice: for total independence, deep copying is preferred; however, when efficiency is paramount and nested references can be preserved, shallow copying becomes the optimal option.

    Examples

    Example 1: Shallow copy using Object assign() method

    In the following example, we use the Object.assign() method create a shallow copy of an object.

    <!DOCTYPE html><html><body><h2>Shallow copy using Object.assign() method</h2><p>Original Object:</p><p id="originalObject"></p><p>Copied Object:</p><p id="copiedObject"></p><script>const originalObject ={ name:"Alice", age:30};const copiedObject = Object.assign({}, originalObject);
    
      document.getElementById("originalObject").textContent =JSON.stringify(originalObject);
      document.getElementById("copiedObject").textContent =JSON.stringify(copiedObject);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example 2: Shallow copy using spread operator

    In this example we use the spread operator (...) to creating a shallow copy of an array.

    <!DOCTYPE html><html><body><h2>Shallow copy using spread operator(...)</h2><p>Original Array:</p><p id="originalArray"></p><p>Copied Object:</p><p id="copiedArray"></p><script>const originalArray =[1,2,3];const copiedArray =[...originalArray];
    
      document.getElementById("originalArray").textContent =JSON.stringify(originalArray);
      document.getElementById("copiedArray").textContent =JSON.stringify(copiedArray);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example 3:Shallow copy of object with array

    In the example below, a combination of Object.assign() and Array.prototype.slice() is used to create a shallow copy of an object, emphasizing proper handling of arrays within the object structure.

    <!DOCTYPE html><html><body><h2>Shallow copy using array slice() method</h2><p>Original Object:</p><p id="originalObject"></p><p>Copied Object:</p><p id="copiedObject"></p><script>const originalObject ={ name:"Bob", hobbies:["reading","coding"]};const copiedObject = Object.assign({}, originalObject,{ hobbies: originalObject.hobbies.slice()});
    
      document.getElementById("originalObject").textContent =JSON.stringify(originalObject);
      document.getElementById("copiedObject").textContent =JSON.stringify(copiedObject);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example 4: Shallow Copy with Nested Objects

    In this example we demonstrate creating of shallow copies of an object with nested properties using the JSON.stringify and JSON.parse methods of JavaScript. The original object contains of a nested structure which has properties like name and address. Address further consists of properties like street and city. We then use JSON.stringify to convert the original object into a JSON formatted string & then apply the JSON.parse to parse the string back into a new object thereby creating a shallow copy.

    <!DOCTYPE html><html><body><h2>Shallow Copy with Nested objects using JSON.stringify &JSON.parse</h2><p>Original Object:</p><pre id="originalObject"></pre><p>Copied Object:</p><pre id="copiedObject"></pre><script>const originalObject ={
    
         name:"Charlie",
         address:{
            street:"123 Main St",
            city:"New York"}};const copiedObject =JSON.parse(JSON.stringify(originalObject));
      document.getElementById("originalObject").textContent =JSON.stringify(originalObject,null,2);
      document.getElementById("copiedObject").textContent =JSON.stringify(copiedObject,null,2);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example 5: Shallow copy impact of modification

    Illustrating the impact of modifications on a shallow copy created via JavaScript's Object.assign() method, the following code initially presents an original object. The original object features properties named "name" and "age," side by side with its corresponding shallow copy. Next, we observe how this code alters the "age" property of our copied object. Subsequently, the code presents an exposition of both the original and copied objects' states post-modification. This instance accentuates that alterations to the shallow copy despite isolating within its duplicated object do not influence the base object; it thereby confirms a peculiar behaviour wherein top-level properties are captured by shallow copies while preserving independence between primary and secondary instances.

    <!DOCTYPE html><html><body><h2>Shallow Copy impact of modification</h2><h3>Before Modification</h3><p>Original Object</p><pre id="originalObjectBefore"></pre><p>Copied Object</p><pre id="copiedObjectBefore"></pre><h3>After Modification</h3><p>Original Object</p><pre id="originalObjectAfter"></pre><p>Copied Object</p><pre id="copiedObjectAfter"></pre><script>const originalObject ={ name:"Alice", age:30};const copiedObject = Object.assign({}, originalObject);
    
    
      document.getElementById("originalObjectBefore").textContent =JSON.stringify(originalObject,null,2);
      document.getElementById("copiedObjectBefore").textContent =JSON.stringify(copiedObject,null,2);
      copiedObject.age =40;
      document.getElementById("originalObjectAfter").textContent =JSON.stringify(originalObject,null,2);
      document.getElementById("copiedObjectAfter").textContent =JSON.stringify(copiedObject,null,2);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Importance of Shallow Copy

    To preserve the original data structure and manage memory efficiently, one must critically understand shallow copying in JavaScript: it duplicates top-level elements a concept that achieves balance. This understanding empowers non-destructive manipulation tasks; for example, array sorting. Furthermore, it simplifies feature implementation processes like undo/redo functionalities, all while significantly enhancing overall user experience an integral role indeed. Shallow copies possessing the capacity to adeptly handle alterations in practical applications maintain data integrity: a crucial aspect when isolating modifications from an original object is necessary in certain scenarios.

  • Unicode

    What is Unicode?

    Unicode is a universal set of characters that contains a list of characters from the majority of languages, writing systems, etc. It provides a unique number for every character without focusing on programming language, platform, operating system, etc. Furthermore, it also includes punctuation, emojis, special characters, etc.

    In short, the Unicode set contains unique numbers, each referring to a unique character, having the same meaning regardless of platform, operating system, etc.

    Intuition behind Unicode

    Before understanding unicode, let’s understand the idea behind it. Can you answer the question of why are you able to read this tutorial? Well, because you know the meaning of the letters written. A reader (you) and writer both have the same comprehension of the English alphabetical letters; that’s why you are able to read what the writer has written.

    Similarly, computers don’t understand the letters. For computers, letters are sequences of bits, and each sequence is mapped to a unique character that is called Unicode.

    Now, let’s understand Unicode in depth.

    Unicode in JavaScript

    JavaScript allows developers to use the Unicode characters in the string literals and source code. Developers need to use the escape notation (\u) to use the Unicode characters in JavaScript code.

    Syntax

    Users can follow the syntax below to use the Unicode characters in JavaScript.

    const char ='\uxxxx';

    In the above syntax, ‘\uxxxx’ is a Unicode character. Here, ‘xxxx’ represents the hexadecimal characters, and /u’ represents the escape notation.

    Examples

    Example: Unicode escape sequence

    In the below example, we have used unicode escape sequence to print the “hello” message.

    <html><body><div>Using unicode escape sequence</div><div id ="output"></div><script>let str ='\u0068\u0065\u006c\u006c\u006f'
    
      document.getElementById("output").innerHTML = str;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Using unicode escape sequence
    hello
    

    Example: Using unicode characters in variable names

    In the code below, we have used the two different Unicode characters as two different identifiers (variable names). In the output, you can observe the value of both identifiers.

    <html><body><div>Using unicode characters in variable names</div><div id ="output"></div><script>// Using the Unicode characters in variable nameslet \u0061 ="Hello";let \u0062 ="World";
    
      document.getElementById("output").innerHTML = a +" "+ b;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Using unicode characters in variable names
    Hello World
    

    Example: Using the Unicode Characters in String

    In this example, we have used the Unicode characters in the string literals. The output shows the special characters in the middle of the string.

    <html><body><div> Using the Unicode Characters in String </div><div id ="output"></div><script>// Using the Unicode characters in the stringlet str ='Hello \u00D8 \u00F8 World';
    
    document.getElementById("output").innerHTML = str;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Using the Unicode Characters in String
    Hello   World
    

    Example: Using Unicode for non-BMP (Basic Multilingual Plane) characters

    In the below example we have used unicode characters (code points) to show a non-BMP (basic multilingual plane) characters. We have demonstrate for a health worker.

    <html><body><div>showing person heath worker using unicode code point</div><div id ="output"></div><script>// Showing emojis using the unicode charactersconst smileyFace ='\u{1F9D1}\u200D\u2695\uFE0F';
    
    document.getElementById("output").innerHTML = smileyFace;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    showing person heath worker using unicode code point
    
    

    Example: Showing Emojies Using the Unicode Characters

    In the code below, we have used the Unicode character to show the smiley face emoji.

    <html><body><div>Showing Emojies Using the Unicode Characters </div><div id ="output"></div><script>// Showing emojis using the unicode charactersconst smileyFace ='\uD83D\uDE0A';
    
    document.getElementById("output").innerHTML = smileyFace;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Showing Emojies Using the Unicode Characters
    
    

    As we have seen, each Unicode character represents a unique character. In JavaScript, we can use Unicode characters with identifiers, string literals, etc.

  • Blob

    What is blob in JavaScript?

    In JavaScript, a Blob is an object that is a group of bytes representing the data stored in the file. We can easily easily read the content of the Blob object as an ArrayBuffer, so it is very useful to store the binary data. The Blob object is used to handle the raw binary data, which we can create from the plain text, file data, etc.

    Syntax

    Users can follow the syntax below to use the Blob() constructor to create a blob object.

    newBlob(BlobContent, Options);

    OR

    newBlob(BlobContent,{type: Type of the Blob content});

    In the above syntax, Blob() constructor takes two parameters and returns an instance of the Blob object. Developers can set the values of the ‘type’ option based on the BlobContent.

    Parameters

    The Blob() constructor takes two parameters, as given below.

    • BlobContent − It is a text, data, or file content.
    • Options − It is an optional object containing various options for BlobContent.

    The ‘type’ is an important property in the Options object. It contains the MIME-type of the BlobContent as a value. For example, to store plain text in the blob object, you can use ‘text/plain’ as a MIME type; for images, you can use ‘image/jpg’ or ‘image/png’, etc.

    Example

    In the below example code, we have used the blob() constructor to create a blob object. We have passed the ‘Hello World!’ string as a first parameter and the ‘text/plain’ MIME type for the content as a second parameter of the blob() constructor.

    After that, we have created the instance of the FileReader() object and used the readAsText() method to read the content of the blob object. In the output, we can see that it prints the plain text, which is the content of the blob object.

    <html><body><h2> JavaScript - Blob Object </h2><h3 id ="output"></h3><script>var data ="Hello World";var blob =newBlob([data],{
    
         type:'text/plain'});// Using the fileReader object to read the blobvar reader =newFileReader();
      reader.addEventListener("loadend",function(e){var text = reader.result;
         document.getElementById("output").innerHTML = text;});// Start reading the blob as text
      reader.readAsText(blob);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Blob URLs

    In the above section, we have learned to use the blob object. Furthermore, we can also create the URL using the blob object. As any particular URL refers to the file in the local file system, the blob URL referes to the content of the blob object. Also, we can use the blob URL as an actual URL with the <a> or <img> tag.

    Let's take a look at the example below to create a URL from the blob object.

    Example: Rendering text content using the Blob URL

    In the example below, we have created the instance of the blob object and passed text content as a parameter. After that, we used the createObjectURL() method to create a blob URL.

    Next, we have updated the value of the 'href' attribute of the '<a>' with the blob URL. In the output, when you click the URL, it shows you the content stored in the blob object.

    <html><body><h2> JavaScript - Blob URL</h2><a href ="#" id ="download"> Download Text File </a><script>// Creating file using Blob objectvar data ="This file contains the content of the blob object.";var blob =newBlob([data],{
    
         type:'text/plain'});// Creating URL from Blob objectvar url =URL.createObjectURL(blob);var a = document.getElementById("download");// Updating the href attribute's value
      a.href = url;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: Rendering an Image Using the Blob URL

    In this example, we have used the file input to get the image as input. Whenever the user uploads the image, we create the blob object using the file content.

    After that, we create a URL from the blob object and use it as a value of the 'src' attribute of the '' tag to render the image on the web page.

    <html><body><h2> JavaScript  Blob URL</h2><h3> Upload image file </h3><input type ="file" id ="fileInput"/><div id ="output"></div><script>// Read the file and create a blob
    
      document.getElementById('fileInput').addEventListener('change',function(){var file =this.files[0];var reader =newFileReader();
         reader.onload=function(){// Create a blobvar blob =newBlob([newUint8Array(this.result)],{ type: file.type });// Create an object URLvar url =URL.createObjectURL(blob);// Set the object URL as the source of an image
            document.getElementById('output').innerHTML ='&lt;img src="'+ url +'" /&gt;';};
        reader.readAsArrayBuffer(file);});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Blob Advantages & Disadvantages

    Here are some advantages and disadvantages of using the blob objects.

    Advantages

    • Blob objects are ideal for handling large binary data files on the web.
    • Developers can fetch the data in chunks by using the blob objects, which improves the performance of the application.
    • Blob objects can be used with the File API to perform the file operations in the browser.

    Disadvantages

    • Large blob objects can consume significant memory and resources, which can impact the overall application performance and use experience.
    • Handling the binary data using the blob object can introduce security concerns to the code.
    • Older browsers do not support blob.
  • BigInt

    BigInt

    The BigInt data type in JavaScript is a numeric primitive that can represent integers with arbitrary magnitude. This is in contrast to the Number data type, which is limited to representing integers between -(253 – 1) and 253 – 1.

    JavaScript which powers dynamic web applications, traditionally employs the Number type for numeric representations in accordance with double-precision floating-point format of the widely adopted IEEE-754 standard. This standard imposes a significant constraint: it can precisely represent only up to 253 – 1 as its maximum safe integer. However, crossing this numerical threshold starts to erode fidelity of numeric values and introduces potential inaccuracies into critical computations.

    JavaScript introduced the BigInt data type in response to these limitations; as its name suggests BigInt addresses the shortcomings of finite precision. This capability, proving indispensable in various scenarios notably within fields such as cryptographic algorithms, financial computations and intricate mathematical operations demanding utmost precision: it allows for the representation of integers with arbitrary accuracy, a significant advancement.

    Declaration and Initialization

    You can create a BigInt using a numeric literal followed by the n suffix or by using the BigInt() constructor.

    const bigIntLiteral =123n;const anotherBigInt =BigInt(456);

    It’s important to note that attempting to mix regular numbers and BigInt without explicit conversion can result in an error.

    Basic Operations

    BigInt supports standard arithmetic operations like addition, subtraction, multiplication, and division. When performing operations, both operands must be of type BigInt.

    const a =123n;const b =456n;const sum = a + b;// 579nconst product = a * b;// 56088n

    Comparison

    BigInt values can be compared using standard comparison operators, such as <, >, <=, >=, and ===.

    const a =123n;const b =456n;
    a > b;// false
    a === b;// false

    Conversions

    Converting between BigInt and regular numbers is possible, but keep in mind that there might be a loss of precision for very large BigInt values.

    const bigIntValue =BigInt("12345678901234567890");const regularNumber =Number(bigIntValue);const bigIntValue =BigInt("12345678901234567890");const regularNumber =Number(bigIntValue);

    Examples

    Example 1: Simple BigInt Arithmetic

    In this example we demonstrate addition and multiplication of 2 BigInt numbers num1 and num2 whos values are 123n and 456n respectively. By enabling the accurate representation of large integer values without risking precision loss, BigInt overcomes a potential shortcoming in regular JavaScript numbers.

    <!DOCTYPE html><html><body><h2>Simple BigInt Arithmetic</h2><p id="result"></p><script>const num1 =123n;const num2 =456n;const sum = num1 + num2;const product = num1 * num2;
    
    
      document.addEventListener("DOMContentLoaded",function(){
         document.getElementById("result").innerText =Sum of ${num1} &amp;amp; ${num2} is ${sum} and their product: ${product};});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example 2: Fibonacci Sequence Generator with BigInt

    The Fibonacci sequence: a series of numbers in which each number is the sum of its two preceding ones; employs BigInt to handle larger values exceeding the precision limits of regular JavaScript numbers. Through the generateFibonacci function, an array serves as storage for these sequence values, guaranteeing precise calculations even for terms with substantial numeric magnitude.

    <!DOCTYPE html><html><body><h2>Fibonacci Sequence</h2><p id="result"></p><script>functiongenerateFibonacci(n){const sequence =[0n,1n];for(let i =2; i <= n; i++){
    
            sequence[i]= sequence[i -1]+ sequence[i -2];}return sequence;}
      document.addEventListener("DOMContentLoaded",function(){const result =generateFibonacci(20); 
         document.getElementById("result").innerText ="Fibonacci Sequence of 1st 20 terms: "+ result.join(", ");});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example 3: Factorial Calculator with BigInt

    Factorial is the product of all the positive integers less than or equal to the number. In order to find the factorial we have made use of BigInt. For small numbers like 5 & 10, a regular number would work but what happens when we have to find the factorial of 10000, the output would be too huge. Hence BigInt would come to our rescue. In this example we find the factorial of 20n with the help of a loop.

    <!DOCTYPE html><html><body><h2>Factorial of a Large Number</h2><p id="result"></p><script>functioncalculateFactorial(){const num =20n;// Calculate factorial of 20let result =1n;for(let i =2n; i <= num; i++){
    
            result *= i;}
         document.getElementById("result").innerText ="Factorial of 20 is "+ result;}
      document.addEventListener("DOMContentLoaded",function(){calculateFactorial();});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example 4: BigInt Color Square

    Utilizing BigInt in this example, we generate random colours within our predefined parameters and apply them to the colorSquare for demonstration. The generation of a random colour involves multiplication: a floating-point number between 0 and 1--obtained through Math.random() is multiplied by the maximum color value. We subsequently round down this result to its nearest integer via Math.floor(), before converting it into BigInt using BigInt(). The BigInt generated is the converted to a hexadecimal string and returned.

    <!DOCTYPE html><html><head><style>
    
      body {
         font-family: Arial, sans-serif;}
      #colorSquare {
         width:400px;
         height:200px;
         border:2px solid #000;}&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h2&gt;BigInt Color Example&lt;/h2&gt;&lt;div id="colorSquare"&gt;&lt;/div&gt;&lt;script&gt;functiongenerateRandomColor(){const maxColorValue =16777215n;// 0xFFFFFF in hexadecimalconst randomColor =BigInt(Math.floor(Math.random()*Number(maxColorValue)));return#${randomColor.toString(16).padStart(6, '0')};}const colorSquare = document.getElementById('colorSquare');
      colorSquare.style.backgroundColor =generateRandomColor();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Error Handling with BigInt

    This code demonstrates a unique case of adding BigInt with regular numbers. In JavaScript, we need to perform explicit conversion to BigInt. When we tried to perform the addition of 42 (regular number) with 42n (or BigInt), it threw an error which caught and displayed on the screen with the help of try catch.

    <!DOCTYPE html><html><body><h2>Adding BigInt & Regular Number</h2><div id="output"></div><script>const regularNumber =42;const bigIntValue =BigInt(regularNumber);// Explicit conversion
    
    
      document.getElementById("output").innerHTML =&amp;lt;p&amp;gt;Regular Number: ${regularNumber}&amp;lt;/p&amp;gt;+&amp;lt;p&amp;gt;BigInt Value: ${bigIntValue}&amp;lt;/p&amp;gt;+&amp;lt;p&amp;gt;Regular Number + BigInt Value results in:&amp;lt;/p&amp;gt;;try{const result = regularNumber + bigIntValue;
         document.getElementById("output").innerHTML +=Result: ${result};}catch(e){
         document.getElementById("output").innerHTML +=Error: ${e};}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

  • Dynamic Imports

    Dynamic Imports

    Whenever the application code grows and contains thousands of lines, it is important to split the code into modules. Modules allow developers to break down complex codes and use them in different files by importing.

    In JavaScript modules chapter, you learned to import and export objects from the modules, but it was a static import, as we load them at the top of the code. Sometimes, we need to import the modules whenever needed rather than importing them statically to improve the performance of the web application. It is also called dynamic imports.

    The import() Expression for Dynamic Imports

    Whenever you need to import a module dynamically, you can use the import() expression, which returns the promise. We can import the module dynamically using the import() expression anywhere in the code.

    Syntax

    Users can follow the syntax below to import modules dynamically using the import() expression.

    import(moduleName).then(module=>{// Use the module here.});

    In the above syntax, we use the then() method with the import() expression to resolve the promise.

    Parameters

    • moduleName − It takes a module name or path as a parameter, which we need to load dynamically.

    Return Value

    It returns the promise.

    Examples of Dynamic Import

    Example 1

    Filename: test.js

    In the code below, we export the ‘val1’ variable containing the integer value.

    exportconst val1 =11;

    Filename: test.html

    In the code below, we have used the if-else statement. We import the module and use its objects in the if() block.

    This way, we can import modules dynamically using the import() expression.

    <html><body><div>Example 1- dynamic importin JavaScript</div><div id ="output"></div><script type="module">let output = document.getElementById('output');let val =2;if(val <5){// Importing the moduleimport('./test.js').then(module=>{
    
            output.innerHTML ="The imported value is "+ module.val1;});}else{
         output.innerHTML ="Value is greater than 5";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Example 1 - dynamic import in JavaScript
    The imported value is 11
    

    Example 2

    Filename: test.js

    In the code below, we have defined the add() function, which returns the sum of two numbers.

    exportfunctionadd(a, b){return a + b;}

    Filename: test.html

    In the code below, we have added the 'click' event listener to the button. When a user clicks the button, it loads the 'test.js' module. Here, we used the async/await to handle the promise returned by the import() expression.

    After that, we use the add() function of the module to sum two numbers, and users can observe the summation result in the output.

    <html><body><div>Example 2- dynamic imports in JavaScript</h2><div id ="output"></div><button id ="button"> Click me </button><script type="module">let output = document.getElementById('output');let btn = document.getElementById('button');//When the button is clicked, load the module
    
      btn.addEventListener('click',async()=&gt;{let module =awaitimport('./test.js');let result = module.add(2,3);
         output.innerHTML ="The sum of 2 and 3 is "+ result;});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Example 2 - dynamic imports in JavaScript
    The sum of 2 and 3 is 5
    

    This way, developers can import modules dynamically in the function, if-else block, etc., whenever needed rather than importing them at the top of the code.

  • Modules

    What is a Module?

    module in JavaScript is a single file containing a JavaScript code or script. Rather than adding the code for the whole application in a single file, we can break down the code and create separate files for the code having the same functionalities.

    In short, the module contains the code to perform the specific task. It can contain variables, functions, classes, etc.

    When the size of the application grows, number of lines in the code also grows. Even real-time applications contain millions of lines of code. Now, think about if developers have only a single file containing millions of lines of code. Are they able to manage it properly? The simple answer is no. Here, using the module comes into the picture.

    Syntax

    Users can follow the syntax below to export and import the modules.

    exportfunctionfunc_name(parameters){// function code}import{func_name} from filename
    

    In the above syntax, the export keyword is used to export the function from the module, and the import keyword is used to import the function from the module.

    Example

    Filename: mul.js

    In the code below, we defined the ‘mul() function in the ‘mul.js’ file, which takes two integers as a parameter and returns the multiplication of them. Also, we used the ‘export’ keyword before the ‘function’ keyword to export the function from the module.

    //  exporting mul() functionexportfunctionmul(a, b){return a * b;}

    Filename: test.html

    <html><body><div> JavaScript - Modules </div><div id ="output"></div><script type="module">import{ mul }from'./mul.js';
    
      document.getElementById('output').innerHTML ="The multiplication of 2 and 3 is "+mul(2,3);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    JavaScript - Modules
    The multiplication of 2 and 3 is 6
    

    In the above code, we have imported the module in an HTML file. However, we can also import the module in another JavaScript file.

    Export Multiple Objects from a Single Module

    You can also export multiple variables, functions, etc., from a single module. Let's understand it via the example below.

    Example

    FileName: math.js

    In the code below, we have exported the mul() and sum() functions. Also, we have exported the variable containing the value of PI. In short, we are exporting the multiple objects from the single module.

    // exporting mul() functionexportfunctionmul(a, b){return a * b;}// exporting sum() functionexportfunctionsum(a, b){return a + b;}// export value of PIexportletPI= Math.PI;

    FileName: test.html

    In the code below, we import multiple objects from a single module and use them to perform the mathematical operations.

    <html><body><div> Exporting Multiple Objects from a Single Module </div><div id ="output"></div><script type="module">import{ mul, sum,PI}from'./math.js';
    
      document.getElementById('output').innerHTML ="The multiplication of 2 and 3 is "+mul(2,3+"&lt;br&gt; The addition of 2 and 3 is "+sum(2,3)+"&lt;br&gt; The value of PI is "+PI;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Exporting Multiple Objects from a Single Module
    The multiplication of 2 and 3 is 6
    The addition of 2 and 3 is 5
    The value of PI is 3.141592653589793
    

    Default Exports

    You can use the 'default' keyword to define the default export in the module. After that, whenever you try to import the object that is not defined in the module, it returns the object that is exported by default. The default export helps in avoiding the import error.

    Syntax

    Users can follow the syntax below to use the default exports in the module.

    exportdefaultfunctionfunc_name(params){// function body}import random_name from filename;

    In the above syntax, the 'default' keyword is used after the export keyword to export the 'func_name' function by default.

    Example

    FileName: test.js

    In the code below, we export the 'v1' variable by default, and we also export the 'v2' variable.

    const v1 ="Version 1";// default exportexportdefault v1;// other modulesexportconst v2 ="Version 2";

    FileName: test.html

    In the code below, we have imported the 'v3' and 'v2' from the test.js file. As 'v3' is not exported from the test.js file, it imports the default object, which is 'v1.

    <html><body><div> Default Export </div><div id ="output"></div><script type="module">// V3 is not defined in the module, so it returns V1.import v3,{ v2 }from'./test.js';
    
    
      document.getElementById('output').innerHTML ="The value of v3 is : "+ v3 +"&lt;br&gt;"+"The value of v2 is : "+ v2;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Default Export
    The value of v3 is : Version 1
    "The value of v2 is : Version 2
    

    Rename Import and Export

    Sometimes, it happens that the code file and module file contain the same name of the object. In such cases, if the developer imports the module in the code file, it can raise conflicts and errors. To resolve this issue, we can change the name of the module either while exporting or importing.

    Syntax to Rename Exports

    Users can follow the syntax below to rename the exports.

    export{
    
    func1 asN1,
    func2 asN2};// import in the code fileimport{N1,N2}from'./module.js';</pre>

    In the above syntax, we have changed the name of func1 to N1 and func2 to N2 at the time of exporting from the module. We used the 'as' keyword to change the name of the function.

    Syntax to Rename Imports

    Users can follow the syntax below to rename the imports.

    export{
    
    func1,
    func2
    };// import in the code fileimport{ func1 asN1, func1 asN2}from'./module.js';

    In the above syntax, we change the function name while importing it.

  • Set Date Methods

    Set Date Methods

    JavaScript Set Date Methods are functionalities linked to the Date object in JavaScript, designed to streamline the adjustment and modification of specific elements within a date and time structure. These methods empower developers to efficiently update individual components, such as year, month, day, hour, and minute, in a Date object, offering a convenient approach for handling and manipulating date-related values in JavaScript applications.

    Here, we will discuss about these JavaScript set date methods in detail. The table below comprises of the most commonly used set date methods and their corresponding description.

    MethodDescription
    setFullYear(year)Sets the year of the date object. Accepts a four-digit year. Adjusts the date; if it’s a leap year and the date is February 29, it remains; otherwise, it changes to the closest valid date in the new year.
    setMonth(month)Sets the month of the date object (0-11). Accepts a numeric value (0-11). Adjusts the date, changing the year if the month value is outside the valid range.
    setDate(day)Sets the day of the month for the date object (1-31). Accepts a numeric value (1-31). Adjusts the date, changing the month and year if the day value is outside the valid range for the current month.
    setHours(hours)The function sets the hour of a date object within the range of 0-23, accepting only numeric values. It adjusts the date as necessary to maintain validity, potentially altering the month and year in addition to time.
    setMinutes(minutes)Accepts numbers ranging from 0 to 59 and sets the minutes of that particular date object. It adjusts the date in such a way that hour, date, month and year are a valid date and time.
    setSeconds(seconds)Sets the seconds of the date object (0-59). Accepts a numeric value (0-59). Adjusts the date, potentially changing the minute, hour, date, month, and year to ensure a valid date and time.
    setMilliseconds(ms)Sets the milliseconds of the date object (0-999). Accepts a numeric value (0-999). Adjusts the date, potentially changing the second, minute, hour, date, month, and year to ensure a valid date and time.
    setTime(milliseconds)The function sets the date and time in milliseconds since January 1, 1970; it accepts a numeric value. Then, the entire date object is transformed to reflect the provided milliseconds value.
    setUTCFullYear(year)Takes input as a 4 digit year and adjusts the Coordinated Universal Time or UTC, considering the leap years.
    setUTCMonth(month)Sets the UTC month of the date object (0-11). Accepts a numeric value (0-11). Adjusts the date in Coordinated Universal Time (UTC), potentially changing the year if the month value is outside the valid range.
    setUTCDate(day)Accepts numeric value between 1 to 31 and sets the UTC day of the month for that particular date object. It basically adjusts the date in Coordinated Universal Time (UTC), changing the month and year if the day value is in the valid range for the current month.
    setUTCHours(hours)Sets the UTC hour of the date object (0-23). Accepts a numeric value (0-23). Adjusts the date in Coordinated Universal Time (UTC), potentially changing the date, month, and year to ensure a valid date and time.
    setUTCMinutes(minutes)Sets the UTC minutes of the date object (0-59). Accepts a numeric value (0-59). Adjusts the date in Coordinated Universal Time (UTC), potentially changing the hour, date, month, and year to ensure a valid date and time.
    setUTCSeconds(seconds)Sets the UTC seconds of the date object (0-59). Accepts a numeric value (0-59). Adjusts the date in Coordinated Universal Time (UTC), potentially changing the minute, hour, date, month, and year to ensure a valid date and time.
    setUTCMilliseconds(ms)Sets the UTC milliseconds of the date object (0-999). Accepts a numeric value (0-999). Adjusts the date in Coordinated Universal Time (UTC), potentially changing the second, minute, hour, date, month, and year to ensure a valid date and time.

    Examples

    Example 1: Simple implementation of set methods

    We employ set methods to modify a variety of date components, thereby demonstrating the versatility inherent in each method. These adjustments to the current date accommodate diverse scenarios; they include not only adding years, months and days but also hours – even minutes and milliseconds.

    <!DOCTYPE html><html><body><div id="result"><p id="setFullYear"></p><p id="setMonth"></p><p id="setDate"></p><p id="setHours"></p><p id="setMinutes"></p><p id="setSeconds"></p><p id="setMilliseconds"></p><p id="setTime"></p><p id="setUTCFullYear"></p><p id="setUTCMonth"></p><p id="setUTCDate"></p><p id="setUTCHours"></p><p id="setUTCMinutes"></p><p id="setUTCSeconds"></p><p id="setUTCMilliseconds"></p></div><script>const currentDate =newDate();
    
      currentDate.setFullYear(currentDate.getFullYear()+1);
      document.getElementById("setFullYear").innerText =setFullYear: ${currentDate.toDateString()};
     
      currentDate.setMonth(currentDate.getMonth()+2);
      document.getElementById("setMonth").innerText =setMonth: ${currentDate.toDateString()};
      
    currentDate.setDate(currentDate.getDate()+5);
      document.getElementById("setDate").innerText =setDate: ${currentDate.toDateString()};
      currentDate.setHours(currentDate.getHours()+3);
      document.getElementById("setHours").innerText =setHours: ${currentDate.toDateString()};
      currentDate.setMinutes(currentDate.getMinutes()+15);
      document.getElementById("setMinutes").innerText =setMinutes: ${currentDate.toDateString()};
      
    currentDate.setSeconds(currentDate.getSeconds()+30);
      document.getElementById("setSeconds").innerText =setSeconds: ${currentDate.toDateString()};
      currentDate.setMilliseconds(currentDate.getMilliseconds()+500);
      document.getElementById("setMilliseconds").innerText =setMilliseconds: ${currentDate.toDateString()};
      
    currentDate.setTime(currentDate.getTime()+86400000);// 86400000 milliseconds in a day
      document.getElementById("setTime").innerText =setTime: ${currentDate.toDateString()};
      currentDate.setUTCFullYear(currentDate.getUTCFullYear()+1);
      document.getElementById("setUTCFullYear").innerText =setUTCFullYear: ${currentDate.toDateString()};
      currentDate.setUTCMonth(currentDate.getUTCMonth()+2);
      document.getElementById("setUTCMonth").innerText =setUTCMonth: ${currentDate.toDateString()};
      
    currentDate.setUTCDate(currentDate.getUTCDate()+5);
      document.getElementById("setUTCDate").innerText =setUTCDate: ${currentDate.toDateString()};
       
    currentDate.setUTCHours(currentDate.getUTCHours()+3);
      document.getElementById("setUTCHours").innerText =setUTCHours: ${currentDate.toDateString()};
      currentDate.setUTCMinutes(currentDate.getUTCMinutes()+15);
      document.getElementById("setUTCMinutes").innerText =setUTCMinutes: ${currentDate.toDateString()};
      currentDate.setUTCSeconds(currentDate.getUTCSeconds()+30);
      document.getElementById("setUTCSeconds").innerText =setUTCSeconds: ${currentDate.toDateString()};
      currentDate.setUTCMilliseconds(currentDate.getUTCMilliseconds()+500);
      document.getElementById("setUTCMilliseconds").innerText =setUTCMilliseconds: ${currentDate.toDateString()};&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example 2: Combining Set Date Methods for a Complex Update

    A sophisticated date manipulation combines multiple set methods: for instance, it adjusts the date by adding two years; subtracts one month then adds fifteen days. Finally with precision and accuracy, the time is set at 18:30:45.

    <!DOCTYPE html><html><body><div id="result"><h2>Complex Date Manipulation</h2><p id="complexManipulation"></p></div><script>const currentDate =newDate();// Combining multiple set methods for a complex update
    
     currentDate.setFullYear(currentDate.getFullYear()+2);
     currentDate.setMonth(currentDate.getMonth()-1);
     currentDate.setDate(currentDate.getDate()+15);
     currentDate.setHours(18);
     currentDate.setMinutes(30);
     currentDate.setSeconds(45);
     document.getElementById("complexManipulation").innerText =Complex Manipulation Result: ${currentDate.toDateString()} ${currentDate.toTimeString()};&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

  • Get Date Methods

    Get Date Methods

    JavaScript utilizes the Date object for date and time manipulation. This object offers an array of methods that facilitate retrieval and modification of date-specific information. Here, we will discuss about the get date methods within JavaScript which fetch different components of the date/time.

    Below is a table of the most commonly used get date methods and their corresponding description.

    MethodDescription
    getFullYear()This method fetches and presents the comprehensive calendar year by retrieving the current year in local time zone; it returns the full four-digit representation of a local date object.
    getMonth()Returns the month (0-11) of the local date object. This method retrieves the current month, with values ranging from 0 (January) to 11 (December). It’s useful for displaying and manipulating month-related information.
    getDate()The method: ‘returns the day component of the current date’, a value ranging from 1 to 31. This functionality proves particularly useful when one needs this information extracted from a local date object.
    getHours()The function ‘getHours()’ extracts and returns the local date object’s hour component (0-23). This allows you to retrieve the current hour in your local time zone for a variety of time-related applications.
    getMinutes()Returns the minutes (0-59) of the local date object. Retrieves the current minute component, ranging from 0 to 59. Useful for displaying and handling time-related data at the minute level.
    getSeconds()This returns the seconds ranging from 0 to 59 of the local date object. It provides precision down the seconds for a variety of time-based calculations/displays.
    getMilliseconds()Returns the milliseconds (0-999) of the local date object. Retrieves the current millisecond component, allowing for high precision in time-related applications and calculations.
    getDay()Returns the index of day of the week starting from 0 which stands for Sunday, all the way up to 6 for Saturday.
    getUTCFullYear()Returns the full 4-digit year of the date object in Coordinated Universal Time (UTC). This method retrieves the current year in UTC, providing a standardized representation of the calendar year irrespective of the local time zone.
    getUTCMonth()Returns the index of the month ranging from 0(Jan) to 11(Dec) but of the date object in Coordinated Universal Time (UTC).
    getUTCDate()Returns the day of the month (1-31) of the date object in Coordinated Universal Time (UTC). Useful for obtaining the day component of the current date in a UTC context.
    getUTCHours()Returns the hour (0-23) of the date object in Coordinated Universal Time (UTC). Retrieves the current hour in UTC, allowing for standardized access to the hour component across different time zones.
    getUTCMinutes()Returns the minutes (0-59) of the date object in Coordinated Universal Time (UTC). Retrieves the current minute component in UTC, providing standardized minute information for various international time-based applications.
    getUTCSeconds()The function fetches the seconds (ranging from 0 to 59) of a date object in Coordinated Universal Time (UTC). It also acquires the current second component in UTC, thereby enabling standardized second information across various time zones.
    getUTCMilliseconds()The function returns the milliseconds (0-999) of the date object in Coordinated Universal Time (UTC); it retrieves and offers high precision for standardized time-related calculations and applications: specifically, it provides the current millisecond component in UTC.

    Examples

    Example 1: Simple demonstration of get date methods

    The following example demonstrates the fundamental application of prevalent JavaScript date methods: It instantiates a novel Date object to represent the present date and time; subsequently, it exhibits an array of diverse components – year, month, day; hours, minutes, seconds, milliseconds; along with their corresponding UTC counterparts. The displayed elements encompass not only standard temporal divisions but also supplementary information about weekdays: thus providing comprehensive insight into current temporal dynamics.

    <!DOCTYPE html><html><head><title> Exxample to demonstrate get date methods in JavaScript</title></head><body><script>// Create a new Date objectconst currentDate =newDate();functiondisplayResult(methodName, result){const resultDiv = document.createElement('div');
    
         resultDiv.innerHTML =${methodName}: ${result};
         document.body.appendChild(resultDiv);}displayResult('getFullYear()', currentDate.getFullYear());displayResult('getMonth()', currentDate.getMonth());displayResult('getDate()', currentDate.getDate());displayResult('getHours()', currentDate.getHours());displayResult('getMinutes()', currentDate.getMinutes());displayResult('getSeconds()', currentDate.getSeconds());displayResult('getMilliseconds()', currentDate.getMilliseconds());displayResult('getDay()', currentDate.getDay());displayResult('getUTCFullYear()', currentDate.getUTCFullYear());displayResult('getUTCMonth()', currentDate.getUTCMonth());displayResult('getUTCDate()', currentDate.getUTCDate());displayResult('getUTCHours()', currentDate.getUTCHours());displayResult('getUTCMinutes()', currentDate.getUTCMinutes());displayResult('getUTCSeconds()', currentDate.getUTCSeconds());displayResult('getUTCMilliseconds()', currentDate.getUTCMilliseconds());&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example 2: Comparison of two dates

    In this example, the Date constructor creates two specific dates: date1 and date2. The script subsequently compares these dates; it displays their formatted representations, along with a message indicating if date1 is later, earlier or equal to date2.

    <!DOCTYPE html><html><head><title>Comparison of two dates in JavaScript</title></head><body><script>const date1 =newDate(2024,0,18);const date2 =newDate(2024,0,26);functiondisplayComparison(){const date1Div = document.createElement('div');
    
         date1Div.innerHTML =Date 1: ${date1.toDateString()};
         document.body.appendChild(date1Div);const date2Div = document.createElement('div');
         date2Div.innerHTML =Date 2: ${date2.toDateString()};
         document.body.appendChild(date2Div);const resultDiv = document.createElement('div');if(date1 &gt; date2){
            resultDiv.innerHTML ="date 1 is later than date 2";}elseif(date1 &lt; date2){
            resultDiv.innerHTML ="date 1 is earlier than date 2";}else{
            resultDiv.innerHTML ="Both dates are equal";}
         document.body.appendChild(resultDiv);}displayComparison();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

  • Date Formats

    Date Formats

    JavaScript offers us a variety of date formats ranging from elementary locale-specific formatting all the way up to sophisticated customization options. Understanding the different date formats is a fundamental and essential aspect of web development, irrespective of whether youre building a dynamic web application, managing time sensitive data or simply displaying dates in a user-friendly manner.

    Here, we are going to cover different date formats of JavaScript and implement them with a few examples to understand them better. Below is a table explaining all the different date formats used in JavaScript.

    FormatExampleDescription
    ISO Format (UTC)2024-01-29T12:34:56.789ZStandardized format with the year, month, day, and time components. The ‘Z’ indicates the time is in UTC (Coordinated Universal Time).
    Locale Date and Time1/29/2024, 12:34:56 PMIt is the localized date & time representation based on the users system or browsers settings and can vary in terms of symbols depending on the locale.
    Custom Date FormatJan 29, 2024, 12:34:56 PM PSTThe custom format allows developers to specify which components of the date (year, month, day, hour, minute, second) are to be included and in what format they should be occurring.
    Short Date Format01/29/24A short representation of the date with the month, day, and year. The order may vary based on the locale.
    Long Date FormatJanuary 29, 2024A long representation of the date with the full month name, day, and year.
    Short Time Format12:34 PMA short representation of the time with hours and minutes.
    Long Time Format12:34:56 PMA long representation of the time with hours, minutes, and seconds.
    UTC Date FormatTue, 29 Jan 2024 12:34:56 GMTCoordinated Universal Time (UTC) formatted date and time string. It includes the day of the week and the timezone abbreviation (GMT).
    Epoch Timestamp1643450096789The number of milliseconds since January 1, 1970, 00:00:00 UTC. Also known as Unix Timestamp. Useful for handling and comparing dates as numbers.
    Relative Time2 hours ago, 3 days agoA human-readable format that expresses the time difference in a relative manner, such as “ago” for past dates. Useful for displaying how much time has passed since a certain date.

    Examples

    Example 1: Displaying current date in different formats

    JavaScript in this example dynamically generates and displays a variety of date formats on the page: ISO format, locale date and time, custom date format; short and long date formats; short and long time formats; UTC date format, even an epoch timestamp. Furthermore, it calculates the relative time between two given dates current one being compared to a specified previous one and presents these results in human-readable form. This code exemplifies pragmatic techniques for formatting dates within an HTML context using JavaScript.

    <!DOCTYPE html><html><body><h2>All Types of Date Formats</h2><script>const currentDate =newDate();functionappendFormattedDate(type, formatFunction){const formattedDate =formatFunction(currentDate);const paragraph = document.createElement('p');
    
         paragraph.innerText =${type}: ${formattedDate};
         document.body.appendChild(paragraph);}appendFormattedDate('ISO Format (UTC)',date=&gt; date.toISOString());appendFormattedDate('Locale Date and Time',date=&gt; date.toLocaleString());const options ={ 
         year:'numeric', 
         month:'short', 
         day:'numeric', 
         hour:'2-digit', 
         minute:'2-digit', 
         second:'2-digit', 
         timeZoneName:'short'};appendFormattedDate('Custom Date Format',date=&gt; date.toLocaleString('en-US', options));appendFormattedDate('Short Date Format',date=&gt; date.toLocaleDateString());appendFormattedDate('Long Date Format',date=&gt; date.toLocaleDateString(undefined,{ year:'numeric', month:'long', day:'numeric'}));appendFormattedDate('Short Time Format',date=&gt; date.toLocaleTimeString());appendFormattedDate('Long Time Format',date=&gt; date.toLocaleTimeString(undefined,{ hour:'2-digit', minute:'2-digit', second:'2-digit'}));appendFormattedDate('UTC Date Format',date=&gt; date.toUTCString());appendFormattedDate('Epoch Timestamp',date=&gt; date.getTime());const previousDate =newDate('2024-01-29T00:00:00Z');const relativeTime =formatRelativeTime(previousDate, currentDate);appendFormattedDate('Relative Time',()=&gt; relativeTime);// Function to calculate relative timefunctionformatRelativeTime(previousDate, currentDate){const elapsedMilliseconds = currentDate - previousDate;const seconds = Math.floor(elapsedMilliseconds /1000);const minutes = Math.floor(seconds /60);const hours = Math.floor(minutes /60);if(seconds &lt;60){return${seconds} second${seconds !== 1 ? 's' : ''} ago;}elseif(minutes &lt;60){return${minutes} minute${minutes !== 1 ? 's' : ''} ago;}elseif(hours &lt;24){return${hours} hour${hours !== 1 ? 's' : ''} ago;}else{return'More than a day ago';}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example 2: Customized date formats

    This example gives us a deeper understanding of the customized date formats which do not have any prefix format and are up to the developer choose. We use the Intl.DateTimeFormat object to create our format of (weekday, month, day, year). With this option customized date formats we can choose not only the parts of the date to be made visible but also their order. A website might be more suitable if it displayed dates in dd/mm/yyyy in some countries but more user friendly if it displayed dates in mm-dd-yyyy in some other countries.

    <!DOCTYPE html><html><body><h2>Custom Date Format Example</h2><script>const currentDate =newDate();functioncustomDateFormat(date){const options ={ weekday:'long', month:'long', day:'numeric', year:'numeric'};returnnewIntl.DateTimeFormat('en-US', options).format(date);}// Function to append formatted date to the bodyfunctionappendFormattedDate(type, formatFunction){const formattedDate =formatFunction(currentDate);
    
         document.body.innerHTML +=&amp;lt;p&amp;gt;${type}: ${formattedDate}&amp;lt;/p&amp;gt;;}// Append custom date formatappendFormattedDate('Custom Date Format', customDateFormat);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example 3: Generating next 5 days dates

    In this example JavaScript generates future dates, specifically for the next five days based on the current date. Subsequently, it formats and displays these dates in three different ways; ISO format; locale-specific arrangement, and a custom layout are showcased on the web page. Without requiring any user input, JavaScript's date handling capabilities receive a practical illustration through dynamically generated dates from the generateFutureDates function.

    <!DOCTYPE html><html><body><h2>Future Dates Generator</h2><div id="futureDates"></div><script>functiongenerateFutureDates(){const today =newDate();const futureDatesDiv = document.getElementById('futureDates');for(let i =1; i <=5; i++){const futureDate =newDate(today.getTime()+ i *24*60*60*1000);// Adding 1 day for each iterationconst isoFormat = futureDate.toISOString();const localeFormat = futureDate.toLocaleString();const customFormatOptions ={ year:'numeric', month:'long', day:'numeric', hour:'2-digit', minute:'2-digit', second:'2-digit', timeZoneName:'short'};const customFormat = futureDate.toLocaleString('en-US', customFormatOptions);
    
    
            futureDatesDiv.innerHTML +=`
            &lt;p&gt;&lt;strong&gt;Day ${i}:&lt;/strong&gt;&lt;/p&gt;
            &lt;p&gt;ISO Format (UTC): ${isoFormat}&lt;/p&gt;
            &lt;p&gt;Locale Date and Time: ${localeFormat}&lt;/p&gt;
            &lt;p&gt;Custom Format: ${customFormat}&lt;/p&gt;
            &lt;hr&gt;
            `;}}generateFutureDates();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

  • Multiline Strings

    multiline string is a JavaScript string that spans multiple lines. Using multiline strings in programs make it easier to read and maintain. In JavaScript, the easiest way to create multiline strings is to use template literals (template strings). The template literals are introduced in ECMAScript 2015 (ES6). Before introduction of template literals, the multiline strings are created by concatenating multiple strings using + operator.

    In JavaScript, a string is a sequence of characters containing alphabetical, numeric, and special characters. We can create the string using single quote (‘), double quote (“) or backtick (`) characters.

    Creating Multiline Strings Using Template Literals

    The template literals are the best way to create multiline string in JavaScript. Template literals are enclosed with backtick (`) characters. A template literal contains strings and also placeholders. Template literals are sometimes also called template strings.

    A simple example of a template literal is as follows −

    This is a template literal enclosed by backtick characters.

    Let’s now create a multiline string using template literals −

    let multilineString =`This is a multiline
    string created using
    template literal.`

    In the above JavaScript code snippet, we have created a multiline string containing three lines. We assigned this multiline string to the variable called multilineString.

    Example

    In the below example, we have created a multiline string using template literal and displayed the string in the web console.

    let mulString =`This is a multiline
    string created using
    template literal.`;
    console.log(mulString);

    Output

    This is a multiline
    string created using
    template literal.
    

    Example

    In the below example, we are trying to display the multiline string crated using the template literal on the webpage. We used <br> to make a line break.

    <!DOCTYPE html><html><body><p id ="output"></p><script>let mulString =`This is a multine <br>
    
      string created using template literal &lt;br&gt;
      and displayed on the webpage.`;    
      document.getElementById("output").innerHTML = mulString;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    This is a multine
    string created using template literal
    and displayed on the webpage.
    

    Creating Multiline String Using + Operator

    We can also create a multiline string in JavaScript by concatenating the individual strings using + operator. To create a line break, we can use the escape character \n or <br>.

    You can concatenate the strings defined with single or double quotes.

    Let's have a look at the following example −

    Example

    In this example, we created a multiline string by concatenating three individual strings. We used escape character (\n) at the end of the individual strings to break the line.

    let mulString ="This is a multiline string\n"+"created by concatenating the individual strings\n"+"and using \\n to break the line.";
    console.log(mulString);

    Output

    This is a multiline string
    created by concatenating the individual strings
    and using \n to break the line.
    

    Example

    In the example below, we created a multiline string by concatenating three strings. We used <br> to break the line.

    <!DOCTYPE html><html><body><p id ="output"></p><script>let mulString ="This is a multiline string <br>"+"created by concatenating the individual strings<br>"+"and line break.";  
    
      document.getElementById("output").innerHTML = mulString;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    This is a multiline string
    created by concatenating the individual strings
    and line break.
    

    Creating Multiline String Using \ Operator

    We can use backslash (\) operator to create multiline strings in JavaScript. We can use the escape character (\n) to break the line.

    Example

    Try the following JavaScript example −

    let mulString ="This is a multiline string\n\
    created using the backslash operator\n\
    and escape character to break the line.";
    console.log(mulString);

    Output

    This is a multiline string
    created using the backslash operator
    and escape character to break the line.
    

    Example

    In the example below, we have created a multiline string using the backslash (\) operator. And to make a line break, we used <br>.

    <!DOCTYPE html><html><body><p id ="output"></p><script>let mulString ="This is first line of the multiline string <br>\
    
      This is second line of the multiline string &lt;br&gt; \
      This is the last line of multiline string.";    
      document.getElementById("output").innerHTML = mulString;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    This is first line of the multiline string
    This is second line of the multiline string
    This is the last line of multiline string.