Home Blog Page 11

Introduction to Node.js

0
full stack development
full stack development

Node.js is a powerful and popular JavaScript runtime environment that enables developers to build fast, scalable, and efficient server-side applications. By utilizing JavaScript for both client-side and server-side code, Node.js provides a unified language environment for full-stack development. But what exactly is Node.js, and why has it become so widely adopted for modern application development?

What is Node.js?

Node.js is an open-source, cross-platform runtime built on the V8 JavaScript engine (the same engine that powers Google Chrome). Unlike traditional server-side environments where JavaScript is only used in the browser, Node.js allows developers to run JavaScript on the server. This enables the use of JavaScript for backend development, providing a unified approach to both frontend and backend coding.

At its core, Node.js is designed to build highly scalable, event-driven applications, especially for applications that handle large volumes of real-time data. Node.js operates on a non-blocking, event-driven model, making it ideal for developing real-time applications such as chat applications, online gaming, and collaborative platforms.

Why Use Node.js?

  1. Asynchronous and Event-Driven: One of the most powerful features of Node.js is its asynchronous, non-blocking nature. This means that when Node.js executes a task (like reading a file from the disk or making a network request), it doesn’t block the entire application while waiting for the task to complete. Instead, it continues executing other tasks and processes once the initial task is done. This increases the performance and responsiveness of applications, especially for I/O-heavy tasks.
  2. Single Language for Full-Stack Development: Node.js allows developers to use JavaScript on both the client and server sides. This reduces the learning curve and allows for faster development since developers only need to be proficient in one language. This full-stack development capability streamlines development processes and makes the codebase easier to maintain.
  3. High Performance: Node.js leverages the V8 JavaScript engine, which compiles JavaScript directly to machine code for faster execution. This contributes to the high performance and efficiency of Node.js applications, especially in terms of handling a large number of simultaneous connections.
  4. Scalability: Node.js is particularly suited for scalable applications. Its non-blocking I/O model makes it efficient for handling many connections simultaneously, which is crucial for web applications that need to support thousands of users at once. Its event-driven architecture also makes it easier to scale applications horizontally by adding more instances.
  5. Rich Ecosystem with npm (Node Package Manager): The Node.js ecosystem is supported by the npm (Node Package Manager), which provides access to thousands of reusable packages and modules that can be easily integrated into applications. These packages range from utility libraries to frameworks like Express.js, which simplifies the process of building web applications.
  6. Real-Time Data Handling: Node.js excels in applications that require real-time data handling. This includes use cases such as online chat systems, live data feeds, and multiplayer games. Its ability to handle multiple simultaneous connections makes it the perfect choice for building real-time applications.

Applications of Node.js

Node.js is used in various fields for building diverse applications. Some of the most common applications include:

  • Web Servers & APIs: Node.js is widely used to build RESTful APIs and web servers. Its ability to handle multiple requests concurrently and provide real-time responses makes it a go-to solution for modern web applications.
  • Real-Time Applications: Applications like chat apps, real-time notifications, collaborative tools, and online gaming benefit from Node.js’s event-driven, real-time capabilities.
  • Data Streaming: Node.js handles data streaming exceptionally well. It’s often used in applications that require streaming large data sets, such as video streaming services, audio streaming platforms, and data processing applications.
  • Microservices Architecture: Node.js is often utilized in microservices architectures, where it provides the flexibility, scalability, and performance needed for distributed applications. Its lightweight nature makes it suitable for building modular services.

How Node.js Works

To understand how Node.js works, it’s essential to know about the event-driven model and the event loop.

  1. Event-Driven Architecture: Node.js operates using an event-driven architecture, where the flow of data is triggered by events. This allows Node.js to handle multiple operations concurrently without blocking the execution thread. When an event occurs (like receiving a request), Node.js executes the associated callback function. Once the task is complete, it continues to the next event.
  2. The Event Loop: Node.js uses a single-threaded event loop to handle asynchronous operations. It processes events one at a time, but it can handle many events concurrently without blocking the application. The event loop is the core of Node.js, and it works by delegating long-running operations, such as file I/O or network requests, to the system while continuing to process other requests.

Getting Started with Node.js

To get started with Node.js, you need to set up your development environment:

  1. Install Node.js:
    • Visit the official Node.js website: https://nodejs.org.
    • Download the latest stable version of Node.js and follow the installation instructions.
    • Verify the installation by running the following commands in the terminal: nginxCopyEditnode -v npm -v
  2. Create a Simple Node.js Application:
    • Open a text editor and create a new file called app.js.
    • Add the following code to start a simple HTTP server: const http = require('http'); const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello, Node.js!'); }); server.listen(3000, 'localhost', () => { console.log('Server running at http://localhost:3000/'); });
  3. Run the Application:
    • Open the terminal, navigate to the folder where app.js is located, and run the command: nginxCopyEditnode app.js
    • Open a browser and visit http://localhost:3000/. You should see the message “Hello, Node.js!”.

Conclusion

Node.js revolutionized JavaScript development by bringing server-side JavaScript to the forefront. With its event-driven, non-blocking I/O model, high performance, and scalability, Node.js has become the backbone for building modern web applications and real-time systems. Whether you are developing a web server, API, or real-time application, Node.js offers the tools and flexibility to build fast and scalable applications.

If you’re new to server-side development or looking to expand your skills in full-stack JavaScript development, learning Node.js will open up a world of opportunities. With a thriving ecosystem, rich community support, and continuous improvements, Node.js is an essential technology for any developer looking to stay ahead in the field.

JavaScript on the Server (Node.js Intro)

0
full stack development
full stack development

Introduction to Node.js

JavaScript has traditionally been used in the browser for front-end development, but with the introduction of Node.js, JavaScript has made its way to the back-end. Node.js allows developers to write server-side applications using JavaScript. It’s fast, scalable, and uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.

In this module, we’ll dive into the basics of Node.js, explore its core concepts, and set up a simple Node.js server.


Table of Contents

  1. What is Node.js?
  2. Features of Node.js
  3. Installing Node.js
  4. Writing Your First Node.js Application
  5. Understanding the Event Loop
  6. Modules in Node.js
  7. Setting Up a Simple HTTP Server
  8. Conclusion

1. What is Node.js?

Node.js is a JavaScript runtime environment built on Chrome’s V8 JavaScript engine. It was created to build scalable network applications. With Node.js, you can use JavaScript to handle HTTP requests, interact with databases, and serve data to clients, just like other back-end programming languages such as Python, Ruby, or PHP.

Node.js allows you to run JavaScript code outside the browser on the server. It’s particularly known for its non-blocking, event-driven architecture that makes it ideal for I/O-heavy applications like real-time chat apps, online gaming servers, and APIs.


2. Features of Node.js

Node.js is designed for building fast and scalable applications. Here are some key features:

  • Event-driven, Non-blocking I/O: This allows Node.js to handle multiple operations concurrently, making it ideal for real-time applications like chat apps or live notifications.
  • Single-threaded: Node.js operates on a single thread, which is great for scaling. It uses asynchronous calls to handle multiple requests without needing extra threads.
  • Fast Execution: Built on Chrome’s V8 engine, Node.js executes JavaScript code at lightning speed.
  • NPM (Node Package Manager): Node.js comes with a package manager called npm, which allows you to easily install and manage libraries and dependencies for your project.
  • Cross-platform: Node.js is cross-platform, meaning it can run on any operating system, such as Linux, macOS, or Windows.

3. Installing Node.js

To start using Node.js, you need to install it on your computer. Here’s how to get started:

  1. Go to the Node.js download page.
  2. Download the LTS (Long Term Support) version for stability.
  3. Follow the installation instructions for your operating system.
  4. Once installed, open your terminal (or command prompt on Windows) and check if the installation was successful by running: bashCopyEditnode -v npm -v

This will display the installed versions of Node.js and npm.


4. Writing Your First Node.js Application

Once Node.js is installed, you can write your first Node.js application. Let’s start by creating a simple “Hello World” server:

Steps to Create Your First Node.js App:

  1. Create a new directory for your project: mkdir my-node-app cd my-node-app
  2. Create a new file called app.js: bashCopyEdittouch app.js
  3. Open app.js in your text editor and add the following code to create a basic HTTP server: const http = require('http'); // Import the HTTP module const server = http.createServer((req, res) => { // Create an HTTP server res.statusCode = 200; // Set HTTP status code res.setHeader('Content-Type', 'text/plain'); // Set response header res.end('Hello, Node.js!\n'); // Send response }); const port = 3000; // Specify the port number server.listen(port, () => { // Start the server and listen on port 3000 console.log(`Server running at http://localhost:${port}/`); });
  4. In the terminal, run the Node.js server: node app.js
  5. Open your browser and go to http://localhost:3000. You should see the text Hello, Node.js!.

This simple example demonstrates how to use Node.js to create an HTTP server that listens for incoming requests and sends a response.


5. Understanding the Event Loop

Node.js is based on an event-driven architecture. This means it handles asynchronous operations (such as reading files or handling HTTP requests) without blocking the execution of other code.

  • The Event Loop is a mechanism that continually checks for events or messages in the system and processes them in a non-blocking way.
  • When Node.js executes asynchronous code (e.g., file reads, network requests), it doesn’t wait for the result but continues executing other code, ensuring that the system remains responsive.

For instance, Node.js can handle thousands of concurrent requests without being blocked by I/O operations.


6. Modules in Node.js

Node.js comes with a set of built-in modules that you can use to perform various tasks. These modules encapsulate functionality and make it easier to work with different aspects of the application.

Some Common Modules:

  • HTTP: To create web servers and handle HTTP requests.
  • FS (File System): For reading from and writing to the file system.
  • Path: To work with and manipulate file and directory paths.
  • OS: Provides operating system-related utility methods (e.g., to get system information).
  • Events: Used to handle and emit events.

You can also install third-party modules using npm. For example, to work with databases like MongoDB, you can install the MongoDB driver using npm.

Example of Using the fs Module:

const fs = require('fs');

// Writing to a file
fs.writeFile('example.txt', 'Hello, Node.js File System!', (err) => {
if (err) throw err;
console.log('File has been saved!');
});

7. Setting Up a Simple HTTP Server

In this section, we’ll dive deeper into building a more interactive HTTP server with Node.js.

Let’s enhance the previous HTTP server by making it dynamic. Instead of responding with the same text for all requests, we will check the URL and respond accordingly.

const http = require('http');

const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');

if (req.url === '/') {
res.end('Welcome to the Home Page!');
} else if (req.url === '/about') {
res.end('Welcome to the About Page!');
} else {
res.statusCode = 404;
res.end('Page not found!');
}
});

const port = 3000;
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});

Now, when you visit http://localhost:3000/, you’ll get a welcome message, and if you go to http://localhost:3000/about, you’ll see the about page message. If you navigate to any other URL, it’ll return a 404 error.


8. Conclusion

Node.js brings JavaScript to the server side, allowing developers to write full-stack applications using the same language throughout. In this module, you learned about:

  • What Node.js is and its core features.
  • How to install Node.js and set up a basic development environment.
  • Writing your first Node.js HTTP server.
  • Understanding how asynchronous, non-blocking I/O works in Node.js with the event loop.
  • Exploring Node.js modules like http, fs, and path.

With this foundation, you’re ready to explore more advanced Node.js concepts and start building server-side applications!

Setting Up Your JavaScript Environment

0
full stack development
full stack development

Introduction to JavaScript Development Environment

Before you start writing JavaScript code, it’s crucial to set up your development environment. The development environment is a combination of software and tools that you use to write, debug, and test your JavaScript code. Setting this up correctly will make your development process much smoother and more efficient.

In this module, we’ll cover the essential tools and steps to get your environment ready for both front-end and back-end JavaScript development.


Table of Contents

  1. What You Need to Get Started
  2. Choosing a Code Editor or IDE
  3. Installing Node.js and npm (Node Package Manager)
  4. Setting Up Browser Developer Tools
  5. Running Your First JavaScript Program
  6. Advanced Tooling (Optional but Recommended)
  7. Conclusion

1. What You Need to Get Started

To write JavaScript code, you’ll need the following basic tools:

  • Text Editor or IDE (Integrated Development Environment): Where you write your code.
  • Node.js: Allows JavaScript to run outside the browser, useful for back-end development.
  • npm (Node Package Manager): A tool that allows you to install JavaScript libraries and manage dependencies.
  • Browser Developer Tools: Provides debugging features for testing JavaScript code in the browser.

Let’s go through each one in detail.


2. Choosing a Code Editor or IDE

A good code editor makes coding much easier. JavaScript is an interpreted language, so you need a place to write and run your code. Here are some popular choices:

Visual Studio Code (VS Code)

  • Why VS Code?
    Visual Studio Code is a lightweight, free, and powerful editor. It provides features like syntax highlighting, IntelliSense (auto-completion), debugging tools, version control, extensions, and more, making it one of the best options for JavaScript development.
  • Installation Instructions for VS Code:
    1. Visit the VS Code Download Page.
    2. Download the installer based on your operating system (Windows, macOS, Linux).
    3. Follow the installation steps on your screen.
    4. Once installed, launch VS Code.
  • Recommended Extensions for JavaScript in VS Code:
    • ESLint: This extension helps you identify and fix errors and ensure your code follows best practices and consistent styling.
    • Prettier: Prettier automatically formats your code to ensure consistent styling across your project.
    • JavaScript (ES6) code snippets: This extension adds reusable code snippets for common JavaScript constructs, like loops, functions, and more.
    • Debugger for Chrome: Allows you to run and debug JavaScript code directly from VS Code.

Other Code Editors

  • Sublime Text: Known for being fast and customizable, but lacks some of the built-in features found in VS Code.
  • Atom: Developed by GitHub, Atom is highly customizable and open-source but can be slower compared to VS Code.
  • WebStorm: A more heavyweight IDE that comes with extensive built-in features for JavaScript development but is paid.

3. Installing Node.js and npm

What is Node.js?

Node.js is a JavaScript runtime environment that allows you to run JavaScript code on the server-side (outside the browser). If you’re building web applications, APIs, or working with JavaScript tools, Node.js is essential.

What is npm?

npm (Node Package Manager) is used to manage libraries and packages for your JavaScript projects. When you install Node.js, npm is also installed automatically.

How to Install Node.js and npm

Follow these steps to install Node.js and npm:

  1. Go to the Node.js download page.
  2. Choose the LTS version for stability and long-term support.
  3. Download the installer for your operating system (Windows, macOS, Linux).
  4. Follow the installation prompts. Make sure to check the box that says Add to PATH during installation (this ensures that you can use Node and npm from the terminal).
  5. After installation, open your terminal (or command prompt on Windows), and run the following commands to check if Node.js and npm are installed correctly:
node -v
npm -v

You should see the version numbers of both Node.js and npm printed in the console.

Managing JavaScript Libraries with npm

With npm, you can install JavaScript libraries and manage dependencies for your projects. For example:

  • To initialize a new project with npm: bashCopyEditnpm init This will create a package.json file, where your project’s dependencies will be listed.
  • To install a library (like Lodash): bashCopyEditnpm install lodash This command will download and install the Lodash library into a node_modules folder in your project directory.

4. Setting Up Browser Developer Tools

While JavaScript is commonly associated with web browsers, each modern browser includes Developer Tools that allow you to inspect, debug, and run JavaScript code. These tools are crucial for front-end development.

How to Use Developer Tools in Google Chrome

  1. Open Chrome and press F12 (or Ctrl + Shift + I on Windows/Linux, Cmd + Option + I on macOS).
  2. Go to the Console tab. This is where you can write JavaScript directly in the browser. You can try writing a simple line of JavaScript in the console: console.log("Hello from the browser console!"); This will output to the console. Developer tools also allow you to inspect HTML elements, watch network requests, and profile your JavaScript code for performance.

Other Browser Developer Tools

  • Firefox Developer Tools: Firefox has a similar set of tools for inspecting and debugging your web applications.
  • Edge Developer Tools: Microsoft Edge also offers developer tools that are similar to those in Chrome.

5. Writing and Running Your First JavaScript Program

Now that you have your environment set up, let’s write and run some simple JavaScript.

Running JavaScript in the Browser Console

  1. Open your browser’s developer tools (e.g., Google Chrome).
  2. Go to the Console tab.
  3. Type the following code:
console.log("Hello, JavaScript!");

This will print Hello, JavaScript! to the browser’s console.

Running JavaScript Using Node.js

If you want to run JavaScript outside the browser, Node.js is the way to go.

  1. Open your terminal (or command prompt on Windows).
  2. Create a new JavaScript file called app.js.
touch app.js
  1. Open the file in your code editor, and write the following code:
console.log("Hello, Node.js!");
  1. To run this program, use the following command:
node app.js

This will print Hello, Node.js! to the terminal.


6. Advanced Tooling (Optional but Recommended)

As you advance in JavaScript development, you might encounter the need for additional tools to optimize your workflow.

Task Runners and Module Bundlers

  • Webpack: A module bundler that allows you to bundle your JavaScript files and other assets.
  • Gulp/Grunt: Task runners for automating repetitive tasks, such as minification, compiling Sass to CSS, and more.

Version Control

  • Git: Git is a version control system that allows you to track changes in your code. You’ll use Git with platforms like GitHub or GitLab to store your projects, collaborate with others, and maintain version history.

7. Conclusion

In this module, we’ve walked through the steps required to set up your JavaScript development environment, including installing a code editor, setting up Node.js, and configuring your browser’s developer tools. With these tools in place, you’re ready to write and test JavaScript both in the browser and on the server with Node.js.

By following these steps, you’ve laid the foundation for your JavaScript development journey. From here, you can start writing your own JavaScript programs, explore libraries and frameworks, and dive deeper into web development.

Unit Testing JavaScript

0
full stack development
full stack development

Introduction to Unit Testing

Unit testing is a critical part of ensuring the reliability and maintainability of your code. In JavaScript, unit tests are used to validate the functionality of individual units or components of your code, usually functions, to ensure that they work as expected.

In this module, we will explore the basics of unit testing, the tools available for JavaScript testing, and how to write meaningful tests for your JavaScript code.


Table of Contents

  1. What is Unit Testing?
  2. Why Unit Testing is Important?
  3. Tools for Unit Testing in JavaScript
  4. Writing Unit Tests with Jest
  5. Mocking in Unit Tests
  6. Running Unit Tests
  7. Best Practices for Unit Testing
  8. Conclusion

1. What is Unit Testing?

Unit Testing involves writing test cases to validate the smallest parts of an application, typically individual functions, to ensure they work correctly. A unit test checks if a function behaves as expected when given a specific input.

A simple unit test for a function might look like this:

function add(a, b) {
return a + b;
}

// Unit test for add function
console.log(add(2, 3)); // Should return 5

Unit testing ensures that each function or unit of your program is independently validated.


2. Why Unit Testing is Important?

Unit testing provides several benefits to your development process:

  • Detecting Issues Early: Helps in catching bugs and issues at an early stage in development.
  • Improves Code Quality: Ensures that your functions behave as expected under various conditions.
  • Refactoring Confidence: You can confidently refactor code since you know that existing functionality is covered by tests.
  • Documentation: Unit tests can serve as documentation for what the code is expected to do.

3. Tools for Unit Testing in JavaScript

There are several tools available to help you write and run unit tests in JavaScript. Some of the most popular ones include:

  • Jest: A JavaScript testing framework that provides a lot of useful features like test runners, assertions, mocks, and more.
  • Mocha: A flexible testing framework for Node.js and the browser. It allows you to write tests in a behavior-driven development style.
  • Chai: An assertion library often used with Mocha, allowing you to write more expressive tests.
  • Jasmine: A testing framework similar to Mocha, known for its clean syntax and assertions.
  • Karma: A test runner for JavaScript, often used with Mocha or Jasmine.

In this module, we’ll focus on using Jest, which is one of the most widely used testing frameworks in modern JavaScript development.


4. Writing Unit Tests with Jest

To begin using Jest, you’ll first need to install it in your project. If you’re using Node.js, you can install it via npm:

npm install --save-dev jest

Once installed, you can write a simple test case for a function. For example, let’s write a unit test for the add function we defined earlier.

Example: Writing a Jest Test

// add.js
function add(a, b) {
return a + b;
}

module.exports = add;

Now, create a test file:

// add.test.js
const add = require('./add');

test('adds 2 + 3 to equal 5', () => {
expect(add(2, 3)).toBe(5);
});

In this test:

  • test() defines a test case with a description and a callback function.
  • expect() is an assertion function that checks if the output matches the expected value.
  • .toBe() is a matcher used to check for exact equality.

Running the Test

Once the test is written, you can run it with the following command:

npx jest

This will execute all the tests in your project, and you should see an output indicating whether the test passed or failed.


5. Mocking in Unit Tests

When writing unit tests, you may need to mock certain dependencies or functions to isolate the unit you’re testing. Jest makes it easy to mock functions, objects, or modules.

Example: Mocking a Dependency

Suppose we have a function that relies on an API call:

function getDataFromAPI(apiCall) {
return apiCall().then(response => response.data);
}

module.exports = getDataFromAPI;

Now, we’ll mock the apiCall function in our test:

// getDataFromAPI.test.js
const getDataFromAPI = require('./getDataFromAPI');

test('fetches data from the API', () => {
const mockApiCall = jest.fn().mockResolvedValue({ data: 'some data' });

return getDataFromAPI(mockApiCall).then(data => {
expect(data).toBe('some data');
expect(mockApiCall).toHaveBeenCalledTimes(1);
});
});

In this example:

  • jest.fn() creates a mock function.
  • mockResolvedValue() allows us to simulate a resolved promise with mock data.
  • expect(mockApiCall).toHaveBeenCalledTimes(1) checks if the mock function was called once.

6. Running Unit Tests

Jest runs all the tests by default when you use the npx jest command. You can also run specific tests:

  • Run a specific test file: npx jest add.test.js
  • Run tests in watch mode: npx jest --watch

This will rerun tests whenever a file is changed.


7. Best Practices for Unit Testing

Here are some best practices to keep in mind when writing unit tests for JavaScript:

  • Test small, isolated units: Each test should cover a single function or unit of your code.
  • Write tests first: Write your tests before implementing the function (TDD – Test Driven Development).
  • Use descriptive names: Name your tests descriptively to clearly indicate what they are testing.
  • Test edge cases: Don’t just test for typical input, but also edge cases and error conditions.
  • Keep tests maintainable: Refactor your tests as you refactor your code.

8. Conclusion

Unit testing is an essential part of modern JavaScript development. By writing meaningful unit tests, you can ensure that your code is reliable, maintainable, and bug-free. With testing tools like Jest, you can easily set up and run tests to validate your code and mock dependencies when needed.

By adhering to best practices and using mocking and other techniques, you can write comprehensive and effective unit tests that ensure your code performs as expected in all scenarios.

Event Bubbling vs Capturing

0
full stack development
full stack development

Understanding Event Propagation in JavaScript

When an event occurs in the DOM, such as a user clicking on a button or a form submission, it triggers a series of steps that decide how the event reaches its target element and how it bubbles up or captures down through the DOM. This process is known as Event Propagation.

Event propagation is handled in two main phases:

  1. Capturing Phase (also known as “Trickling down”)
  2. Bubbling Phase

In this module, we’ll explore both phases and how they affect event handling in JavaScript.


Table of Contents

  1. What is Event Propagation?
  2. The Capturing Phase
  3. The Bubbling Phase
  4. Differences Between Bubbling and Capturing
  5. Controlling Event Propagation
  6. Practical Examples
  7. Conclusion

1. What is Event Propagation?

When an event is triggered on a DOM element, it doesn’t just affect that element. Instead, the event will propagate through the DOM tree in one of two directions:

  • Capturing Phase: The event starts from the topmost element and travels down to the target element (parent to child).
  • Bubbling Phase: The event starts from the target element and bubbles up to the topmost element (child to parent).

The event will propagate through the DOM tree unless we stop it at some point.


2. The Capturing Phase

The capturing phase (or trickling phase) occurs before the event reaches the target element. In this phase, the event moves from the root element to the target element.

In most cases, you don’t need to worry about capturing because it’s the default for most event listeners. However, you can listen for events in the capturing phase using addEventListener() by passing true as the third argument.

Example of Capturing:

document.getElementById("parent").addEventListener("click", () => {
console.log("Parent element - Capturing Phase");
}, true);

document.getElementById("child").addEventListener("click", () => {
console.log("Child element - Capturing Phase");
}, true);

In this example, if you click the child element, the event will first trigger on the parent element during the capturing phase.


3. The Bubbling Phase

The bubbling phase occurs after the event reaches the target element. During this phase, the event bubbles up from the target element to the root element.

By default, events bubble, and the target element is the first one to receive the event. Then, the event propagates upward to its ancestors (parents, grand-parents, etc.).

Example of Bubbling:

document.getElementById("parent").addEventListener("click", () => {
console.log("Parent element - Bubbling Phase");
});

document.getElementById("child").addEventListener("click", () => {
console.log("Child element - Bubbling Phase");
});

In this case, if you click the child element, the event will first trigger on the child element, and then bubble up to the parent element.


4. Differences Between Bubbling and Capturing

PropertyCapturing PhaseBubbling Phase
DirectionParent → Child (from outermost element to target)Target → Parent (from target element to outermost)
Default BehaviorNot default (must be explicitly set with true)Default (events bubble up after being triggered)
Event Listener BehaviorTriggered first if true is passed as third argumentTriggered after bubbling (default behavior)

5. Controlling Event Propagation

You can control the event propagation by using the following methods:

  • event.stopPropagation(): Stops the event from propagating further, either during the capturing or bubbling phase. Example: document.getElementById("child").addEventListener("click", (event) => { console.log("Child clicked"); event.stopPropagation(); // Prevent the event from bubbling });
  • event.stopImmediatePropagation(): Stops the event from propagating further and also prevents any other event listeners of the same event from being called. Example: document.getElementById("child").addEventListener("click", (event) => { console.log("Child clicked"); event.stopImmediatePropagation(); // Prevents further handlers on this element });

6. Practical Examples

Let’s see a practical example of how event propagation works with both capturing and bubbling phases.

Example 1: Capturing vs Bubbling

<div id="parent">
<button id="child">Click me!</button>
</div>

<script>
// Capturing phase
document.getElementById("parent").addEventListener("click", () => {
console.log("Parent element - Capturing Phase");
}, true);

// Bubbling phase
document.getElementById("parent").addEventListener("click", () => {
console.log("Parent element - Bubbling Phase");
});

document.getElementById("child").addEventListener("click", () => {
console.log("Child element - Bubbling Phase");
});
</script>

Here, when the button is clicked, the logs will be as follows:

  • Capturing Phase: Parent element first.
  • Bubbling Phase: Child element first, followed by the parent element.

Example 2: Stopping Propagation

<div id="parent">
<button id="child">Click me!</button>
</div>

<script>
document.getElementById("parent").addEventListener("click", () => {
console.log("Parent element clicked");
});

document.getElementById("child").addEventListener("click", (event) => {
console.log("Child element clicked");
event.stopPropagation(); // Stop the event from bubbling up
});
</script>

Here, when you click the button, you’ll see:

  • Child element clicked
  • The Parent element clicked will not be logged because stopPropagation() is called.

7. Conclusion

Understanding Event Bubbling vs Capturing is vital for controlling how events propagate through the DOM and how to handle user interactions effectively. By using event propagation techniques like stopPropagation() and leveraging both capturing and bubbling phases, you can have greater control over your event-driven applications.