Blog

  • JavaScript – Clickjacking Attack

    Clickjacking Attack

    An attacker employs clickjacking, a form of cyber-attack, to deceive a user into clicking on an object different from their perception; this deception may result in unintended actions. The attacker achieves this by overlaying invisible elements or frames over valid content thus camouflaging the malicious intent or manipulating the appearance of webpage elements outright.

    Severe risks such as unauthorized financial transactions, potential data breaches and compromise of sensitive information are posed by clickjacking. Clickjacking impacts users and website owners alike leading to legal consequences, financial loss, and heightened cybersecurity concerns. The deceptive nature of clickjacking can erode user trust with far-reaching consequences in the digital ecosystem.

    Disclaimer: The contents of this chapter are only for education purposes!

    How clickjacking works?

    Overlaying Content

    • The attackers create a malicious/spam/scam website or injects malicious code into a website which is actually legitimate in nature.
    • The attacker positions invisible elements or frames over the legitimate content on the page. These elements can be transparent iframes or other HTML elements.

    Deceptive Presentation

    • The attacker then entices the user to interact with the visible elements on the page, which are typically buttons, links, or forms.
    • However, these visible elements are actually on top of the invisible, malicious elements.

    User Interaction

    • When the user interacts with the visible elements (clicking, typing, etc.), they are unknowingly interacting with the hidden, malicious elements that are overlaid on top of the legitimate content.

    Unintended Actions

    • The attacker can manipulate the hidden elements to perform unintended actions on behalf of the user. This could include making unwanted transactions, changing account settings, or even submitting sensitive information.

    User Unawareness

    • Because the user believes they are interacting with the visible elements they see, they remain unaware that their actions are being redirected to perform malicious activities.

    Examples

    Example 1: Button Overlay

    The provided HTML code demonstrates a button overlay clickjacking example. The button is presented to the user, but it is actually overlaid on a hidden, malicious iframe, leading the user to a potentially harmful page.

    home.html

    <!DOCTYPE html><html><body><h2>This is content of the home page</h2><iframe src="legitimate-site.html" width="100%" height="100%"></iframe><div><button onclick="window.location.href='malicious-site.html'">Click Me</button></div></body></html>

    legitimate-site.html

    <!DOCTYPE html><html><body><header><h1>Welcome to Legitimate Site</h1></header><section><p>This is a legitimate website. You can trust the content here.</p></section><footer><p>© 2024 Legitimate Site. All rights reserved.</p></footer></body></html>

    malicious-site.html

    <!DOCTYPE html><html><head><style>
          body {
             font-family: Arial, sans-serif;}.danger-sign {
             color: red;
             font-size:2em;}.warning-message {
             color: red;
             font-weight: bold;}</style></head><body><header><h1 class="danger-sign"> Danger: Malicious Site</h1></header><section><p class="warning-message">This website has been identified as potentially harmful. Visiting it may pose a security risk to your computer and personal information.</p></section><footer><p>Please close this page immediately and do not proceed.</p></footer></body></html>

    Output

    Clickjacking Attack

    Example 2

    When the webpage loads in this example, it initiates an automatic click on a button identified as “clickMe.” This specific button, upon receiving user interaction by means of clicking, activates a JavaScript event that re-routes the user to a potentially harmful site named ‘malicious-site.html.’ Such covert manipulation disconcertingly guides users towards unintended destinations without their knowledge or consent. Always note: these practices are indeed, potentially harmful and unethical in nature; one must approach them with responsibility and within legal and ethical boundaries.

    The malicious-site.html code is same as above.

    home.html

    <!DOCTYPE html><html><head><style>
          body {
             display: flex;
             align-items: center;
             justify-content: center;
             height:100vh;
             margin:0;}
    
          button {
             position: absolute;
             z-index:1;
             background-color: transparent;
             border: none;
             font-size:20px;
             cursor: pointer;}</style></head><body onload="myFunction()"><h2>Your Content Goes Here</h2><button id="clickMe">Click Me</button><script>
          window.onload=function(){var button = document.getElementById("clickMe");
             button.click();};
          document.getElementById("clickMe").addEventListener("click",function(){
             window.location.href ="malicious-site.html";});</script></body></html>

    Output

    Clickjacking Attack

    Real World Clickjacking Incidents

    1. Facebook “Like” Button (2011)

    Attackers overlaid a malicious “Like” button on an enticing video thumbnail, tricking users into unknowingly liking a malicious page.

    2. Adobe Flash Update Scam (2015):

    Malicious buttons disguised as Adobe Flash updates were overlayed on legitimate websites, leading users to unwittingly download malware.

    3. Twitter Clickjacking Attack

    Malicious links on Twitter, disguised as enticing content, led users to unintentionally retweet and spread malicious content.

    4. LinkedIn Fake Connection Requests

    Clickjacking was used to trick LinkedIn users into connecting with fake profiles by overlaying connection request buttons on seemingly innocent content.

    5. Google Play Store Deception

    Malicious overlays on the Google Play Store tricked users into unintended downloads or actions, often related to ads.

    Preventive Measures

    1. X-Frame-Options Header

    Set the X-Frame-Options header to DENY or SAMEORIGIN in your web server’s response to prevent your site from being embedded in iframes.

    2. Frame-Busting Scripts

    Implement frame-busting scripts in your web pages to prevent them from being embedded in iframes.

    3. Content Security Policy (CSP)

    Use Content Security Policy headers to control the sources from which your website can load content, reducing the risk of clickjacking.

    4. User Education

    Educate users about potential risks associated with interacting with unfamiliar or suspicious-looking content.

    As cybersecurity evolves, future trends in clickjacking may include more sophisticated techniques leveraging artificial intelligence, increased use of social engineering tactics, and a focus on bypassing advanced security measures. Additionally, with the rise of emerging technologies like augmented reality (AR) and virtual reality (VR), new vectors for immersive clickjacking experiences may emerge, demanding continuous innovation in defensive strategies and user awareness.

  • JavaScript – IndexedDB

    What is IndexedDB?

    IndexedDB, or Indexed Database, represents a low-level JavaScript API. Its function involves the storage and retrieval of voluminous structured data – this includes files and blobs. With its capabilities to work with client-side databases: it enables web applications to locally store, query, and modify data on the user’s device. This functionality proves particularly advantageous when constructing web applications that confront significant data volumes; operate without an internet connection, working offline and deliver responsive user experiences through local data caching.

    Key concepts and features of IndexedDB:

    • Asynchronous API − Relying on event-driven programming, IndexedDB utilizes an asynchronous API to prevent main-thread blocking and enhance user experience.
    • Database − IndexedDB databases, functioning as containers for object stores, facilitate the organization, retrieval and deletion of data.
    • Object Store − An object store akin to a table in a relational database, encapsulates collections of JavaScript objects; it provides support for CRUD operations.
    • Index − Indexes in object stores can enhance the efficiency of data querying, as they are able to improve search and sort performance based on specific fields.
    • Transactions − Transactions in IndexedDB perform all operations, guaranteeing consistency and integrity through their ability to make multiple actions either succeed or fail as a unit.

    Why use IndexedDB?

    Web developers, in their search for efficient client-side storage solutions, find IndexedDB indispensable. Its asynchronous nature guarantees a responsive user experience: it thwarts main-thread blocking; moreover, its support for transactions by maintaining data integrity is commendable. IndexedDB is capable of managing significant volumes of structured data locally; this capability significantly enhances offline functionality a reduction on the need for relentless server communication. With its flexible key structure, indexing support for optimized queries, and the ability to upgrade schema; it stands as a robust choice for constructing web applications. These applications often require local storage, offline support and most importantly effective data management.

    CRUD Operations

    Let us now see the CRUD operation codes with IndexedDB.

    Create/Insert Operation

    To insert a new record into an object store, you utilize the add() method in IndexedDB. This method accepts a JavaScript object or value as its parameter and subsequently incorporates it within the designated object store. However, if there already exists an entry with identical key parameters; this operation will fail, thus rendering it ideal for guaranteeing uniqueness.

    const request = objectStore.add(data);
    request.onsuccess=()=>{// Handle success event};
    
    request.onerror=()=>{// Handle error};

    Read (Retrieve) Opeation

    The get() Method

    Utilize the get() method: it retrieves a singular record from an object store, this action is contingent upon your possession of knowledge regarding the specific key for your intended entry.

    The openCursor() Method

    Initiating an active cursor that iterates through records within an object store, the openCursor() method enhances efficiency and control by allowing for processing each individual entry; this proves useful in traversing all entries present in the said object store.

    const request = objectStore.openCursor();
    request.onsuccess=(event)=>{const cursor = event.target.result;if(cursor){const data = cursor.value;// Process data
          cursor.continue();}};
    
    request.onerror=()=>{// Handle error};

    Update Operation

    The put() method updates an existing record or adds a new one when the key doesn’t exist. Its versatility renders it suitable for data manipulation, specifically updating and inserting.

    const request = objectStore.put(data);

    Delete Operation

    To remove a specific record from an object store based on its key, one must employ the delete() method; this method offers a direct approach for deleting entries.

    const request = objectStore.delete(key);

    Implementation Example

    All the important methods of the above CRUD operation are implemented in this code. It presents database data as a table, each record accompanied by delete and update buttons. When you click on the create button, it displays an element for form creation on screen; thereby allowing entry of name and email to be inserted into the database. By default, this form remains hidden; it only appears upon button click and subsequently vanishes when its task is complete. The ‘prompt()’ method populates the details update form, a feature that provides convenience for users as alerts also appear in this same location. Moreover: pertinent alerts serve to signal either successful events or errors to the user.

    <!DOCTYPE html><html><head><style>
          body {
             font-family: Arial, sans-serif;
             margin:20px;}
          h2 {
             color: #333;}
    
          button {
             padding:8px;
             margin:5px;}
    
          #createForm, #updateForm {
             display: none;
             border:1px solid #ddd;
             padding:10px;
             margin-bottom:10px;}
    
          table {
             border-collapse: collapse;
             width:100%;
             margin-top:20px;
             width: auto;}
    
          th, td {
             border:1px solid #dddddd;
             text-align: left;
             padding:8px;}
    
          th {
             background-color: #f2f2f2;}</style></head><body><h2>IndexedDB CRUD Operations</h2><button onclick="showCreateForm()">Create Data</button><div id="createForm" style="display: none;">// hidden by default, displayed on create button click<h3>Create Data</h3><label for="name">Name:</label><input type="text" id="name" required><br><br><label for="email">Email:</label><input type="email" id="email" required><br><button onclick="createData()">Save</button><button onclick="cancelCreate()">Cancel</button></div><table id="data-table"><thead><tr><th>ID</th><th>Name</th><th>Email</th><th>Actions</th></tr></thead><tbody></tbody></table><script>const dbName ="myDatabase";let db;// Open/create indexedDB named myDatabase with version 11const request = window.indexedDB.open(dbName,11);
          request.onerror=(event)=>{alert("Database error: "+ event.target.errorCode);};
    
          request.onsuccess=(event)=>{
             db = event.target.result;showData();};
          request.onupgradeneeded=(event)=>{
             db = event.target.result;const objectStore = db.createObjectStore("myObjectStore",{ keyPath:"id", autoIncrement:true});
             objectStore.createIndex("name","name",{ unique:false});
             objectStore.createIndex("email","email",{ unique:true});};functionshowData(){//populates the table from the dbconst transaction = db.transaction(["myObjectStore"],"readonly");const objectStore = transaction.objectStore("myObjectStore");const tableBody = document.querySelector("#data-table tbody");
             tableBody.innerHTML ="";const request = objectStore.openCursor();
             request.onsuccess=(event)=>{const cursor = event.target.result;if(cursor){const row = tableBody.insertRow();
                   row.insertCell(0).textContent = cursor.value.id;
                   row.insertCell(1).textContent = cursor.value.name;
                   row.insertCell(2).textContent = cursor.value.email;const actionsCell = row.insertCell(3);//update & delete is performed on the basis of id, hence id is passed as parameter to functions when corresponding button is clicked
                   actionsCell.innerHTML =`
                   <button onclick="showUpdateForm(${cursor.value.id})">Update</button>
                   <button onclick="deleteData(${cursor.value.id})">Delete</button>
                        `;
                   cursor.continue();}};}functioncreateData(){const transaction = db.transaction(["myObjectStore"],"readwrite");const objectStore = transaction.objectStore("myObjectStore");const name = document.getElementById("name").value;const email = document.getElementById("email").value;const newData ={
                name: name,
                email: email
             };const request = objectStore.add(newData);
    
             request.onsuccess=()=>{showData();cancelCreate();alert("Data added successfully")};
    
             request.onerror=()=>{alert("Error creating data.");};}functionshowCreateForm(){
             document.getElementById("createForm").style.display ="block";}functioncancelCreate(){//if the user decides to not insert the record.
          document.getElementById("createForm").style.display ="none";
             document.getElementById("name").value ="";
             document.getElementById("email").value ="";}functionshowUpdateForm(id){const transaction = db.transaction(["myObjectStore"],"readwrite");const objectStore = transaction.objectStore("myObjectStore");const request = objectStore.get(id);
    
             request.onsuccess=(event)=>{const data = event.target.result;if(data){const name =prompt("Update Name:", data.name);const email =prompt("Update Email:", data.email);if(name !==null&& email !==null){
                      data.name = name;
                      data.email = email;const updateRequest = objectStore.put(data);
    
                      updateRequest.onsuccess=()=>{showData();alert("Updated data for "+data.name)};
    
                      updateRequest.onerror=()=>{alert("Error updating data.");};}}};}functiondeleteData(id){const transaction = db.transaction(["myObjectStore"],"readwrite");const objectStore = transaction.objectStore("myObjectStore");const request = objectStore.delete(id);
     
             request.onsuccess=()=>{showData();alert("Deleted data for id "+id)};
    
             request.onerror=()=>{alert("Error deleting data.");};}</script></body></html>

    Try running the above program. In the output, you will get an interface to create, update, and delete data. The newly created or updated data will appear in tabular form just after the operation is finished.

  • JavaScript – Reference Type

    JavaScript Reference Type

    There are two types of data types in JavaScript: primitive and reference type.

    Primitive data types are immutable, which means that they cannot be changed. The primitive data types in JavaScript are: Number, String, Boolean, Undefined, Null, Symbol.

    Reference data types are mutable, which means that they can be changed. The reference data types in JavaScript are: Object, Array, Function.

    When you assign a primitive data type to a variable, the variable gets a copy of the value. When you assign a reference data type to a variable, the variable gets a reference to the value. This means that if you change the value of a reference data type, the change will be reflected in all of the variables that reference that value.

    For example, the following code creates two variables, x and y, and assigns them the value 10:

    let x =10;let y =10;

    The variables x and y both have a copy of the value 10. If you change the value of x, the value of y will not change.

    x =20;
    console.log(x);// 20
    console.log(y);// 10

    The following code creates two variables, x and y, and assigns them an array:

    const x =[1,2,3];const y = x;

    The variables x and y both reference the same array. If you change the value of the array that x references, the change will be reflected in the array that y references.

    x[0]=4;
    console.log(x);// [4, 2, 3]
    console.log(y);// [4, 2, 3]

    It is important to understand the difference between primitive and reference data types in JavaScript so that you can write code that is efficient and predictable.

    Objects and functions are the two main reference types in JavaScript and are explained as follows.

    Object

    Objects are unordered collections of key-value pairs, where keys are strings or symbols, and values can be any data type, including other objects.

    const person ={
      firstName:"John",
      lastName:"Doe",
      age:30};

    Function

    Functions are also reference types in JavaScript. Functions are special types of objects that can be invoked (called) to perform a task.

    functiongreet(name){alert("Hello, "+ name +"!");}

    Examples

    Example 1: Object Mutability

    In this example, we demonstrate object mutability for which first an object is created and then modifications are made through that reference which in turn affect the original object. The person object is modified via the reference from the anotherPerson precisely the age which is changed from 25 to 30. As seen in the output, the original object changes after the modification hence the object is said to be mutated.

    <!DOCTYPE html><html><body><h2>JavaScript Reference Types Example: Object Mutability</h2><script>// Create an objectconst person ={
             name:"John",
             age:25};// Create a reference to the objectlet anotherPerson = person;// Display the original object
          document.write("<p>Original Object: "+JSON.stringify(person)+"</p>");// Modify the object through the reference
          anotherPerson.age =30;// Display the modified object
          document.write("<p>Modified Object: "+JSON.stringify(person)+"</p>");// Both references point to the same object, so changes are reflected in both
          document.write("<p>Original Object after modification through reference: "+JSON.stringify(person)+"</p>");</script></body></html>

    Example 2: Array Modification

    Arrays which can store multiple values of different data types in JavaScript inside of a single variable are demonstrated here. They exhibit mutability which means then when a reference is made to an array, changes made to the reference also reflect in the original array. Here we create an array of colors and modify it through the reference of moreColors, mainly by pushing an element yellow.

    <!DOCTYPE html><html><body><h2>JavaScript Reference Types Example: Array Modification</h2><script>// Create an arrayconst colors =["red","green","blue"];// Create a reference to the array let moreColors = colors;// Display the original array
          document.write("<p>Original Array: "+JSON.stringify(colors)+"</p>");// Modify the array through the reference
          moreColors.push("yellow");// Display the modified array
          document.write("<p>Modified Array: "+JSON.stringify(colors)+"</p>");// Both references point to the same array, so changes are reflected in both
          document.write("<p>Original Array after modification through reference: "+JSON.stringify(colors)+"</p>");</script></body></html>

    Example 3: Function Reference Type

    In this example, we create a function greet whose reference is initially assigned to greetingFunction. After using it to say Hello, we modify the reference to point to a different function which greets with Hola. This demonstrated the flexibility of function references in JavaScript.

    <!DOCTYPE html><html><body><h2>JavaScript Reference Types Example: Function Invocation</h2><script>// Create a functionfunctiongreet(name){return"Hello, "+ name +"!";}// Create a reference to the functionlet greetingFunction = greet;
    
          document.write("<p>Original Function Result: "+greetingFunction("John")+"</p>");greetingFunction=function(name){return"Hola, "+ name +"!";};
    
          document.write("<p>Modified Function Result: "+greetingFunction("Maria")+"</p>");</script></body></html>

    Example 4: Custom class

    This example demonstrated custom classes in JavaScript another crucial aspect from the point of view reference types. The class consists of properties and functions/methods. Here we create a class Book with a constructor and a method. 4 instances of this book class are created namely (book1, book2, book3, book4) and are given the respective data such as title, author and genre.

    <!DOCTYPE html><html><body><h2>JavaScript Reference Types Example: Custom class</h2><script>// Define a custom class for BookclassBook{constructor(title, author, genre){this.title = title;this.author = author;this.genre = genre;}// Method to get book detailsgetDetails(){return`Title: ${this.title}<br>Author: ${this.author}<br>Genre: ${this.genre}`;}}// Create instances of the Book classconst book1 =newBook("The Great Gatsby","F. Scott Fitzgerald","Fiction");const book2 =newBook("To Kill a Mockingbird","Harper Lee","Classics");const book3 =newBook("Harry Potter and the Sorcerer's Stone","J.K. Rowling","Fantasy");const book4 =newBook("1984","George Orwell","Dystopian Fiction");
    
          document.write("<h3>Book 1 Details:</h3>");
          document.write("<p>"+ book1.getDetails()+"</p>");
    
          document.write("<h3>Book 2 Details:</h3>");
          document.write("<p>"+ book2.getDetails()+"</p>");
    
          document.write("<h3>Book 3 Details:</h3>");
          document.write("<p>"+ book3.getDetails()+"</p>");
    
          document.write("<h3>Book 4 Details:</h3>");
          document.write("<p>"+ book4.getDetails()+"</p>");</script></body></html>

    Example 5: Immutable Objects

    This example focuses on immutability of objects which is achieved using the Object.freeze() while creating the object. Immutability basically means the object will not change after creation or simply ensures that once an object is defined, its properties cannot be modified. Here we create a person object with name & age as properties and then attempt to change the age to 35. However, this modification is prevented by the frozen state of the object and throws an error. Immutability is an important aspect as helps maintain data integrity thereby preventing unintended changes and enhancing the predictability in code execution.

    <!DOCTYPE html><html><body><h2>Immutable Object with Error Handling</h2><script>// Enable strict mode'use strict';// Create an immutable objectconst person = Object.freeze({
             name:"Alice",
             age:30});
    
          document.write("<p><strong>Before Modification:</strong></p>");
          document.write("<p>Name: "+ person.name +"</p>");
          document.write("<p>Age: "+ person.age +"</p>");try{// Attempting to modify the object will result in an error
             person.age =35;}catch(error){
             document.write(error);}
    
          document.write("<p><strong>After Modification Attempt:</strong></p>");
          document.write("<p>Name: "+ person.name +"</p>");
          document.write("<p>Age: "+ person.age +"</p>");</script></body></html>
  • JavaScript – Call Stack

    JavaScript engine uses the call stacks to manage the execution context. It is an important mechanism by which a JavaScript run engine keeps track of the function calls in a JavaScript code. However, the working of the JavaScript call stack is performed internally, but it is important to understand how JavaScript executes the functions.

    JavaScript call stack keeps track of what function or block of code needs to run currently. It works in the LIFO (Last In, First Out) manner. So, whatever function is added at the top in the call stack it gets executed first.

    How JavaScript Call Stack Works?

    Whenever you execute any JavaScript code, it adds the global execution context to the script.

    When you call any function, the JavaScript engine adds the function to the call stack. After that, when you call any nested function from the outer function, it adds a nested function in the call stack.

    When the execution of the inner function is complete, it pops the function from the call stack. Next, it executes the outer function and pops it from the call stack. Again, it starts executing the code in the global context.

    When the call stack becomes empty, the script stops running.

    Let’s understand the JavaScript call stack via example.

    functiontwo(){
      console.log("this is function two");}functionone(){two();
      console.log("This is function one");}one();

    The above code would be executed like this.

    1. When the execution of the code starts, the call stack remains empty until execution reaches the one() function.

    2. Add function one() in the call stack. Now, the call stack is [one()].

    3. Execute the first line of function one(), which calls the function two().

    4. Add function two() in the call stack. Now, the call stack is [two(), one()].

    5. Execute all lines of function two().

    6. Move back to execute the remaining lines of code of function one().

    7. Delete the function two() from the call stack. Now, the call stack is [one()].

    8. Start executing the remaining code of the function one(). When the execution of function one() completes, the JavaScript engine starts executing the remaining code.

    9. Delete function one() from the call stack. Now, the call stack is empty.

    10. Execute the remaining code.

    Example

    Whenever we execute the below code, it will add the global execution context in the call stack. Whenever it calls any function from the global execution contest, it will add that function to the call stack, and start executing that function first.

    When another function is called from the particular function, it gets added to the call stack and gets priority for the execution.

    When the execution of the particular function is finished, the interpreter removes it from the call stack.

    Whenever a stack takes more space than its size, it throws the ‘stack overflow’ error.

    <html><body><h2> JavaScript - Call stack </h2><div id ="output"></div><script>const output = document.getElementById("output");functiontwo(){
            output.innerHTML +="two <br>";}functionone(){two();
            output.innerHTML +="one <br>";}one();</script></body></html>

    JavaScript Call Stack Overflow

    Whenever the size of the call stack exceeds the defined size, a call stack overflow occurs. Generally, whenever a recursive function doesn’t have an exit point call, a stack overflow occurs.

    For example, in the code below, the fib() function doesn’t have an exit point. So, it throws a call stack overflow error.

    functionfib(){fib();}fib();

    Javascript is a single-thread programming language. So, it runs the code line-by-line from top to bottom. It means a JavaScript program can have only 1 call stack, and it can execute one line at a time.

  • JavaScript – 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);</script></body></html>

    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);</script></body></html>

    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);</script></body></html>

    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);</script></body></html>

    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);</script></body></html>

    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.

  • JavaScript – 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;</script></body></html>

    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;</script></body></html>

    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;</script></body></html>

    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;</script></body></html>

    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;</script></body></html>

    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.

  • JavaScript – 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);</script></body></html>

    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;</script></body></html>

    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 ='<img src="'+ url +'" />';};
            reader.readAsArrayBuffer(file);});</script></body></html>

    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.
  • JavaScript – 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} & ${num2} is ${sum} and their product: ${product}`;});</script></body></html>

    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(", ");});</script></body></html>

    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();});</script></body></html>

    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;}</style></head><body><h2>BigInt Color Example</h2><div id="colorSquare"></div><script>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();</script></body></html>

    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 =`<p>Regular Number: ${regularNumber}</p>`+`<p>BigInt Value: ${bigIntValue}</p>`+`<p>Regular Number + BigInt Value results in:</p>`;try{const result = regularNumber + bigIntValue;
             document.getElementById("output").innerHTML +=`Result: ${result}`;}catch(e){
             document.getElementById("output").innerHTML +=`Error: ${e}`;}</script></body></html>
  • JavaScript – 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";}</script></body></html>

    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()=>{let module =awaitimport('./test.js');let result = module.add(2,3);
             output.innerHTML ="The sum of 2 and 3 is "+ result;});</script></body></html>

    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.

  • JavaScript – 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);</script></body></html>

    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+"<br> The addition of 2 and 3 is "+sum(2,3)+"<br> The value of PI is "+PI;</script></body></html>

    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 +"<br>"+"The value of v2 is : "+ v2;</script></body></html>

    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';

    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.