Important JavaScript topics :

·

7 min read

In this blog we are going to learn about some most important topics of JavaScript before diving into the topics lets discuss about what is JavaScript :

JavaScript is a high-level, interpreted programming language that enables developers to create dynamic and interactive content on websites. It is primarily executed in web browsers to enhance user experience by allowing manipulation of the Document Object Model (DOM) and handling events.

Understanding how JavaScript code gets executed, making it asynchronous, the event loop, callbacks, and web browser APIs are fundamental concepts for any web developer. In this blog post, we'll delve into these concepts, shedding light on the inner workings of JavaScript.

How does JavaScript code gets executed :

  • JavaScript is an interpreted language that runs in a single-threaded environment, meaning it processes one task at a time. The process of executing JavaScript code involves several key steps:

    a. Parsing: The JavaScript engine parses the source code and converts it into an Abstract Syntax Tree (AST).

    b. Compilation: The AST is then compiled into machine code or bytecode.

    c. Execution: The compiled code is executed line by line, creating variables, and manipulating the program's state.

Now lets dive into how code works behind the scene in javaScript engine:

  1. Call Stack:

    • Manages the execution flow of JavaScript code in a Last In, First Out (LIFO) order.

    • Functions are added to the stack when called and executed sequentially.

  2. Web APIs:

    • Browser-specific functionalities provided to JavaScript, such as timers and DOM manipulation.

    • Asynchronous tasks trigger the offloading of operations to the Web API.

  3. Callback Queue:

    • Holds callback functions ready for execution after asynchronous tasks complete.

    • Once an operation finishes, its callback is placed in the Callback Queue.

  4. Event Loop:

    • Continuously checks the Call Stack and Callback Queue.

    • If the Call Stack is empty, it takes the first callback from the Queue and pushes it onto the Stack for execution.

  5. Execution Flow:

    • Code starts executing in the global context, with functions added to the Call Stack.

    • Asynchronous tasks are offloaded to Web APIs, and their callbacks go to the Callback Queue.

    • The Event Loop monitors the Call Stack, pushing callbacks onto it when the stack is empty.

  • Lets see the inplementation part :

// Parsing: JavaScript engine parses the source code
const num1 = 5;
const num2 = 10;
// Compilation: AST is compiled into machine code or bytecode
// Execution: Compiled code is executed line by line
const sum = num1 + num2;
console.log("Sum:", sum);

// Asynchronous operation example (using setTimeout)
// setTimeout represents an asynchronous operation that 
// will be executed after a delay
setTimeout(() => {
  console.log("Asynchronous operation completed");
}, 2000);

console.log("End of the program");

Understanding this sequential execution is crucial, but often, it becomes necessary to introduce asynchronous behavior for improved performance and responsiveness.

Ways to Make Code Asynchronous:

JavaScript provides several mechanisms to make code asynchronous and non-blocking:

a. Callbacks: Functions that are passed as arguments and executed later, typically when an asynchronous operation completes.Here is an example callback is passed to a function

function fetchData(callback) {
    setTimeout(function() {
        console.log("Data fetched");
        callback();
    }, 1000);
}

console.log("Start");
fetchData(function() {
    console.log("Callback executed");
});
console.log("End");

b. Promises : A more modern approach that represents a value that might be available now, in the future, or never, handling asynchronous operations in a more structured way.Promises can be in one of three states: pending, fulfilled, or rejected.

function fetchData() {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            console.log("Data fetched");
            resolve();
        }, 1000);
    });
}

console.log("Start");
fetchData().then(function() {
    console.log("Promise resolved");
});
console.log("End");

c. Async/Await: Introduced in ES2017, this syntax simplifies asynchronous code by allowing developers to write it in a more synchronous style.Async/Await is a syntactic sugar built on top of Promises, making asynchronous code look more like synchronous code. The async keyword is used to define a function that returns a Promise, and the await keyword is used within the function to wait for the resolution of a Promise.

function fetchData() {
    return new Promise(function(resolve) {
        setTimeout(function() {
            console.log("Data fetched");
            resolve();
        }, 1000);
    });
}

async function fetchDataAsync() {
    console.log("Start");
    await fetchData();
    console.log("Async/Await done");
}

fetchDataAsync().then(function() {
    console.log("End");
});

These tools enable developers to create efficient and responsive applications without freezing the user interface during time-consuming operations.

Event Loops :

The event loop is a fundamental concept in asynchronous programming, and it plays a crucial role in the execution model of many programming languages, especially those with event-driven architectures. It's commonly used in environments like web browsers (JavaScript).

  • Basics of the Event Loop:

At a high level, the event loop is a continuous process that checks the message queue for new events and executes associated callbacks. It allows programs to perform asynchronous operations, such as handling user input, network requests, and timers, without blocking the entire program's execution.

Here's a simplified explanation of the event loop process:

  1. Event Loop Initialization:

    • The event loop starts when the program begins execution.
  2. Execution Stack:

    • The main program runs in a thread and has an execution stack.

    • Synchronous code is executed in a sequential manner, with each function call adding to the stack.

  3. Message Queue:

    • Asynchronous operations (e.g., callbacks, timers, I/O operations) are scheduled to run later.

    • When these operations complete, corresponding messages are added to the message queue.

  4. Event Loop Tick:

    • The event loop continuously checks if the execution stack is empty.

    • If the stack is empty, it picks up the first message from the queue and executes its associated callback.

  5. Callback Execution:

    • The callback is executed, and any synchronous code within it is added to the execution stack.
  6. Repeat:

    • The event loop continues to iterate, checking the stack and processing messages from the queue until both are empty.
  • Callbacks :

In JavaScript, a callback is a function passed as an argument to another function, with the intention that it will be invoked or executed later, usually after the completion of an asynchronous operation or an event. Callbacks are a fundamental concept in JavaScript, especially in scenarios where you need to work with operations that may take some time to complete, such as fetching data from a server, reading a file, or handling user interactions.

function fetchData(callback) {
    // Simulating an asynchronous operation (e.g., fetching data)
    setTimeout(function() {
        const data = "This is the fetched data";
        // Calling the provided callback with the fetched data
        callback(data);
    }, 1000);
}

// Using the fetchData function with a callback
fetchData(function(result) {
    console.log("Data received:", result);
});

in this example, fetchData is a function that simulates an asynchronous operation, and it takes a callback function as an argument. Once the asynchronous operation is complete (simulated by a timeout), it invokes the provided callback, passing the fetched data to it.

Callbacks are essential for handling asynchronous tasks in JavaScript and are widely used in various contexts, such as event handling, AJAX requests, and more. They provide a way to manage the flow of execution in non-blocking environments, ensuring that code remains responsive and efficient.

Web browers API :

Web Browser APIs (Application Programming Interfaces) are sets of tools and functionalities provided by web browsers to JavaScript to interact with and manipulate various aspects of web pages and the browser environment. These APIs allow developers to create dynamic and interactive web applications by providing access to features like DOM manipulation, AJAX requests, timers, geolocation, and more.

Key Web Browser APIs:

  1. DOM API (Document Object Model):

    • Allows JavaScript to interact with and manipulate the structure and content of HTML and XML documents.

    • Provides methods to create, modify, and delete HTML elements and attributes.

  2. XHR (XMLHttpRequest) API:

    • Enables making HTTP requests from the browser, facilitating communication with servers.

    • Used in AJAX (Asynchronous JavaScript and XML) for retrieving data without refreshing the entire page.

  3. Fetch API:

    • A modern replacement for XHR, providing a more flexible and powerful interface for making network requests.

    • Supports Promises, making it easier to work with asynchronous code.

  4. Geolocation API:

    • Allows access to the user's geographical location information.

    • Useful for location-based services and applications.

  5. Web Storage API:

    • Consists of localStorage and sessionStorage, allowing developers to store key-value pairs locally on the user's browser.

    • Persistent (localStorage) and session-based (sessionStorage) storage options.

  6. WebSockets API:

    • Enables bidirectional communication between the browser and a server over a single, long-lived connection.

    • Ideal for real-time applications like chat and online gaming.

Resource for Further Reading:

For a deep dive into Web Browser APIs and their usage, the Mozilla Developer Network (MDN) provides comprehensive and well-documented resources. The MDN Web Docs on JavaScript and Web APIs cover a wide range of topics with examples, explanations, and best practices.

MDN Web Docs - JavaScript

MDN Web Docs - Web APIs

These resources are valuable for understanding the intricacies of individual APIs, their methods, and how to effectively use them in web development.