Understanding JavaScript Concepts

A beginner's guide to essential JavaScript concepts.

JavaScript’s Functionality in the Browser

1. Event Loop

The Event Loop is a JavaScript mechanism that handles asynchronous operations, allowing non-blocking code execution. JavaScript runs in a single thread, so the Event Loop helps manage asynchronous tasks without halting code execution, which is crucial for handling user interactions and API requests smoothly.

How It Works:


    console.log("Start");
    
    setTimeout(() => {
      console.log("Inside Timeout");
    }, 0);
    
    console.log("End");
    
    // Output: "Start", "End", "Inside Timeout"
        

Explanation: Although setTimeout is set to zero milliseconds, its callback is still sent to the Callback Queue, so it runs after synchronous tasks (console.log("End")).

2. Browser APIs

Browser APIs provide built-in functionalities to interact with the web browser. Commonly used Browser APIs include LocalStorage, SessionStorage, and the Fetch API.

LocalStorage

LocalStorage is used for storing data that persists across browser sessions. It stores key-value pairs as strings and is limited in size (typically around 5MB).


    // Save data
    localStorage.setItem("username", "Alice");
    
    // Retrieve data
    const username = localStorage.getItem("username");
    console.log(username); // Output: "Alice"
    
    // Remove data
    localStorage.removeItem("username");
    
    // Clear all data
    localStorage.clear();
        

Fetch API

The Fetch API allows for making network requests, such as retrieving data from a server. It returns Promises, enabling handling of asynchronous responses.


    fetch("https://jsonplaceholder.typicode.com/posts/1")
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.error("Error:", error));
        

Explanation: fetch sends a GET request to retrieve data from the provided URL, and .then() handles the JSON response.

3. Web Components

Web Components are a set of standardized APIs that allow developers to create reusable custom HTML elements. Web Components consist of three main technologies:

Example: Creating a simple <user-card> component:


            <user-card></user-card>
            
            <script>
              class UserCard extends HTMLElement {
                constructor() {
                  super();
                  // Attach a shadow DOM
                  this.attachShadow({ mode: 'open' });
            
                  // Template content
                  const template = document.createElement('template');
                  template.innerHTML = `
                    <style>
                      h2 { color: blue; }
                    </style>
                    <div>
                      <h2>User Card</h2>
                      <p>Name: <slot name="username"></slot></p>
                    </div>
                  `;
            
                  // Attach template content to shadow DOM
                  this.shadowRoot.appendChild(template.content.cloneNode(true));
                }
              }
            
              // Define the new element
              customElements.define("user-card", UserCard);
            </script>
            

Explanation: Here, a UserCard class extends HTMLElement to create a new <user-card> element. Shadow DOM encapsulates the element’s styles and structure, so it remains isolated from the rest of the document.