<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Samyak Jain - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Samyak Jain - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 14 May 2026 22:43:31 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/samyakjainblog/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ What are Decorators in Python? Explained with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ In this tutorial, you will learn about Python decorators: what they are, how they work, and when to use them. Table of Contents Foundation for Decorators [Introduction to Python Decorators](#Introduction to Python Decorators) Creating Simple Decorat... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/decorators-in-python-tutorial/</link>
                <guid isPermaLink="false">66c7217e87ceefbdaf9b9217</guid>
                
                    <category>
                        <![CDATA[ decorator ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Samyak Jain ]]>
                </dc:creator>
                <pubDate>Tue, 18 Jun 2024 18:53:30 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/07/decorators-in-python.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this tutorial, you will learn about Python decorators: what they are, how they work, and when to use them.</p>
<h2 id="heading-table-of-contents"><strong>Table of Contents</strong></h2>
<ol>
<li><a class="post-section-overview" href="#heading-foundation-for-decorators">Foundation for Decorators</a></li>
<li>[Introduction to Python Decorators](#Introduction to Python Decorators)</li>
<li><a class="post-section-overview" href="#heading-now-lets-look-at-a-decorator-example">Creating Simple Decorators</a><br>– <a class="post-section-overview" href="#heading-applying-decorators-to-functions">Applying Decorators to Functions</a><br>– <a class="post-section-overview" href="#heading-using-the-syntax-for-decorators">Using the @ Syntax for Decorators</a></li>
<li><a class="post-section-overview" href="#heading-how-to-handle-functions-with-arguments">How to Handle Functions with Arguments</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-classes-as-decorators">Using Classes as Decorators</a></li>
<li><a class="post-section-overview" href="#heading-best-practices-for-using-decorators">Best Practices for Using Decorators</a></li>
<li><a class="post-section-overview" href="#heading-practical-applications-of-decorators">Real-World Applications of Decorators</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<p>Decorators are a powerful and elegant way to extend the behavior of functions or methods without modifying their actual code. But before diving into decorators, it's helpful to understand two foundational concepts in Python: first-class functions and closures.</p>
<h2 id="heading-foundation-for-decorators">Foundation for Decorators</h2>
<h3 id="heading-first-class-functions-in-python">First-Class Functions in Python</h3>
<p>First-class functions mean that functions in Python are treated like any other object. This implies that functions can be:</p>
<ul>
<li>Passed as arguments to other functions.</li>
<li>Returned from other functions.</li>
<li>Assigned to variables.</li>
</ul>
<h3 id="heading-understanding-closures">Understanding Closures</h3>
<p>Closures in Python allow a function to remember the environment in which it was created. This means the inner function has access to the variables in the local scope of the outer function even after the outer function has finished executing.</p>
<p>Let’s look at an example to understand closures:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">outer_func</span>():</span>
    greet = <span class="hljs-string">"Hello!"</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">inner_func</span>():</span>
        print(greet)

    <span class="hljs-keyword">return</span> inner_func

new_function = outer_func()
new_function()  <span class="hljs-comment"># Outputs: Hello!</span>
new_function()  <span class="hljs-comment"># Outputs: Hello!</span>
</code></pre>
<p>In this example:</p>
<ul>
<li>We have <code>outer_func</code> that doesn't take any parameters but has a local variable <code>greet</code>.</li>
<li>An <code>inner_func</code> is defined within <code>outer_func</code> that prints <code>greet</code>.</li>
<li>When we call <code>outer_func</code>, it returns <code>inner_func</code> but does not execute it immediately. We assign the returned function to <code>new_function</code>. Now, <code>new_function</code> can be called later, and it will remember the <code>greet</code> variable from <code>outer_func</code>’s scope, printing "Hello!" each time it’s called.</li>
</ul>
<p>This is what a closure is—it remembers our <code>greet</code> variable even after the outer function has finished executing.</p>
<h4 id="heading-modifying-closures-with-parameters">Modifying Closures with Parameters</h4>
<p>Let's enhance our closure by passing a parameter to the <code>outer_func</code> instead of using a local variable:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">outer_func</span>(<span class="hljs-params">greet</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">inner_func</span>():</span>
        print(greet)
    <span class="hljs-keyword">return</span> inner_func

namaste_func = outer_func(<span class="hljs-string">"Namaste!"</span>)
howdy_func = outer_func(<span class="hljs-string">"Howdy!"</span>)

namaste_func()  <span class="hljs-comment"># Outputs: Namaste!</span>
howdy_func()    <span class="hljs-comment"># Outputs: Howdy!</span>
</code></pre>
<p>Here:</p>
<ul>
<li><code>outer_func</code> now takes a parameter <code>greet</code>.</li>
<li>The <code>inner_func</code> prints this <code>greet</code>.</li>
<li>When we call <code>outer_func</code> with "Namaste!" and "Howdy!", it returns functions that remember these specific messages.</li>
</ul>
<p>So, this was a quick brief about first-class functions and closures. If you want to learn more about them you can read this comprehensive blog <a target="_blank" href="https://www.freecodecamp.org/news/first-class-functions-and-closures-in-python/">here</a>.</p>
<h2 id="heading-introduction-to-python-decorators"><strong>Introduction to Python Decorators</strong></h2>
<p>A decorator is a function that takes another function as an argument, adds some functionality, and returns a new function. This allows you to "wrap" another function to extend its behavior (adding some functionality before or after) without modifying the original function's source code.</p>
<p>So, this is the closure example that we used above:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">outer_func</span>(<span class="hljs-params">greet</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">inner_func</span>():</span>
        print(greet)
    <span class="hljs-keyword">return</span> inner_func
</code></pre>
<h3 id="heading-now-lets-look-at-a-decorator-example">Now, let's look at a Decorator Example:</h3>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">decorator_function</span>(<span class="hljs-params">func</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapper_function</span>():</span>
        <span class="hljs-keyword">return</span> func()
    <span class="hljs-keyword">return</span> wrapper_function
</code></pre>
<p>Here, instead of a value (like <code>greet</code>), we're accepting a function (<code>func</code>) as an argument. Within our <code>wrapper_function</code>, instead of just printing out a message, we're going to execute this <code>func</code> and then return that.</p>
<h3 id="heading-applying-decorators-to-functions">Applying Decorators to Functions</h3>
<p>Here's how we can apply our decorator to a simple function:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">decorator_function</span>(<span class="hljs-params">func</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapper_function</span>():</span>
        <span class="hljs-keyword">return</span> func()
    <span class="hljs-keyword">return</span> wrapper_function

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">display</span>():</span>
    print(<span class="hljs-string">'The display function was called'</span>)

decorated_display = decorator_function(display)
decorated_display()  <span class="hljs-comment"># Outputs: The display function was called</span>
</code></pre>
<p>In this example:</p>
<ul>
<li>We define a simple function <code>display</code> that prints a message.</li>
<li>We apply the <code>decorator_function</code> to <code>display</code>, creating a new variable<code>decorated_display</code>.</li>
<li>When we call <code>decorated_display()</code>, it runs the <code>wrapper_function</code> inside our decorator, which in turn calls and returns the <code>display</code> function.</li>
</ul>
<h3 id="heading-using-the-syntax-for-decorators">Using the @ Syntax for Decorators</h3>
<p>Python provides a more readable way to apply decorators using the <code>@</code> symbol. This syntax is easier to understand and is commonly used in Python code:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">decorator_function</span>(<span class="hljs-params">func</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapper_function</span>():</span>
        print(<span class="hljs-string">f'Wrapper executed before <span class="hljs-subst">{func.__name__}</span>'</span>)
        <span class="hljs-keyword">return</span> func()
    <span class="hljs-keyword">return</span> wrapper_function

<span class="hljs-meta">@decorator_function</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">display</span>():</span>
    print(<span class="hljs-string">'The display function was called'</span>)

display()  <span class="hljs-comment"># Outputs: Wrapper executed before display</span>
           <span class="hljs-comment">#          The display function was called</span>
</code></pre>
<p>Here:</p>
<ul>
<li>We use <code>@decorator_function</code> decorator above the <code>display</code> function definition which is equivalent to <code>display = decoratorFunction(display)</code>.</li>
<li>Now, when we call <code>display()</code>, it automatically goes through the decorator, printing the additional message first.</li>
</ul>
<h2 id="heading-how-to-handle-functions-with-arguments">How to Handle Functions with Arguments</h2>
<p>The decorator we've written so far won't work if our original function takes arguments. For example, consider the following function:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">display_info</span>(<span class="hljs-params">name, age</span>):</span>
    print(<span class="hljs-string">'display_info was called with ({}, {})'</span>.format(name, age))

display_info(<span class="hljs-string">'Kalam'</span>, <span class="hljs-number">83</span>)  <span class="hljs-comment"># Outputs: display_info was called with (Kalam, 83)</span>
</code></pre>
<p>If we try to apply our current decorator to <code>display_info</code>, it will raise an error because the <code>wrapperFunction</code> takes no arguments but the original function expects two.</p>
<h3 id="heading-modifying-the-decorator-to-handle-arguments">Modifying the Decorator to Handle Arguments</h3>
<p>We can modify our decorator to accept any number of positional and keyword arguments by using <code>*args</code> and <code>**kwargs</code>.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> functools

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">decoratorFunction</span>(<span class="hljs-params">func</span>):</span>
<span class="hljs-meta">    @functools.wraps(func)</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapperFunction</span>(<span class="hljs-params">*args, **kwargs</span>):</span>
        print(<span class="hljs-string">'Wrapper executed before {}'</span>.format(func.__name__))
        <span class="hljs-keyword">return</span> func(*args, **kwargs)
    <span class="hljs-keyword">return</span> wrapperFunction

<span class="hljs-meta">@decoratorFunction</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">display</span>():</span>
    print(<span class="hljs-string">'The display function was called'</span>)

<span class="hljs-meta">@decoratorFunction</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">display_info</span>(<span class="hljs-params">name, age</span>):</span>
    print(<span class="hljs-string">'display_info was called with ({}, {})'</span>.format(name, age))

display_info(<span class="hljs-string">'Kalam'</span>, <span class="hljs-number">83</span>)  
display()
</code></pre>
<p>In this updated decorator:</p>
<ul>
<li><code>wrapperFunction</code> now accepts any number of positional (<code>*args</code>) and keyword arguments (<code>**kwargs</code>).</li>
<li>These arguments are passed to <code>func</code> when it is called inside <code>wrapperFunction</code>.</li>
</ul>
<p>The output of this will be:</p>
<pre><code>Wrapper executed before display_info
display_info was called <span class="hljs-keyword">with</span> (Kalam, <span class="hljs-number">83</span>)
Wrapper executed before display
The display <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">was</span> <span class="hljs-title">called</span></span>
</code></pre><p>This setup makes our decorator flexible enough to handle any function, regardless of its parameters.</p>
<p>BTW, Notice how we added new functionality to two different functions (<code>display()</code> and <code>display_info()</code>) without altering them? This is one of the main benefits of decorators: they allow us to extend the behavior of several functions in a DRY (Don't Repeat Yourself) way, as demonstrated in this example.</p>
<h2 id="heading-how-to-use-classes-as-decorators">How to Use Classes as Decorators</h2>
<p>While function-based decorators are common, you can also use classes to create decorators. Using classes as decorators can offer more flexibility and readability, especially for complex decorators.</p>
<p>To help you understand them better, We'll turn a function-based decorator into a class-based decorator:</p>
<h3 id="heading-original-function-based-decorator">Original Function-Based Decorator</h3>
<p>Let's start with a simple function-based decorator:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">decoratorFunction</span>(<span class="hljs-params">func</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapperFunction</span>(<span class="hljs-params">*args, **kwargs</span>):</span>
        print(<span class="hljs-string">'Wrapper executed before calling {}'</span>.format(func.__name__))
        <span class="hljs-keyword">return</span> func(*args, **kwargs)
    <span class="hljs-keyword">return</span> wrapperFunction
</code></pre>
<h3 id="heading-creating-a-class-based-decorator">Creating a Class-Based Decorator</h3>
<p>To turn this function-based decorator into a class-based decorator, follow these steps:</p>
<p><strong>Step 1: Define the Class</strong><br>First, we define a new class called <code>DecoratorClass</code>. This class will handle the decoration process.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DecoratorClass</span>:</span>
    <span class="hljs-keyword">pass</span>
</code></pre>
<p><strong>Step 2: Implement the</strong> <strong><code>__init__</code> Method</strong><br>The <code>__init__</code> is a special method that initializes the object when an instance of the class is created.<br>Next, we pass the function to be decorated (<code>func</code>) as an argument to the <code>__init__</code> method and store it in an instance variable <code>self.func</code>.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DecoratorClass</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, func</span>):</span>
        self.func = func
</code></pre>
<p><strong>Step 3: Implement the <code>__call__</code> Method</strong><br>The <code>__call__</code> method is a special method that allows an instance of the class to be called as a function. This method is essential because it handles the actual decoration logic. In this case:</p>
<ul>
<li>The <code>__call__</code> method takes <code>*args</code> and <code>**kwargs</code> to handle any number of positional and keyword arguments.</li>
<li>Inside <code>__call__</code>, we print a message and then call the original function with its arguments.</li>
</ul>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DecoratorClass</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, func</span>):</span>
        self.func = func

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__call__</span>(<span class="hljs-params">self, *args, **kwargs</span>):</span>
        print(<span class="hljs-string">'Executing wrapper before {}'</span>.format(self.func.__name__))
        <span class="hljs-keyword">return</span> self.func(*args, **kwargs)
</code></pre>
<h3 id="heading-using-the-class-based-decorator">Using the Class-Based Decorator</h3>
<p>We can now use the <code>@</code> syntax to apply the class-based decorator to functions, just as we did with the function-based decorator.</p>
<pre><code class="lang-python"><span class="hljs-meta">@DecoratorClass</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">display</span>():</span>
    print(<span class="hljs-string">'display function executed'</span>)

<span class="hljs-meta">@DecoratorClass</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">display_info</span>(<span class="hljs-params">name, age</span>):</span>
    print(<span class="hljs-string">'display_info function executed with arguments ({}, {})'</span>.format(name, age))
</code></pre>
<h3 id="heading-running-the-decorated-functions">Running the Decorated Functions</h3>
<p>When we call the decorated functions, the <code>__call__</code> method of <code>DecoratorClass</code> is executed:</p>
<pre><code class="lang-python">display_info(<span class="hljs-string">'Kalam'</span>, <span class="hljs-number">83</span>)
display()
</code></pre>
<h3 id="heading-complete-example">Complete Example</h3>
<p>Here is the complete example with the class-based decorators:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DecoratorClass</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, func</span>):</span>
        self.func = func

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__call__</span>(<span class="hljs-params">self, *args, **kwargs</span>):</span>
        print(<span class="hljs-string">'Executing wrapper before {}'</span>.format(self.func.__name__))
        <span class="hljs-keyword">return</span> self.func(*args, **kwargs)

<span class="hljs-meta">@DecoratorClass</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">display</span>():</span>
    print(<span class="hljs-string">'display function executed'</span>)

<span class="hljs-meta">@DecoratorClass</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">display_info</span>(<span class="hljs-params">name, age</span>):</span>
    print(<span class="hljs-string">'display_info function executed with arguments ({}, {})'</span>.format(name, age))

display_info(<span class="hljs-string">'Kalam'</span>, <span class="hljs-number">83</span>)
display()
</code></pre>
<p>In this class-based decorator:</p>
<ul>
<li><strong><code>__init__</code> Method:</strong> This method binds the original function to an instance of the class.</li>
<li><strong><code>__call__</code> Method:</strong> This method allows an instance of <code>DecoratorClass</code> to be called as a function. It prints a message and then calls the original function with any provided arguments.</li>
<li><strong>Decorating Functions:</strong> We use the <code>@DecoratorClass</code> syntax to decorate the <code>display</code> and <code>display_info</code> functions.</li>
<li><strong>Execution:</strong> When <code>display_info('Kalam', 83)</code> is called, the <code>__call__</code> method of <code>DecoratorClass</code> is executed, printing the message and then executing <code>display_info</code>. Similarly, when <code>display()</code> is called, it executes the <code>__call__</code> method, prints the message, and then executes <code>display</code>.</li>
</ul>
<p>Both function-based and class-based decorators provide the same functionality. The choice between them depends on personal preference and the complexity of the decorator logic.</p>
<h2 id="heading-best-practices-for-using-decorators">Best Practices for Using Decorators</h2>
<p>When using decorators in Python, it's essential to follow best practices to maintain clean, maintainable code that aligns with Pythonic conventions.</p>
<h4 id="heading-1-preserve-function-metadata-with-functoolswraps">1. Preserve Function Metadata with <code>functools.wraps</code></h4>
<p>When you create a decorator, the original function's metadata (such as its name, docstring, and module) is often lost. This can lead to confusion and issues with introspection, documentation, and debugging. To preserve this metadata, use the <code>functools.wraps</code> decorator within your wrapper function.</p>
<p><code>functools.wraps</code> was introduced in Python 2.5 as part of the <code>functools</code> module, which provides higher-order functions and operations on callable objects. The <code>wraps</code> decorator is specifically designed to update the wrapper function to look more like the wrapped function by copying attributes such as the function name, module, and docstring (yes, you guessed it right - <code>functools.wraps()</code> itself is a decorator). </p>
<p>Let's see an Example:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> functools

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">decoratorFunction</span>(<span class="hljs-params">func</span>):</span>
<span class="hljs-meta">    @functools.wraps(func)</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapperFunction</span>(<span class="hljs-params">*args, **kwargs</span>):</span>
        print(<span class="hljs-string">f'Wrapper executed before <span class="hljs-subst">{func.__name__}</span>'</span>)
        <span class="hljs-keyword">return</span> func(*args, **kwargs)
    <span class="hljs-keyword">return</span> wrapperFunction

<span class="hljs-meta">@decoratorFunction</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">display</span>():</span>
    <span class="hljs-string">"""Display function docstring"""</span>
    print(<span class="hljs-string">'The display function was called'</span>)

print(display.__name__)   <span class="hljs-comment"># Outputs: display</span>
print(display.__doc__)    <span class="hljs-comment"># Outputs: Display function docstring</span>
</code></pre>
<p>In this example, <code>@functools.wraps(func)</code> is used to ensure that the <code>wrapperFunction</code> retains the original <code>func</code>'s metadata.</p>
<h4 id="heading-2-keep-decorators-simple-and-focused">2. Keep Decorators Simple and Focused</h4>
<p>A decorator should have a single responsibility and should not try to do too many things. If a decorator becomes complex, consider breaking it down into multiple, simpler decorators that can be composed together. Example:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> functools

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">log_function_call</span>(<span class="hljs-params">func</span>):</span>
<span class="hljs-meta">    @functools.wraps(func)</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapper</span>(<span class="hljs-params">*args, **kwargs</span>):</span>
        print(<span class="hljs-string">f'Calling <span class="hljs-subst">{func.__name__}</span>'</span>)
        <span class="hljs-keyword">return</span> func(*args, **kwargs)
    <span class="hljs-keyword">return</span> wrapper

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">measure_time</span>(<span class="hljs-params">func</span>):</span>
    <span class="hljs-keyword">import</span> time
<span class="hljs-meta">    @functools.wraps(func)</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapper</span>(<span class="hljs-params">*args, **kwargs</span>):</span>
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(<span class="hljs-string">f'<span class="hljs-subst">{func.__name__}</span> took <span class="hljs-subst">{end - start}</span> seconds'</span>)
        <span class="hljs-keyword">return</span> result
    <span class="hljs-keyword">return</span> wrapper

<span class="hljs-meta">@log_function_call</span>
<span class="hljs-meta">@measure_time</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">compute_square</span>(<span class="hljs-params">n</span>):</span>
    <span class="hljs-keyword">return</span> n * n

print(compute_square(<span class="hljs-number">5</span>))
</code></pre>
<p>In this example, <code>log_function_call</code> and <code>measure_time</code> are simple, single-responsibility decorators that can be composed to add both logging and timing functionality to <code>compute_square</code>. This is what Decorators do - providing a clean and readable way to implement common patterns like logging and timing.</p>
<h4 id="heading-3-use-descriptive-names-for-decorators-and-wrapped-functions">3. Use Descriptive Names for Decorators and Wrapped Functions</h4>
<p>Choose clear and descriptive names for your decorators and the functions they wrap so they clearly indicates their functionality. This makes the purpose and behavior of the code more apparent. </p>
<h4 id="heading-4-document-your-decorators">4. Document Your Decorators</h4>
<p>Always document your decorators, explaining their purpose and how they should be used. This is especially important if others will use your decorators or if you are working in a team.</p>
<h2 id="heading-practical-applications-of-decorators">Practical Applications of Decorators</h2>
<p>Now you might be wondering, "Okay, decorators are fancy and all, but how and where do we actually use them?" Well, here are some practical applications:</p>
<ul>
<li><strong>Logging Function Calls</strong>:<br>Logging is a common requirement for tracking the usage of functions and methods, especially in debugging and monitoring applications.</li>
<li><strong>Timing Functions</strong>:<br>Decorators can measure the time it takes for a function to execute, which is useful for performance analysis.</li>
</ul>
<p>We have seen both the examples above in the <a class="post-section-overview" href="#heading-2-keep-decorators-simple-and-focused">best practices section.</a></p>
<p>Beyond these common uses, there are other usecases such as:</p>
<ul>
<li><strong>Input Validation:</strong><br>Decorators can be used to validate inputs to functions, ensuring that they meet certain criteria before the function proceeds.</li>
<li><strong>Memoization</strong>:<br>The <code>memoize</code> function is a decorator that helps to cache (store) the results of expensive function calls and reuse the cached result when the same inputs occur again. This technique is called Memoization and it is useful to optimize the performance, especially for recursive functions like calculating Fibonacci numbers.</li>
</ul>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> wraps

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">validate_non_negative</span>(<span class="hljs-params">func</span>):</span>
<span class="hljs-meta">    @wraps(func)</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapper</span>(<span class="hljs-params">*args, **kwargs</span>):</span>
        <span class="hljs-keyword">if</span> any(arg &lt; <span class="hljs-number">0</span> <span class="hljs-keyword">for</span> arg <span class="hljs-keyword">in</span> args):
            <span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">"Arguments must be non-negative"</span>)
        <span class="hljs-keyword">return</span> func(*args, **kwargs)
    <span class="hljs-keyword">return</span> wrapper

<span class="hljs-meta">@validate_non_negative</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">square_root</span>(<span class="hljs-params">x</span>):</span>
    <span class="hljs-keyword">return</span> x ** <span class="hljs-number">0.5</span>

print(square_root(<span class="hljs-number">4</span>))
</code></pre>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> functools

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">memoize</span>(<span class="hljs-params">func</span>):</span>
    cache = {}
<span class="hljs-meta">    @functools.wraps(func)</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapper</span>(<span class="hljs-params">*args</span>):</span>
        <span class="hljs-keyword">if</span> args <span class="hljs-keyword">in</span> cache:
            <span class="hljs-keyword">return</span> cache[args]
        result = func(*args)
        cache[args] = result
        <span class="hljs-keyword">return</span> result
    <span class="hljs-keyword">return</span> wrapper

<span class="hljs-meta">@memoize</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fibonacci</span>(<span class="hljs-params">n</span>):</span>
    <span class="hljs-keyword">if</span> n <span class="hljs-keyword">in</span> {<span class="hljs-number">0</span>, <span class="hljs-number">1</span>}:
        <span class="hljs-keyword">return</span> n
    <span class="hljs-keyword">return</span> fibonacci(n - <span class="hljs-number">1</span>) + fibonacci(n - <span class="hljs-number">2</span>)

fibonacci(<span class="hljs-number">10</span>)
</code></pre>
<p>Run <a target="_blank" href="https://gist.github.com/theSamyak/09a54ed5a6cc0380ee34a1a527f2c9e8">this function</a> to see the time difference when running Fibonacci function with or without memoization.</p>
<ul>
<li><strong>Access Control and Authentication</strong>:<br>In web applications, access control and authentication are crucial for security. Decorators can be used to enforce user permissions, ensuring that only authorized users can access certain functions or endpoints.</li>
</ul>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> wraps

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">requires_login</span>(<span class="hljs-params">func</span>):</span>
<span class="hljs-meta">    @wraps(func)</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapper</span>(<span class="hljs-params">*args, **kwargs</span>):</span>
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> user_is_logged_in():
            <span class="hljs-keyword">raise</span> Exception(<span class="hljs-string">"User not logged in"</span>)
        <span class="hljs-keyword">return</span> func(*args, **kwargs)
    <span class="hljs-keyword">return</span> wrapper

<span class="hljs-meta">@requires_login</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">view_dashboard</span>():</span>
    <span class="hljs-keyword">return</span> <span class="hljs-string">"Dashboard content"</span>

<span class="hljs-comment"># user_is_logged_in is a placeholder for the actual authentication check function.</span>
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Decorators in Python provide a clean and powerful way to extend the behavior of functions. By understanding first-class functions and closures, you can grasp how decorators work under the hood.</p>
<p>Whether you're using function-based or class-based decorators, you can enhance your functions without altering their original code, keeping your codebase clean and maintainable.</p>
<ul>
<li>Decorators are powerful for extending the functionality of functions.</li>
<li>They can be implemented using functions or classes.</li>
<li>The <code>@decorator</code> syntax is a cleaner and more readable way to apply decorators.</li>
<li>They help keep your code DRY (Don't Repeat Yourself) by abstracting common functionality.</li>
</ul>
<p><strong>Thank you for reading!</strong> If you have any comments, criticism, or questions, feel free to tweet or reach out to me at @<a target="_blank" href="https://x.com/OGsamyak">OGsamyak</a>. Your feedback helps me improve!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ First-Class Functions, Higher-Order Functions, and Closures in Python – Explained with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ In modern programming, it's important to understand concepts like first-class functions, higher-order functions, and closures. These ideas help us write flexible and efficient code and serve as building blocks for many advanced coding techniques. Fir... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/first-class-functions-and-closures-in-python/</link>
                <guid isPermaLink="false">66c72182e39cd88fc3e1ccf9</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Samyak Jain ]]>
                </dc:creator>
                <pubDate>Mon, 17 Jun 2024 21:19:47 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/07/first-class-functions-high-order-functions-and-closures-in-python.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In modern programming, it's important to understand concepts like first-class functions, higher-order functions, and closures. These ideas help us write flexible and efficient code and serve as building blocks for many advanced coding techniques.</p>
<p>First-class functions and higher-order functions allow us to treat functions as first-class citizens. We'll study what they are, but for now, just know that they make our code more powerful and reusable. Closures take this a step further by allowing functions to remember variables from their containing scope.</p>
<p>This tutorial will dive into these concepts and explain how they interrelate, with practical coding examples to illustrate their usage.</p>
<h2 id="heading-table-of-contents"><strong>Table of Contents</strong></h2>
<ol>
<li><a target="_blank" href="https://www.freecodecamp.org/news/first-class-functions-and-closures-in-python/#first-class-functions">First-Class Functions</a><br>– <a target="_blank" href="https://www.freecodecamp.org/news/first-class-functions-and-closures-in-python/#assigning-functions-to-variables">Assigning Functions to Variables</a><br>– <a target="_blank" href="https://www.freecodecamp.org/news/first-class-functions-and-closures-in-python/#passing-functions-as-arguments">Passing Functions as Arguments</a><br>– <a target="_blank" href="https://www.freecodecamp.org/news/first-class-functions-and-closures-in-python/#returning-functions-from-other-functions">Returning Functions from Other Functions</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/first-class-functions-and-closures-in-python/#higher-order-functions">Higher-Order Functions</a><br>– <a target="_blank" href="https://www.freecodecamp.org/news/first-class-functions-and-closures-in-python/#lambda-functions">Lambda Functions</a><br>– <a target="_blank" href="https://www.freecodecamp.org/news/first-class-functions-and-closures-in-python/#example-a-higher-order-function-that-takes-a-function-as-an-argument-first-class-function-">Higher-Order Function that Takes a Function as an Argument</a><br>– <a target="_blank" href="https://www.freecodecamp.org/news/first-class-functions-and-closures-in-python/#example-a-higher-order-function-that-returns-another-function-first-class-function-">Higher-Order Function that Returns Another Function</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/first-class-functions-and-closures-in-python/#closures">Closures</a><br>– <a target="_blank" href="https://www.freecodecamp.org/news/first-class-functions-and-closures-in-python/#basic-nested-function-with-immediate-execution">Basic Closure (Basic Nested Function with Immediate Execution)</a><br>– <a target="_blank" href="https://www.freecodecamp.org/news/first-class-functions-and-closures-in-python/#returning-the-inner-function">Returning the Inner Function</a><br>– <a target="_blank" href="https://www.freecodecamp.org/news/first-class-functions-and-closures-in-python/#using-closures-with-parameters">Using Closures with Parameters</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/first-class-functions-and-closures-in-python/#real-world-applications-of-closures">Real-World Applications</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/first-class-functions-and-closures-in-python/#conclusion">Conclusion</a></li>
</ol>
<p>To fully grasp closures, it is essential to first understand the concepts of first-class functions and higher-order functions. These concepts are the cornerstone of many advanced programming patterns and are fundamental to the functioning of closures. Let's dive into these concepts and how they interrelate.</p>
<h2 id="heading-first-class-functions"><strong>First-Class Functions</strong></h2>
<p>In programming, a language is said to have first-class functions if it treats functions as first-class citizens. This means that functions in such a language can be:</p>
<ol>
<li><strong>Assigned to variables</strong></li>
<li><strong>Passed as arguments to other functions</strong></li>
<li><strong>Returned from other functions</strong></li>
</ol>
<p>In simpler terms, first-class functions can be handled like any other variable or object in the language. Let’s explore these capabilities with some coding examples.</p>
<h3 id="heading-assigning-functions-to-variables"><strong>Assigning Functions to Variables</strong></h3>
<p>Typically, we call a function and assign its result to a variable. For instance:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span>(<span class="hljs-params">a, b</span>):</span>
    <span class="hljs-keyword">return</span> a + b

result = add(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>)

print(add)  <span class="hljs-comment"># Prints the function object</span>
print(result)  <span class="hljs-comment"># Prints 7</span>
</code></pre>
<p>Here, <code>add</code> is a function that returns the sum of two numbers. When we call <code>add(3, 4)</code>, it returns <code>7</code>, which is assigned to the variable <code>result</code>. The output of this code would be:</p>
<pre><code>&lt;<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span> <span class="hljs-title">at</span> 0<span class="hljs-title">x</span>...&gt;
7</span>
</code></pre><p>Now let's assign the <code>add</code> function to a variable <code>sum_function</code> without calling it (that is, without parentheses).</p>
<pre><code class="lang-python">sum_function = add
</code></pre>
<p>Printing <code>add</code> and <code>sum_function</code> shows they both refer to the same function object:</p>
<pre><code class="lang-python">print(add)   <span class="hljs-comment"># Outputs: &lt;function add at 0x...&gt;</span>
print(sum_function)   <span class="hljs-comment"># Outputs: &lt;function add at 0x...&gt;</span>
</code></pre>
<p>This demonstrates that functions can be assigned to variables just like any other data type. We can now use <code>sum_function</code> just like the original <code>add</code> function and even delete the original function name <code>add</code>, and the function will still be accessible through <code>sum_function</code>.</p>
<pre><code class="lang-python"><span class="hljs-keyword">del</span> add
print(sum_function(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>))  <span class="hljs-comment"># Output: 7</span>
</code></pre>
<h3 id="heading-passing-functions-as-arguments"><strong>Passing Functions as Arguments</strong></h3>
<p>Another aspect of first-class functions is the ability to pass them as arguments to other functions. This allows for greater flexibility and modularity by enabling functions to operate on other functions.</p>
<p>Let's illustrate this with a custom <code>map</code> function. A <code>map</code> function applies a given function to each item in a list (or array) and returns a new list with the results.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">double</span>(<span class="hljs-params">n</span>):</span>
    <span class="hljs-keyword">return</span> n * <span class="hljs-number">2</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">map_function</span>(<span class="hljs-params">func, values</span>):</span>
    result = []
    <span class="hljs-keyword">for</span> value <span class="hljs-keyword">in</span> values:
        result.append(func(value))
    <span class="hljs-keyword">return</span> result

<span class="hljs-comment"># using the custom map function</span>
doubled_values = map_function(double, [<span class="hljs-number">3</span>, <span class="hljs-number">6</span>, <span class="hljs-number">9</span>, <span class="hljs-number">12</span>, <span class="hljs-number">15</span>])
print(doubled_values)  <span class="hljs-comment"># Output: [6, 12, 18, 24, 30]</span>
</code></pre>
<p>In this example, the <code>double</code> function takes a number <code>n</code> and returns its double. The <code>map_function</code> function takes a function <code>func</code> and a list of <code>values</code>, applies <code>func</code> to each element in <code>values</code>, and returns a new list with the results.</p>
<p>When <code>map_function</code> is called with <code>double</code> and the list <code>[3, 6, 9, 12, 15]</code>, it applies the <code>double</code> function to each element in the list, resulting in <code>[6, 12, 18, 24, 30]</code>. This demonstrates how functions can be passed as arguments to create flexible and reusable code patterns.</p>
<p>Note that when passing the function, we do not include parentheses (that is, <code>double</code> instead of <code>double()</code>), indicating that we are passing the function itself and not the result of calling the function.</p>
<h3 id="heading-returning-functions-from-other-functions"><strong>Returning Functions from Other Functions</strong></h3>
<p>Returning functions from other functions is another important characteristic of first-class functions. This concept allows for the creation of more complex and modular code, often used in scenarios like creating configurable functions or closures.</p>
<p>To illustrate further, let's look at a practical example where a function returns another function:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">create_multiplier</span>(<span class="hljs-params">factor</span>):</span>
    <span class="hljs-string">"""Returns a function that multiplies its input by the given factor."""</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">multiplier</span>(<span class="hljs-params">x</span>):</span>
        <span class="hljs-keyword">return</span> x * factor
    <span class="hljs-keyword">return</span> multiplier

<span class="hljs-comment"># Create specific multiplier functions</span>
double = create_multiplier(<span class="hljs-number">2</span>)
triple = create_multiplier(<span class="hljs-number">3</span>)

<span class="hljs-comment"># Use the created functions</span>
print(double(<span class="hljs-number">5</span>))  <span class="hljs-comment"># Output: 10</span>
print(triple(<span class="hljs-number">5</span>))  <span class="hljs-comment"># Output: 15</span>
</code></pre>
<p>In this example, the <code>create_multiplier</code> function takes a parameter <code>factor</code> and returns another function <code>multiplier</code>. This <code>multiplier</code> function, when called with an argument <code>x</code>, returns the product of <code>x</code> and <code>factor</code>.</p>
<p>When <code>create_multiplier</code> is called with <code>2</code>, it returns a function that multiplies its argument by <code>2</code>. Similarly, when called with <code>3</code>, it returns a function that multiplies its argument by <code>3</code>. These returned functions (<code>double</code> and <code>triple</code>) can then be called with arguments to perform multiplication. For example, <code>double(5)</code> returns <code>10</code> and <code>triple(5)</code> returns <code>15</code>.</p>
<p>This is the essence of a closure – where the returned function (<code>multiplier</code>) retains access to the variable (<code>factor</code> ) from its enclosing scope, even after the outer function (<code>create_multiplier</code>) has finished executing. This allows the created functions (<code>double</code> and <code>triple</code>) to remember and use the <code>factor</code> value they were created with.</p>
<h2 id="heading-higher-order-functions"><strong>Higher-Order Functions</strong></h2>
<p>Higher-order functions derive their power from the ability to treat functions as first-class citizens. This means functions can be passed as arguments to other functions or returned as values from them. </p>
<p>A higher-order function can:</p>
<ul>
<li>Take one or more functions as arguments</li>
<li>Return a function as its result</li>
</ul>
<p>We've seen examples of both already:</p>
<ul>
<li>In our "<a target="_blank" href="https://www.freecodecamp.org/news/first-class-functions-and-closures-in-python/#passing-functions-as-arguments">Passing Functions as Arguments</a>" example, <code>map_function</code> is a higher-order function because it takes a function (<code>double</code>) as an argument.</li>
<li>In our "<a target="_blank" href="https://www.freecodecamp.org/news/first-class-functions-and-closures-in-python/#returning-functions-from-other-functions">Returning Functions from Other Functions</a>" example, <code>create_multiplier</code> is a higher-order function because it returns another function (<code>multiplier</code>) as a result.</li>
</ul>
<p>Before we move to closures, let's quickly discuss Lambda functions, as they add another layer of flexibility and allow for more concise and expressive code.</p>
<h3 id="heading-lambda-functions"><strong>Lambda Functions</strong></h3>
<p>Lambda functions in Python, also known as anonymous functions, are small, functions defined using the <code>lambda</code> keyword. They are often used for short-term tasks that do not require a full function definition with <code>def</code>. Their Syntax is:</p>
<pre><code class="lang-python"><span class="hljs-keyword">lambda</span> arguments: expression
</code></pre>
<p>The reason we are discussing them is b/c they can be passed as arguments to higher-order functions or returned from them, making them versatile tools in functional programming.</p>
<h4 id="heading-example-using-lambda-functions-in-a-custom-map-function"><strong>Example: Using Lambda Functions in a Custom Map Function</strong></h4>
<p>We previously discussed the <code>map_function</code> example. Let’s see how we can achieve the same functionality using a lambda function:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">map_function</span>(<span class="hljs-params">func, values</span>):</span>
    <span class="hljs-keyword">return</span> [func(value) <span class="hljs-keyword">for</span> value <span class="hljs-keyword">in</span> values]

<span class="hljs-comment"># Using a lambda function as the argument</span>
doubled_values = map_function(<span class="hljs-keyword">lambda</span> n: n * <span class="hljs-number">2</span>, [<span class="hljs-number">3</span>, <span class="hljs-number">6</span>, <span class="hljs-number">9</span>, <span class="hljs-number">12</span>, <span class="hljs-number">15</span>])
print(doubled_values)  <span class="hljs-comment"># Output: [6, 12, 18, 24, 30]</span>
</code></pre>
<p>In this example, the lambda function <code>lambda n: n * 2</code> is passed directly to <code>map_function</code>, eliminating the need for a separate <code>double</code> function definition.</p>
<h4 id="heading-example-creating-multiplier-functions-with-lambdas"><strong>Example: Creating Multiplier Functions with Lambdas</strong></h4>
<p>Revisiting the <code>create_multiplier</code> example, we can use a lambda function for the <code>multiplier</code>:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">create_multiplier</span>(<span class="hljs-params">factor</span>):</span>
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">lambda</span> x: x * factor

<span class="hljs-comment"># Create specific multiplier functions</span>
double = create_multiplier(<span class="hljs-number">2</span>)
triple = create_multiplier(<span class="hljs-number">3</span>)

<span class="hljs-comment"># Use the created functions</span>
print(double(<span class="hljs-number">5</span>))  <span class="hljs-comment"># Output: 10</span>
print(triple(<span class="hljs-number">5</span>))  <span class="hljs-comment"># Output: 15</span>
</code></pre>
<p>Here, <code>create_multiplier</code> returns a lambda function that multiplies its input by the specified <code>factor</code>. This is a compact and expressive way to define the same functionality.</p>
<p>For a more in-depth understanding of lambda functions, you can check this tutorial <a target="_blank" href="https://www.freecodecamp.org/news/p/8926a586-a677-442f-8fa9-6ba325286250/">here</a>.</p>
<h4 id="heading-the-interdependence-of-higher-order-functions-and-first-class-functions">The Interdependence of Higher-Order Functions and First-Class Functions:</h4>
<p>Higher-order functions are fundamentally tied to the concept of first-class functions. Without Python's support for treating functions as first-class citizens, higher-order functions wouldn't be possible.</p>
<p>We can say - Without first-class functions, we cannot have higher-order functions, as they inherently rely on the ability to treat functions as first-class entities, operating on them by taking them as arguments or returning them as results.</p>
<p>Let's understand with more examples:</p>
<h4 id="heading-example-a-higher-order-function-that-takes-a-function-as-an-argument-first-class-function"><strong>Example: A Higher-Order Function that Takes a Function as an Argument (First Class Function)</strong></h4>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">apply_operation</span>(<span class="hljs-params">operation, x, y</span>):</span>
    <span class="hljs-keyword">return</span> operation(x, y)

<span class="hljs-comment"># Functions to pass as arguments</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span>(<span class="hljs-params">x, y</span>):</span>
    <span class="hljs-keyword">return</span> x + y

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">multiply</span>(<span class="hljs-params">x, y</span>):</span>
    <span class="hljs-keyword">return</span> x * y

<span class="hljs-comment"># Using the higher-order function</span>
result_add = apply_operation(add, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>)
result_multiply = apply_operation(multiply, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>)

print(result_add)       <span class="hljs-comment"># Output: 7</span>
print(result_multiply)  <span class="hljs-comment"># Output: 12</span>
</code></pre>
<p>In this example, <code>apply_operation</code> is a higher-order function because it takes another function (<code>operation</code>) as an argument. The <code>add</code> and <code>multiply</code> functions are first-class functions because they can be passed as arguments to other functions.</p>
<p>The <code>apply_operation</code> function takes three parameters: a function (<code>operation</code>) and two integers (<code>x</code> and <code>y</code>). It returns the result of applying the <code>operation</code> function to <code>x</code> and <code>y</code>.</p>
<p>By calling <code>apply_operation(add, 3, 4)</code>, it returns 7, the result of adding 3 and 4. Similarly, calling <code>apply_operation(multiply, 3, 4)</code> returns 12, the result of multiplying 3 and 4. This demonstrates the flexibility and reusability of higher-order functions, showing how we can perform different operations on the same set of inputs.</p>
<h4 id="heading-example-a-higher-order-function-that-returns-another-function-first-class-function"><strong>Example: A Higher-Order Function that Returns Another Function (First Class Function)</strong></h4>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">discount_applier</span>(<span class="hljs-params">discount_rate</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">apply_discount</span>(<span class="hljs-params">price</span>):</span>
        <span class="hljs-keyword">return</span> price - (price * discount_rate / <span class="hljs-number">100</span>)
    <span class="hljs-keyword">return</span> apply_discount

<span class="hljs-comment"># Creating closures with different discount rates</span>
holiday_discount = discount_applier(<span class="hljs-number">20</span>)
member_discount = discount_applier(<span class="hljs-number">15</span>)

<span class="hljs-comment"># Applying the discounts</span>
print(holiday_discount(<span class="hljs-number">100</span>))  <span class="hljs-comment"># Output: 80.0</span>
print(member_discount(<span class="hljs-number">100</span>))   <span class="hljs-comment"># Output: 85.0</span>
</code></pre>
<p>In this example, <code>discount_applier</code> takes a parameter <code>discount_rate</code> and returns a new function <code>apply_discount</code>. This makes it a "higher-order function" and <code>apply_discount</code> is considered a "first-class function" because it is defined inside <code>discount_applier</code> and returned to be used later.</p>
<p>This <code>apply_discount</code> function, when called with an argument <code>price</code>, returns the discounted price calculated using the <code>discount_rate</code>.</p>
<p>When <code>discount_applier</code> is called with a discount rate of 20, it returns a function that applies a 20% discount to its argument. Similarly, when called with a discount rate of 15, it returns a function that applies a 15% discount. These returned functions (<code>holiday_discount</code> and <code>member_discount</code>) can then be used to apply the respective discounts.</p>
<p>By calling <code>holiday_discount(100)</code>, it returns 80.0, applying a 20% discount to 100. Calling <code>member_discount(100)</code> returns 85.0, applying a 15% discount.</p>
<p>These examples illustrate how higher-order functions enable the creation of flexible, reusable, and modular code patterns by leveraging the capabilities of first-class functions. They form the foundation of many advanced programming techniques, including closures, and are essential for writing expressive and powerful code.</p>
<h2 id="heading-closures"><strong>Closures</strong></h2>
<p>A closure is a feature in many programming languages, including Python, that allows a function to remember and access variables from an enclosing scope even after the outer function has finished executing.</p>
<p>In simpler terms, a closure is an inner function that has access to variables from its containing (or outer) function, even after that outer function has completed its execution.</p>
<p>Let's look at a few examples to understand how closures work in Python:</p>
<h3 id="heading-basic-nested-function-with-immediate-execution"><strong>Basic Nested Function with Immediate Execution</strong></h3>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">outer_scope</span>():</span>
    name = <span class="hljs-string">'Sam'</span>
    city = <span class="hljs-string">'New York'</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">inner_scope</span>():</span>
        print(<span class="hljs-string">f"Hello <span class="hljs-subst">{name}</span>, Greetings from <span class="hljs-subst">{city}</span>"</span>)

    <span class="hljs-keyword">return</span> inner_scope()

outer_scope()
</code></pre>
<p>In this example, the <code>outer_scope</code> function defines two local variables: <code>name</code> and <code>city</code>. It then defines and immediately calls <code>inner_scope</code>, which prints a greeting message using the <code>name</code> and <code>city</code> variables from the enclosing scope.</p>
<p>When <code>outer_scope</code> is called, the nested function <code>inner_scope</code> runs, producing the greeting message: "Hello Sam, Greetings from New York".</p>
<h3 id="heading-returning-the-inner-function"><strong>Returning the Inner Function</strong></h3>
<p>Now, let's modify the example to return the inner function without executing it immediately:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">outer_scope</span>():</span>
    name = <span class="hljs-string">'Sam'</span>
    city = <span class="hljs-string">'New York'</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">inner_scope</span>():</span>
        print(<span class="hljs-string">f"Hello <span class="hljs-subst">{name}</span>, Greetings from <span class="hljs-subst">{city}</span>"</span>)

    <span class="hljs-keyword">return</span> inner_scope

<span class="hljs-comment"># Assigning the inner function to a variable</span>
greeting_func = outer_scope()

<span class="hljs-comment"># Calling the inner function</span>
greeting_func()
</code></pre>
<p>Here, <code>outer_scope</code> defines <code>name</code> and <code>city</code> as variables similarly to the above example. It then defines and returns the <code>inner_scope</code> function but this time without calling it (that is, <code>inner_scope</code> instead of <code>inner_scope()</code>),</p>
<p>When <code>greeting_func = outer_scope()</code> is executed, it assigns the <code>inner_scope</code> function returned by <code>outer_scope</code> to <code>greeting_func</code>.</p>
<p>Now, <code>greeting_func</code> holds a reference to the <code>inner_scope</code> function. Calling <code>greeting_func()</code> executes <code>inner_scope</code>, which prints: "Hello Sam, Greetings from New York".</p>
<p>Even though <code>outer_scope</code> has finished executing by the time we call <code>greeting_func()</code>, the <code>inner_scope</code> function (now referenced by <code>greeting_func</code>) retains access to the variables <code>name</code> and <code>city</code> from its enclosing scope. This is what makes it a closure – it "closes over" the variables from its containing scope.</p>
<h3 id="heading-using-closures-with-parameters"><strong>Using Closures with Parameters</strong></h3>
<p>To demonstrate the power of closures, let's create a more dynamic example by adding parameters to the <code>outer_scope</code> function:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">outer_scope</span>(<span class="hljs-params">name, city</span>):</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">inner_scope</span>():</span>
        print(<span class="hljs-string">f"Hello <span class="hljs-subst">{name}</span>, Greetings from <span class="hljs-subst">{city}</span>"</span>)

    <span class="hljs-keyword">return</span> inner_scope

<span class="hljs-comment"># Creating closures with different names and locations</span>
greet_priyanshu = outer_scope(<span class="hljs-string">'Dr Priyanshu'</span>, <span class="hljs-string">'Jaipur'</span>)
greet_sam = outer_scope(<span class="hljs-string">'Sam'</span>, <span class="hljs-string">'New York'</span>)

<span class="hljs-comment"># Executing the closures</span>
greet_priyanshu()    <span class="hljs-comment"># Output: Hello Dr Priyanshu, Greetings from Jaipur</span>
greet_sam()     <span class="hljs-comment"># Output: Hello Sam, Greetings from New York</span>
</code></pre>
<p>Now here, the <code>outer_scope</code> function takes <code>name</code> and <code>city</code> as parameters. Inside <code>outer_scope</code>, the <code>inner_scope</code> function is defined to print a greeting message using <code>name</code> and <code>city</code>. Instead of calling <code>inner_scope</code>, <code>outer_scope</code> returns the <code>inner_scope</code> function itself.</p>
<p>When <code>outer_scope</code> is called with specific arguments, it creates and returns a closure that captures these arguments. For instance, <code>greet_priyanshu</code> is a closure that remembers <code>Dr Priyanshu</code> and <code>Jaipur</code>, while <code>greet_sam</code> remembers <code>Sam</code> and <code>New York</code>. When these closures are called, they produce the respective greeting messages.</p>
<p>Even though <code>outer_scope</code> has finished executing in both cases, the <code>inner_scope</code> functions (now <code>greet_priyanshu</code> and <code>greet_sam</code>) retain access to their respective <code>name</code> and <code>city</code> variables from their enclosing scopes, demonstrating closure behavior.</p>
<p>If you want, you can also use a lambda function in place of our inner function (<code>inner_scope</code>) like this:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">outer_scope</span>(<span class="hljs-params">name, city</span>):</span>
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">lambda</span>: print(<span class="hljs-string">f"Hello <span class="hljs-subst">{name}</span>, Greetings from <span class="hljs-subst">{city}</span>"</span>)

greet_priyanshu = outer_scope(<span class="hljs-string">'Dr Priyanshu'</span>, <span class="hljs-string">'Jaipur'</span>)
greet_sam = outer_scope(<span class="hljs-string">'Sam'</span>, <span class="hljs-string">'New York'</span>)

greet_priyanshu()    <span class="hljs-comment"># Output: Hello Dr Priyanshu, Greetings from Jaipur</span>
greet_sam()           <span class="hljs-comment"># Output: Hello Sam, Greetings from New York</span>
</code></pre>
<p>By using a lambda function, we achieve the same result but in a more concise way. The closures created by <code>outer_scope</code> still retain access to the <code>name</code> and <code>city</code> variables, demonstrating the same closure behavior.</p>
<h2 id="heading-real-world-applications-of-closures"><strong>Real-World Applications of Closures</strong></h2>
<p>Now let's see some practical applications of closures in real-world programming. Here are a few scenarios where closures are commonly used:</p>
<h3 id="heading-event-handlers-in-web-development-a-js-example-but-important-use-case"><strong>Event Handlers in Web Development (a js example but important use case)</strong></h3>
<p>In JavaScript, closures are often used to handle events, such as button clicks.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Button Handler Example<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"button1"</span>&gt;</span>Button 1<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"button2"</span>&gt;</span>Button 2<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
        <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createButtonHandler</span>(<span class="hljs-params">buttonName</span>) </span>{
            <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
                alert(<span class="hljs-string">`Button <span class="hljs-subst">${buttonName}</span> clicked!`</span>);
            };
        }

        <span class="hljs-keyword">const</span> button1 = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'button1'</span>);
        <span class="hljs-keyword">const</span> button2 = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'button2'</span>);

        button1.onclick = createButtonHandler(<span class="hljs-string">'Button 1'</span>);
        button2.onclick = createButtonHandler(<span class="hljs-string">'Button 2'</span>);
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p><strong>Explanation</strong>:</p>
<ul>
<li><code>createButtonHandler</code> is a higher-order function that takes a <code>buttonName</code> as an argument and returns a function (the closure).</li>
<li>The returned function (closure) captures the <code>buttonName</code> variable from its lexical scope.</li>
<li>When a button is clicked, the corresponding closure is invoked, and it has access to the <code>buttonName</code> that was passed when the handler was created.</li>
</ul>
<h3 id="heading-maintaining-state-in-gui-applications"><strong>Maintaining State in GUI Applications</strong></h3>
<p>In Python, closures can be used to maintain state in graphical user interface (GUI) applications, such as those created with <a target="_blank" href="https://github.com/theSamyak/Tkinter-V3">Tkinter</a>.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> tkinter <span class="hljs-keyword">as</span> tk

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">create_counter</span>():</span>
    count = <span class="hljs-number">0</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">counter</span>():</span>
        <span class="hljs-keyword">nonlocal</span> count
        count += <span class="hljs-number">1</span>
        print(<span class="hljs-string">f'Button clicked <span class="hljs-subst">{count}</span> times'</span>)
    <span class="hljs-keyword">return</span> counter

root = tk.Tk()
root.title(<span class="hljs-string">'Counter Example'</span>)

counter = create_counter()
button = tk.Button(root, text=<span class="hljs-string">'Click me'</span>, command=counter)
button.pack(pady=<span class="hljs-number">20</span>)

root.mainloop()
</code></pre>
<p><strong>Explanation</strong>:</p>
<ul>
<li><code>create_counter</code> is a higher-order function that initializes <code>count</code> to 0 and defines a nested <code>counter</code> function.</li>
<li>The <code>counter</code> function is a closure that captures the <code>count</code> variable from the enclosing scope.</li>
<li>The <code>nonlocal</code> keyword allows the closure to modify the <code>count</code> variable.</li>
<li>Each time the button is clicked, the <code>counter</code> function is invoked, and it increments and prints the <code>count</code>.</li>
</ul>
<p>Some other applications include:</p>
<h3 id="heading-creating-decorators"><strong>Creating Decorators</strong></h3>
<p>Decorators in Python are a powerful tool for modifying or extending the behavior of functions and methods. Closures are the underlying mechanism for implementing decorators.  </p>
<p>You can read <a target="_blank" href="https://www.freecodecamp.org/news/decorators-in-python-tutorial/">this article on Decorators</a> to learn more about them if you'd like.</p>
<h3 id="heading-data-hiding-and-encapsulation"><strong>Data Hiding and Encapsulation</strong></h3>
<p>Closures can be used to create private variables and methods in a function, which can be accessed and modified only by the inner function. This provides a way to achieve encapsulation in Python.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p><strong>First-class functions</strong> allows you to treat functions as any other object or data types, offering the flexibility to:</p>
<ol>
<li>Assign them to variables</li>
<li>Pass them as arguments to other functions</li>
<li>Return them from other functions</li>
</ol>
<p>On the other hand, <strong>Higher-order functions</strong> not only let you treat functions like data, but they also let you use functions to create new functions or to change how other functions behave, enabling operations such as:</p>
<ol>
<li>Accepting functions as arguments/parameters</li>
<li>Returning functions as results</li>
</ol>
<p>This capability allows for dynamic and reusable code patterns, essential for functional programming.</p>
<p><strong>Closures</strong>, in summary, allow inner functions to access variables from their enclosing scope.</p>
<p>Practical usage of closures includes scenarios where you need functions to remember state even after the outer function has completed execution.</p>
<p><strong>Thank you for reading!</strong> If you have any comments, criticisms, or questions, feel free to tweet or reach out to me at @<a target="_blank" href="https://x.com/OGsamyak">OGsamyak</a>. Your feedback helps me improve!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Lambda Functions in Python – How to Use Lambdas with Map, Filter, and Reduce ]]>
                </title>
                <description>
                    <![CDATA[ In this tutorial, we will explore the various aspects of lambda functions in Python, including their syntax, use cases, and limitations. By understanding how to effectively utilize lambda functions, you can write more concise and efficient Python cod... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/lambda-functions-in-python/</link>
                <guid isPermaLink="false">66c7218b6cc1d99b93d53b2b</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Samyak Jain ]]>
                </dc:creator>
                <pubDate>Fri, 14 Jun 2024 14:44:05 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/07/python-lambda-functions.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this tutorial, we will explore the various aspects of lambda functions in Python, including their syntax, use cases, and limitations.</p>
<p>By understanding how to effectively utilize lambda functions, you can write more concise and efficient Python code. This will enhance your programming skills and make your codebase cleaner and easier to manage.</p>
<h2 id="heading-table-of-contents"><strong>Table of Contents:</strong></h2>
<ol>
<li><a target="_blank" href="https://www.freecodecamp.org/news/lambda-functions-in-python/#what-are-lambda-functions-in-python">What are Lambda Functions in Python?</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/lambda-functions-in-python/#lambda-function-syntax-and-basic-uses">Lambda Function Syntax and Basic Uses</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/lambda-functions-in-python/#ways-to-call-lambda-functions">Ways to Call Lambda Functions</a><br>– <a target="_blank" href="https://www.freecodecamp.org/news/lambda-functions-in-python/#1-assigning-to-a-variable">Assigning to a Variable</a><br>– <a target="_blank" href="https://www.freecodecamp.org/news/lambda-functions-in-python/#2-directly-calling-the-lambda-function">Directly Calling the Lambda Function</a><br>– <a target="_blank" href="https://www.freecodecamp.org/news/lambda-functions-in-python/#3-using-as-an-argument-to-higher-order-functions">Using as an Argument to Higher-Order Functions</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/lambda-functions-in-python/#additional-use-cases">Additional Use Cases</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/lambda-functions-in-python/#conclusion">Conclusion</a></li>
</ol>
<h2 id="heading-what-are-lambda-functions-in-python"><strong>What are Lambda Functions in Python?</strong></h2>
<p>In Python, a lambda function is a small, anonymous function defined using the <code>lambda</code> keyword.</p>
<p>These functions are typically used for short, throwaway operations where a full function definition might be overkill. They are called anonymous because they do not require a name (although they can be assigned to a variable for reuse).</p>
<p>Lambda functions excel in scenarios where you need a quick, simple function for a brief period, and a full function definition would be excessive. This makes them ideal for operations that are straightforward and can be written in a single line, such as simple mathematical calculations or basic data transformations.</p>
<p>They are particularly used in functional programming contexts with higher-order functions like <code>map</code>, <code>filter</code>, and <code>reduce</code> where they are often passed as arguments. Just remember that for more complex operations, regular functions are preferred for their readability and maintainability.</p>
<h2 id="heading-lambda-function-syntax-and-basic-uses"><strong>Lambda Function Syntax and Basic Uses</strong></h2>
<pre><code class="lang-python"><span class="hljs-keyword">lambda</span> arguments: expression

<span class="hljs-comment"># to give it a name, assign it to a variable:</span>
function_name = <span class="hljs-keyword">lambda</span> arguments: expression

<span class="hljs-comment"># this is equivalent to:</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">function_name</span>(<span class="hljs-params">arguments</span>):</span>
    <span class="hljs-keyword">return</span> expression
</code></pre>
<p>Unlike regular functions defined with <code>def</code>, lambda functions are limited to a single expression due to their design for simplicity and brevity. They can take single or multiple arguments but cannot contain statements or multiple expressions.</p>
<p>Lambda functions are intended for short, straightforward operations that can be written in a single line.</p>
<p>Example:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Regular function to find the average of three numbers</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">average</span>(<span class="hljs-params">x, y, z</span>):</span>
    <span class="hljs-keyword">return</span> (x + y + z) / <span class="hljs-number">3</span>

<span class="hljs-comment"># Lambda function to find the average of three numbers</span>
average = <span class="hljs-keyword">lambda</span> x, y, z: (x + y + z) / <span class="hljs-number">3</span>
</code></pre>
<p>Although lambda functions can only contain one expression, we can still do a lot with them.</p>
<p>For example, here's a Lambda function to concatenate 2 strings and convert them to uppercase:</p>
<pre><code class="lang-python">concat_and_uppercase = <span class="hljs-keyword">lambda</span> str1, str2: (<span class="hljs-string">f'The concatenated string is <span class="hljs-subst">{str1 + str2}</span>'</span>.upper())

print(concat_and_uppercase(<span class="hljs-string">"hello"</span>, <span class="hljs-string">"world"</span>))  <span class="hljs-comment"># Output: THE CONCATENATED STRING IS HELLOWORLD</span>
</code></pre>
<h2 id="heading-ways-to-call-lambda-functions"><strong>Ways to Call Lambda Functions</strong></h2>
<p>There are primarily three ways to use or call lambda functions:</p>
<h3 id="heading-1-assigning-to-a-variable"><strong>1. Assigning to a Variable</strong></h3>
<p>Assign the lambda function to a variable and then call it using that variable:</p>
<pre><code class="lang-python">multiply = <span class="hljs-keyword">lambda</span> x, y: print(<span class="hljs-string">f'<span class="hljs-subst">{x}</span> * <span class="hljs-subst">{y}</span> = <span class="hljs-subst">{x * y}</span>'</span>)
multiply(<span class="hljs-number">2</span>, <span class="hljs-number">10</span>)  <span class="hljs-comment"># Output: 2 * 10 = 20</span>

<span class="hljs-keyword">or</span> 

multiply = <span class="hljs-keyword">lambda</span> x, y: <span class="hljs-string">f'<span class="hljs-subst">{x}</span> * <span class="hljs-subst">{y}</span> = <span class="hljs-subst">{x * y}</span>'</span>
print(multiply(<span class="hljs-number">2</span>, <span class="hljs-number">10</span>))  <span class="hljs-comment"># Output: 2 * 10 = 20</span>
</code></pre>
<h3 id="heading-2-directly-calling-the-lambda-function"><strong>2. Directly Calling the Lambda Function</strong></h3>
<p>Define and immediately invoke the lambda function by wrapping the definition in parentheses and providing the arguments directly:</p>
<pre><code class="lang-python">print((<span class="hljs-keyword">lambda</span> x, y: <span class="hljs-string">f'<span class="hljs-subst">{x}</span> * <span class="hljs-subst">{y}</span> = <span class="hljs-subst">{x * y}</span>'</span>)(<span class="hljs-number">2</span>, <span class="hljs-number">10</span>))  <span class="hljs-comment"># Output: 2 * 10 = 20</span>

<span class="hljs-keyword">or</span>

(<span class="hljs-keyword">lambda</span> x, y: print(<span class="hljs-string">f'<span class="hljs-subst">{x}</span> * <span class="hljs-subst">{y}</span> = <span class="hljs-subst">{x * y}</span>'</span>))(<span class="hljs-number">2</span>, <span class="hljs-number">10</span>)  <span class="hljs-comment"># Output: 2 * 10 = 20</span>
</code></pre>
<h3 id="heading-3-using-as-an-argument-to-higher-order-functions"><strong>3. Using as an Argument to Higher-Order Functions</strong></h3>
<p>Lambda functions are often used as arguments to higher-order functions like <code>map</code>, <code>filter</code>, and <code>reduce</code>.</p>
<p>These are functions that take other functions as arguments. They help in processing collections of data (like lists or tuples) in a functional programming style.</p>
<h4 id="heading-using-lambda-functions-with-map"><strong>Using lambda functions with <code>map()</code></strong></h4>
<p>The <code>map</code> function applies a specified function to each item in an iterable (like a list) and returns a new iterable with the updated items.</p>
<pre><code class="lang-python"><span class="hljs-comment"># syntax</span>

map(function, iterable)
</code></pre>
<ul>
<li><code>function</code> here takes one argument and returns a value.</li>
<li>iterable's elements (for example, <code>list</code>, <code>tuple</code>) will be passed to the function.</li>
</ul>
<p>Example:</p>
<pre><code class="lang-python"><span class="hljs-comment"># List of pairs of numbers</span>
pairs = [(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>), (<span class="hljs-number">4</span>, <span class="hljs-number">5</span>), (<span class="hljs-number">6</span>, <span class="hljs-number">7</span>)]

<span class="hljs-comment"># Using lambda function with map to multiply each pair and print the result</span>
list(map(<span class="hljs-keyword">lambda</span> pair: print(<span class="hljs-string">f'<span class="hljs-subst">{pair[<span class="hljs-number">0</span>]}</span> * <span class="hljs-subst">{pair[<span class="hljs-number">1</span>]}</span> = <span class="hljs-subst">{pair[<span class="hljs-number">0</span>] * pair[<span class="hljs-number">1</span>]}</span>'</span>), pairs))
</code></pre>
<p><strong>Explanation:</strong> In this code, we use a lambda function to define a small, anonymous function that takes each pair of numbers and prints their multiplication.</p>
<p>The <code>map</code> function applies this lambda function to each pair (tuple) in the list. Wrapping the <code>map</code> call with <code>list</code> ensures the lambda function is executed for each pair. As a result, the code prints the multiplication results for each pair in the list, showing outputs like "2 <em> 3 = 6", "4 </em> 5 = 20", and "6 * 7 = 42".</p>
<h4 id="heading-using-lambda-functions-with-filter"><strong>Using lambda functions with <code>filter()</code></strong></h4>
<p>The <code>filter</code> function filters elements in an iterable based on a specified predicate. Only elements for which the predicate returns <code>True</code> are included in the new iterable.</p>
<pre><code class="lang-python"><span class="hljs-comment"># syntax</span>

filter(predicate, iterable)
</code></pre>
<p>Predicate is a function that takes one argument and returns a boolean value (True or False). Iterable elements here will be tested by the predicate.</p>
<p>Example:</p>
<pre><code class="lang-python"><span class="hljs-comment"># List of ages</span>
ages = [<span class="hljs-number">25</span>, <span class="hljs-number">30</span>, <span class="hljs-number">18</span>, <span class="hljs-number">42</span>, <span class="hljs-number">17</span>, <span class="hljs-number">50</span>, <span class="hljs-number">22</span>, <span class="hljs-number">19</span>]

<span class="hljs-comment"># Function to filter adults (age 18 and above) using filter with lambda</span>
adults = filter(<span class="hljs-keyword">lambda</span> age: age &gt;= <span class="hljs-number">18</span>, ages)
print(list(adults))  <span class="hljs-comment"># Output: [25, 30, 18, 42, 50, 22, 19]</span>
</code></pre>
<p><strong>Explanation:</strong> In this code, we start with a list of ages. We use a lambda function to define a simple condition that checks if an age is 18 or older.</p>
<p>The <code>filter</code> function applies this lambda function to each age in the list, filtering out any ages below 18. By converting the result of <code>filter</code> to a list, we obtain a list of ages that are 18 and above. Finally, we print this filtered list, which results in the ages <code>[25, 30, 18, 42, 50, 22, 19]</code> being displayed, as these are the ages that meet the criterion of being 18 or older.</p>
<h4 id="heading-using-lambda-functions-with-reduce"><strong>Using lambda functions with <code>reduce()</code></strong></h4>
<p>The <code>reduce</code> function applies a specified function to the elements of an iterable cumulatively to reduce them to a single value. It is part of the <code>functools</code> module.</p>
<pre><code class="lang-python"><span class="hljs-comment"># syntax</span>

<span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> reduce
reduce(function, iterable)
</code></pre>
<p>Here, Function takes two arguments and returns a single value. Iterable elements will be processed by the function.</p>
<p>Example:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> reduce

<span class="hljs-comment"># List of numbers</span>
numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]

<span class="hljs-comment"># Using reduce with lambda to sum the numbers</span>
sum_of_numbers = reduce(<span class="hljs-keyword">lambda</span> x, y: x + y, numbers)
print(sum_of_numbers)  <span class="hljs-comment"># Output: 15</span>
</code></pre>
<p><strong>Explanation:</strong> In this code, we start with a list of numbers. We use the <code>reduce</code> function from the <code>functools</code> module to compute the sum of all the numbers in the list. We use a lambda function to define a simple addition operation that takes two arguments, <code>x</code> and <code>y</code>, and returns their sum. The <code>reduce</code> function applies this lambda function cumulatively to the items in the list, starting from the first pair and continuing through the entire list, like this:</p>
<ul>
<li>Initially, <code>x</code> is the first element of the list (1) and <code>y</code> is the second element (2), resulting in 3.</li>
<li>This sum (3) then becomes <code>x</code>, and the next element in the list (3) becomes <code>y</code>, yielding 6.</li>
<li>This process continues until all elements in the list have been summed. Ultimately, the final result is 15, representing the sum of all the numbers in the list [1, 2, 3, 4, 5].</li>
</ul>
<h2 id="heading-additional-use-cases"><strong>Additional Use Cases</strong></h2>
<p>Lambda functions can also be used in sorting or other functional programming contexts. For example:</p>
<h3 id="heading-sorting-a-list-of-strings"><strong>Sorting a List of Strings:</strong></h3>
<pre><code class="lang-python">cities = [<span class="hljs-string">"India"</span>, <span class="hljs-string">"Germany"</span>, <span class="hljs-string">"America"</span>, <span class="hljs-string">"Japan"</span>]
sorted_cities = sorted(cities, key=<span class="hljs-keyword">lambda</span> city: city.lower())

print(sorted_cities)  <span class="hljs-comment"># Output: ['America', 'Germany', 'India', 'Japan']</span>
</code></pre>
<p>In this code, we have a list called <code>cities</code> containing the names of different cities. We use the <code>sorted</code> function to sort these city names alphabetically, ignoring case sensitivity. The <code>key</code> parameter in the <code>sorted</code> function allows us to specify a function (in this case, a lambda function) to customize the sorting order.</p>
<p>The lambda function <code>lambda city: city.lower()</code> converts each city name to lowercase before sorting. This ensures that the sorting is case-insensitive, so cities with different capitalization are treated the same way.</p>
<p>After sorting, the sorted list is assigned to the variable <code>sorted_cities</code>, and we print the result. The output shows the sorted list of cities: <code>['America', 'Germany', 'India', 'Japan']</code>, where the cities are arranged alphabetically ignoring the case of the letters.</p>
<h3 id="heading-lambda-functions-in-list-comprehensions"><strong>Lambda Functions in List Comprehensions:</strong></h3>
<p>Lambda functions can be used within list comprehensions to apply a function to each element in a list.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-python"><span class="hljs-comment"># List of numbers</span>
numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]

<span class="hljs-comment"># Using lambda in list comprehension to square each number</span>
squared_numbers = [(<span class="hljs-keyword">lambda</span> x: x ** <span class="hljs-number">2</span>)(x) <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> numbers]
print(squared_numbers)  <span class="hljs-comment"># Output: [1, 4, 9, 16, 25]</span>
</code></pre>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Lambda functions in Python provide a quick and concise way to create small, throwaway functions. They're especially useful in functional programming with higher-order functions like <code>map</code>, <code>filter</code>, and <code>reduce</code>.</p>
<p>While lambda functions are powerful and concise, make sure you balance their use with code readability and maintainability. For more complex logic, regular functions defined with <code>def</code> are preferred because they support multiple expressions and statements, and you can include documentation.</p>
<p>By understanding and using lambda functions effectively, you can write more concise and efficient Python code.</p>
<p><strong>Thank you for reading!</strong> If you have any comments, criticisms, or questions, feel free to tweet or reach out to me at @<a target="_blank" href="https://x.com/OGsamyak">OGsamyak</a>. Your feedback helps me improve!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn Git Fundamentals – A Handbook on Day-to-Day Development Tasks ]]>
                </title>
                <description>
                    <![CDATA[ Welcome to my comprehensive guide on Git, the distributed version control system that has revolutionized collaboration and code management in software development.  Whether you're a seasoned developer or just starting your journey in programming, und... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-git-basics/</link>
                <guid isPermaLink="false">66c7218e55df43f1418b5b2c</guid>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Git ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ version control ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Samyak Jain ]]>
                </dc:creator>
                <pubDate>Wed, 03 Apr 2024 03:57:39 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/04/Learn-Git-Basics-Cover-3--1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Welcome to my comprehensive guide on Git, the distributed version control system that has revolutionized collaboration and code management in software development. </p>
<p>Whether you're a seasoned developer or just starting your journey in programming, understanding Git is essential to gain proper control over your code, efficiently managing your projects and collaborating with others. </p>
<p>In this tutorial, I'll take you through the fundamentals of Git, covering everything from its basic workflow to advanced branching strategies and rebasing techniques. </p>
<p>By the end of this guide, you'll have a solid understanding of Git's core concepts and be confident and well equipped with the skills to effectively use it in your development workflow.</p>
<h2 id="heading-prerequisites">Prerequisites:</h2>
<p>All you need to bring to the table is a curious and eager-to-learn mindset. This guide is crafted with beginners in mind, so no prior knowledge of version control systems or programming is required. Whether you're a complete novice or have some experience with coding, you'll find this tutorial accessible and easy to follow.</p>
<h2 id="heading-table-of-contents"><strong>Table of Contents:</strong></h2>
<ol>
<li><a class="post-section-overview" href="#heading-what-is-git">What is Git?</a><br>– <a class="post-section-overview" href="#heading-what-makes-git-different-from-other-version-control-systems">Difference from other version control systems</a><br>– <a class="post-section-overview" href="#heading-the-three-states-and-basic-git-workflow">The Three States and Basic Git Workflow</a></li>
<li><a class="post-section-overview" href="#heading-first-time-git-setup">First-Time Git Setup</a></li>
<li><a class="post-section-overview" href="#heading-how-to-get-help-in-git">Get Help in Git</a></li>
<li><a class="post-section-overview" href="#heading-how-to-get-a-git-repository">How to Get a Git Repository</a><br>– <a class="post-section-overview" href="#heading-1-how-to-initialize-a-repository-in-an-existing-directory-in-git">Initialize a Repository in an Existing Directory</a><br>– <a class="post-section-overview" href="#heading-2-how-to-clone-an-existing-repository-in-git">Clone an Existing Repository in Git</a></li>
<li><a class="post-section-overview" href="#heading-how-to-record-changes-to-the-repository">How to Record Changes to the Repository</a></li>
<li><a class="post-section-overview" href="#heading-how-to-view-commit-history-in-git">View Commit History in Git</a></li>
<li><a class="post-section-overview" href="#heading-how-to-undo-things-in-git">Undo Things in Git</a></li>
<li><a class="post-section-overview" href="#how-to-work-with-remote-repositories-in-git">Remote Repositories in Git</a></li>
<li><a class="post-section-overview" href="#heading-tagging-in-git">Tagging in Git</a></li>
<li><a class="post-section-overview" href="#heading-git-aliases">Git Aliases</a></li>
<li><a class="post-section-overview" href="#heading-git-branching">Git Branching</a><br>– <a class="post-section-overview" href="#heading-how-to-create-a-new-branch-in-git">Create a New Branch in Git</a><br>– <a class="post-section-overview" href="#heading-understanding-branches">Understanding Branches</a><br>– <a class="post-section-overview" href="#heading-how-to-switch-to-another-branch-in-git">Switch to Another Branch in Git</a><br>– <a class="post-section-overview" href="#how-to-visualise-branches-in-git-">Visualise Branches in Git</a></li>
<li><a class="post-section-overview" href="#heading-how-to-manage-branches-in-git">How to Manage Branches in Git</a><br>– <a class="post-section-overview" href="#heading-how-to-manage-merged-branches">Managing Merged Branches</a><br>– <a class="post-section-overview" href="#heading-how-to-rename-branches">Renaming Branches</a><br>– <a class="post-section-overview" href="#heading-how-to-change-the-default-branch-name">Changing the Default Branch Name</a></li>
<li><a class="post-section-overview" href="#heading-branching-workflow">Branching Workflow</a></li>
<li><a class="post-section-overview" href="#heading-rebasing-in-git">Rebasing in Git</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<h2 id="heading-what-is-git">What is Git?</h2>
<p>Git is a distributed version control system that helps you and your team collaborate effectively while keeping your project's history safe. It's like having a time machine for your code!</p>
<h3 id="heading-what-makes-git-different-from-other-version-control-systems">What makes Git different from other Version Control Systems?</h3>
<h4 id="heading-conceptual-difference">Conceptual Difference:</h4>
<p>The big thing that sets Git apart from other tools is how it thinks about data. Instead of storing changes to files, Git thinks of its data as a series of snapshots of your project, means, every time you make a change and save it (commit), Git takes a snapshot of all your files at that moment. If a file hasn't changed, Git just keeps a link to the previous identical file.</p>
<h4 id="heading-local-operations">Local Operations:</h4>
<p>With Git, most things you do don't need a connection to a server. Because you have the entire project history on your computer, operations are super fast. You can browse project history or see changes between versions without waiting for a server.</p>
<h4 id="heading-data-integrity">Data Integrity:</h4>
<p>Git makes sure nothing gets lost or corrupted. Every file and directory is checksummed, and Git knows if anything changes. </p>
<p>Git uses a SHA-1 hash, a unique code for each version of a file. If any changes are made to the content, even a single character, it will result in a different SHA-1 hash.</p>
<h4 id="heading-append-only-model">Append-Only Model:</h4>
<p>In Git, almost everything adds data to the project, making it hard to accidentally lose information. Once you commit changes, they are safely stored. Experimenting is less risky with Git.</p>
<h3 id="heading-the-three-states-and-basic-git-workflow">The Three States and Basic Git Workflow</h3>
<p>Understanding Git's three states—modified, staged, and committed—is essential for effective version control:</p>
<ul>
<li><strong>Modified</strong>: Changes made to files in your <strong>Working tree</strong> that are not yet committed.</li>
<li><strong>Staged</strong>: Modifications marked for the next commit in the <strong>Staging area</strong> to be included in next commit.</li>
<li><strong>Committed</strong>: Changes permanently stored in the local <strong>Git directory</strong>.</li>
</ul>
<p><strong>Basic Git Workflow</strong>:</p>
<ol>
<li><strong>Modify files</strong> in your working tree.</li>
<li><strong>Stage changes</strong> you want to include in the next commit.</li>
<li><strong>Commit changes</strong>, which permanently saves snapshots to the Git directory.</li>
</ol>
<h2 id="heading-first-time-git-setup">First-Time Git Setup</h2>
<p>Setting up Git for the first time involves customizing your Git environment to suit your preferences. But first, you'll need to download Git from <a target="_blank" href="https://git-scm.com/download/win">Git - Downloads</a> or use the Chocolatey package. Then just follow the installation instructions and you should be good to go.</p>
<h3 id="heading-git-configuration">Git Configuration</h3>
<p>We use the <code>git config</code> tool to customize our Git environment. This tool allows us to both retrieve and set configuration variables that dictate how Git operates. These variables can be stored in three different locations:</p>
<ol>
<li><strong>System-wide Configuration:</strong><br>Stored in the <code>/etc/gitconfig</code> file, these settings apply to all users on the system and all repositories. We can interact with this file using the <code>--system</code> option with <code>git config</code>.</li>
<li><strong>User-specific Configuration:</strong><br>Stored in <code>~/.gitconfig</code> or <code>~/.config/git/config</code>, these values are specific to you as a user. We can interact with this file using the <code>--global</code> option with <code>git config</code>, affecting all repositories you work with on your system.</li>
<li><strong>Repository-specific Configuration:</strong><br>Stored in the <code>.git/config</code> file within a specific repository, these settings override global configurations and apply only to that repository.</li>
</ol>
<p>Each level of configuration overrides values from the previous level. For instance, values in <code>.git/config</code> will override those in <code>~/.gitconfig</code>.</p>
<p>To view all configuration settings and their sources/origins:</p>
<pre><code class="lang-bash">$ git config --list --show-origin
</code></pre>
<h4 id="heading-how-to-configure-your-identity-in-git">How to Configure your identity in Git:</h4>
<p>Identity in Git is used for attributing commits properly. Let's set up your user name and email address.</p>
<pre><code class="lang-bash">$ git config --global user.name <span class="hljs-string">"Your Name"</span>
$ git config --global user.email <span class="hljs-string">"your.email@example.com"</span>
</code></pre>
<p>If you need to override this for specific projects, you can omit the <code>--global</code> option when setting the values, and they'll only apply to that particular repository.</p>
<h4 id="heading-how-to-configure-your-default-text-editor">How to Configure Your Default Text Editor</h4>
<p>After configuring your identity, it's important to set up your default text editor in Git. This text editor will be used when Git needs you to input messages, such as when writing commit messages or resolving merge conflicts.</p>
<p>By default, Git uses your system's default text editor. However, if you prefer to use a different text editor, such as Emacs, you can set it up like this:</p>
<pre><code class="lang-bash">$ git config --global core.editor <span class="hljs-string">"emacs"</span>
</code></pre>
<p>On Windows systems, setting up a different text editor requires specifying the full path to its executable file. For example, if you want to use Notepad++, you might use a command like this:</p>
<pre><code class="lang-bash">$ git config --global core.editor <span class="hljs-string">"'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"</span>
</code></pre>
<p>Make sure you provide the correct path to the executable file of your text editor.</p>
<p>By the way, these – <code>"-multiInst -notabbar -nosession -noPlugin"</code> – are options used to customize the behavior of Notepad++ when it is launched by Git.</p>
<h4 id="heading-how-to-change-default-branch-name-in-git-optional">How to Change default branch name in Git (optional):</h4>
<p>By default, when you initialize a new repository with <code>git init</code>, Git creates a branch named <code>master</code>. But from Git version 2.28 onwards, you have the option to set a different name for the initial branch.</p>
<pre><code class="lang-bash">$ git config --global init.defaultBranch main
</code></pre>
<h4 id="heading-how-to-check-configurationsettings-in-git">How to Check Configuration/settings in Git:</h4>
<p>You can view your Git configuration using:</p>
<pre><code class="lang-bash">$ git config --list
$ git config user.name  <span class="hljs-comment"># To check a specific setting (e.g., user name):</span>
</code></pre>
<p>The <code>git config --list</code> command lists all the configuration settings Git can find at that moment.</p>
<h2 id="heading-how-to-get-help-in-git">How to Get Help in Git</h2>
<p>There are three equivalent ways to get detailed help for any Git command:</p>
<ol>
<li>Git Help Command: <code>$ git help &lt;verb&gt;</code></li>
<li>Using the <code>--help</code> Option: <code>$ git &lt;verb&gt; --help</code></li>
<li>Manual pages (manpages): <code>$ man git-&lt;verb&gt;</code></li>
</ol>
<p>Replace the <code>&lt;verb&gt;</code> with whatever command you need help with. For example, to get help for the <code>config</code> command, you can type:</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">help</span> config
or
$ man git-config
</code></pre>
<p>These commands work offline as well, which is handy.</p>
<p>If you need quick, concise information about the available options for a Git command, you can use the <code>-h</code> option:</p>
<pre><code class="lang-bash">$ git add -h    <span class="hljs-comment"># This will display options available for the add command</span>
</code></pre>
<h2 id="heading-how-to-get-a-git-repository">How to Get a Git Repository</h2>
<p>To start using Git, you typically obtain a Git repository. There are essentially two main ways to get started:</p>
<h3 id="heading-1-how-to-initialize-a-repository-in-an-existing-directory-in-git">1. How to Initialize a Repository in an Existing Directory in Git</h3>
<p>Open a terminal or command prompt. Use the <code>cd</code> command to change the directory to your project's location: <code>cd /path/to/your/project</code>.</p>
<p>Once you're in your project directory, initialize a Git repository by running:</p>
<pre><code class="lang-bash">$ git init
</code></pre>
<p>This command creates a new subdirectory named <code>.git</code> where Git stores all the necessary files for your Git repository. At this point, none of your project files are being tracked yet.</p>
<p>Now, Suppose you have certain files that you want Git to start tracking:</p>
<pre><code class="lang-bash">$ git add *.py        <span class="hljs-comment"># Add all Python files</span>
$ git add README.md   <span class="hljs-comment"># Add README file</span>
$ git commit -m <span class="hljs-string">'Initial commit'</span>
</code></pre>
<p><code>git add</code> adds files to the staging area indicating that you want to include them in the next commit, and then commit the changes. The <code>-m</code> flag allows you to add a descriptive message to the commit.</p>
<h3 id="heading-2-how-to-clone-an-existing-repository-in-git">2. How to Clone an Existing Repository in Git:</h3>
<p>The second way to obtain a Git repository is by cloning an existing one. This is useful when you want to work on a project that already exists elsewhere (for example, a project you'd like to contribute to).</p>
<p><strong>Note:</strong> When you clone a repository, Git retrieves a full copy of nearly all data that the server has. This includes every version of every file for the history of the project. This means you'll have a complete copy of the repository's history on your local machine.</p>
<p>To clone a repo, Use the <code>git clone</code> command followed by the URL of the repo you want to clone. For example, to clone the grok-1 repository, you can use:</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">clone</span> https://github.com/xai-org/grok-1.git
</code></pre>
<p>This creates a directory named grok-1, initializes a <code>.git</code> directory inside it, and pulls down all the data for that repository.</p>
<p>BTW, <code>.git</code> is just a convention to signify that the URL points to a Git repository. You can use it or not, it doesn't matter.</p>
<p>If you want to clone into a directory with a different name, you can specify it. To clone the grok-1 repo into a directory named "chatgpt" instead of "grok-1", do this:</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">clone</span> https://github.com/xai-org/grok-1.git chatgpt
</code></pre>
<p>Git provides various transfer protocols you can use for cloning repos. The example above uses the <code>https://</code> protocol, but you may also see <code>git://</code> or <code>user@server:path/to/repo.git</code>, which uses the SSH transfer protocol.</p>
<h2 id="heading-how-to-record-changes-to-the-repository">How to Record Changes to the Repository</h2>
<p>Now that you have a Git repository set up, you'll often need to make changes and record those changes in your repository. The process involves tracking files, staging changes, and committing snapshots. Let's explore the steps involved:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/lifecycle.png" alt="Image" width="600" height="400" loading="lazy">
<em>pic credit - https://git-scm.com/</em></p>
<h3 id="heading-1-how-to-check-the-status-of-your-files-in-git">1. How to Check the Status of Your Files in Git:</h3>
<p>When working with a Git repository, it's crucial to understand the status of your files. </p>
<p>Git categorizes files into two types: tracked and untracked. Tracked files are those that Git recognizes, either because they were part of the last snapshot (commit) or have been staged. Untracked files are everything else—files that Git is not currently monitoring. To check the status of your repository:</p>
<pre><code class="lang-bash">$ git status
</code></pre>
<p>This command provides comprehensive information about the current branch, its synchronization status, and the status of your files. </p>
<p><code>git status</code> also suggests actions you can take. For instance, when files are modified but not staged for commit, <code>git status</code> suggests using <code>git add &lt;file&gt;</code> to stage them. It also suggests using <code>git checkout -- &lt;file&gt;</code> to discard changes in the working directory. These suggestions streamline your workflow by providing quick access to relevant Git commands.</p>
<p>Also, <code>git status</code> offers a Short Status mode (<code>git status -s</code>), which presents a more concise view of your changes using symbols like M (modified), A (added), and ?? (untracked) to represent file statuses.</p>
<h3 id="heading-2-how-to-track-new-files-in-git">2. How to Track New Files in Git</h3>
<p>When you create a new file in your project, Git initially considers it untracked. To start tracking a new file, you need to add it to the staging area using the <code>git add</code> command.</p>
<p>For instance, let's create a new file called <code>index.html</code> for our project and add it to the staging area:</p>
<pre><code class="lang-bash">$ touch index.html
$ git add index.html
</code></pre>
<p>After adding, running <code>git status</code> again will show that the <code>index.html</code> file is now tracked and staged for commit.</p>
<h3 id="heading-3-how-to-stage-modified-files-in-git">3. How to Stage Modified Files in Git</h3>
<p>If you modify an existing tracked file, you need to stage the changes using <code>git add</code>. Let's say we modify an existing file called <code>styles.css</code></p>
<pre><code class="lang-bash">$ vim styles.css
</code></pre>
<p>After making changes, stage the file:</p>
<pre><code class="lang-bash">$ git add styles.css
</code></pre>
<p>Now, when you check the status, you'll see both the modified file and the new file staged for commit.</p>
<h3 id="heading-4-how-to-ignore-files-in-git">4. How to Ignore Files in Git</h3>
<p>Often, there are files or directories within a project that aren't intended for Git tracking. These might include log files, build artifacts, or sensitive information like local environment settings (such as *.env or config.json). You can specify these files to be ignored using a <code>.gitignore</code> file.</p>
<p>Create a <code>.gitignore</code> file :</p>
<pre><code class="lang-bash">$ nano .gitignore
</code></pre>
<p>List the patterns of files or directories you want to ignore.:</p>
<pre><code class="lang-bash">$ <span class="hljs-built_in">echo</span> <span class="hljs-string">'*.log'</span> &gt;&gt; .gitignore
$ <span class="hljs-built_in">echo</span> <span class="hljs-string">'build/'</span> &gt;&gt; .gitignore
</code></pre>
<p>Here, we're telling Git to ignore all files with a <code>.log</code> extension and the <code>build/</code> directory.</p>
<p><strong>Note:</strong> Files already tracked by Git before being added to the <code>.gitignore</code> file will remain tracked. To remove them, you'll need to manually untrack them using Git commands. </p>
<p>Here are some patterns you can use to work more effectively in Git.</p>
<ul>
<li><strong>Target individual files or file extensions precisely:</strong> For example, <code>test.txt</code> ignores only that specific file, while <code>*.log</code> ignores all files ending with <code>.log</code>.</li>
<li><strong>Wildcards for broader matches:</strong> The asterisk (<code>*</code>) wildcard matches any number of characters. For example, <code>*.doc</code> ignores all files with the <code>.doc</code> extension, regardless of their name.</li>
</ul>
<h3 id="heading-5-how-to-view-changes-in-git">5. How to View Changes in Git:</h3>
<p>If you want to see the exact changes you've made to your files before committing, you can use the <code>git diff</code> command.</p>
<p>To see unstaged changes:</p>
<pre><code class="lang-bash">$ git diff
</code></pre>
<p>And to see staged changes:</p>
<pre><code class="lang-bash">$ git diff --cached README.md
</code></pre>
<p><code>git diff</code> provides a detailed view of the actual modifications. Use <code>git diff &lt;filename&gt;</code> to focus on changes within a particular file.</p>
<h3 id="heading-6-how-to-commit-changes">6. How to Commit Changes:</h3>
<p>When you are ready to commit your changes, use the <code>git commit</code> command. This opens your text editor for you to provide a commit message. Alternatively, you can use the <code>-m</code> flag to add a commit message directly:</p>
<p>Once you have staged the changes you want to include in the commit, you can commit them using <code>git commit</code></p>
<pre><code class="lang-bash">$ git commit -m <span class="hljs-string">"Your commit message here"</span>
</code></pre>
<h3 id="heading-7-how-to-remove-files-in-git">7. How to Remove Files in Git:</h3>
<p>If you need to remove a file from Git's tracking, you can use <code>git rm</code>. It remove the file from both the repository and working directory. Suppose you want to remove a file named <code>temp.txt</code>:</p>
<pre><code class="lang-bash">$ git rm temp.txt
</code></pre>
<p>If you only want to remove it from the repository but keep it in the working directory, use the <code>--cached</code> option:</p>
<pre><code class="lang-bash">$ git rm --cached temp.txt
</code></pre>
<h3 id="heading-8-how-to-move-or-rename-files-in-git">8. How to Move (or Rename) Files in Git:</h3>
<p>Git doesn't explicitly track file movements. But you can use <code>git mv</code> to rename or move files within your repository. For example, to rename <code>old_file.txt</code> to <code>new_file.txt</code>:</p>
<pre><code class="lang-bash">$ git mv old_file.txt new_file.txt
</code></pre>
<p>It is equivalent to manually moving the file, followed by using <code>git rm</code> to remove the old file, and then <code>git add</code> to add the new file. <code>git mv</code> basically consolidates these steps into a single command.</p>
<p>These commands form the basic workflow for making changes, staging them, and committing them to your Git repository.</p>
<h2 id="heading-how-to-view-commit-history-in-git">How to View Commit History in Git</h2>
<p>After creating multiple commits or cloning a repository, the <code>git log</code> command allows you to examine the commit history. </p>
<p>By default, it lists commits in reverse chronological order, displaying each commit with its SHA-1 checksum, author's name and email, date, and commit message.<br>Now let's see how can we enhance this output:</p>
<h3 id="heading-how-to-view-commit-differences-in-git">How to View Commit Differences in Git:</h3>
<p>To view the difference introduced in each commit, you can use the <code>-p</code> or <code>--patch</code> option:</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">log</span> -p -2    <span class="hljs-comment"># -2 is used to view the differences introduced in each of the last two commits</span>
</code></pre>
<h3 id="heading-how-to-display-statistics-in-git">How to Display Statistics in Git:</h3>
<p>The <code>--stat</code> option provides summarized statistics for each commit, including the modified files, lines added/deleted, and a summary.</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">log</span> --<span class="hljs-built_in">stat</span>
</code></pre>
<h3 id="heading-how-to-customize-git-log-output-format">How to Customize Git Log Output Format:</h3>
<p>The <code>--pretty</code> option allows you to alter the log output format. Various options are available for different formats:</p>
<ul>
<li><code>oneline</code>: Concise, single-line summary of each commit. </li>
<li><code>short</code>: Default format with author, date, and message. </li>
<li><code>full</code>: Detailed format with commit hash, author, date, message, and diff.</li>
<li><code>fuller</code>: More detailed format, including full file paths. </li>
<li><code>format</code>: Customize the output using format specifiers.</li>
</ul>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">log</span> --pretty=oneline
</code></pre>
<p><strong>Useful format specifiers for</strong> <code>--pretty=format</code>:</p>
<ul>
<li><code>%h:</code> Abbreviated commit hash</li>
<li><code>%an:</code> Author name</li>
<li><code>%ae:</code> Author email</li>
<li><code>%ad:</code> Author date</li>
<li><code>%s:</code> Subject (commit message)</li>
</ul>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">log</span> --pretty=format:<span class="hljs-string">"%h %an %ad %s"</span>
</code></pre>
<p><strong>ASCII Graph</strong>:</p>
<p>Using <code>--graph</code>, you can also visualize branch and merge history.</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">log</span> --pretty=format:<span class="hljs-string">"%h %s"</span> --graph
</code></pre>
<h3 id="heading-how-to-limit-git-log-output">How to Limit Git Log Output:</h3>
<p>In addition to formatting options, <code>git log</code> offers various limiting options to refine the displayed commit history.</p>
<ul>
<li><code>-&lt;n&gt;:</code> Shows only the last n commits.</li>
<li><code>--since, --until:</code> Limits commits to those made after/before the specified date.</li>
<li><code>--author:</code> Shows commits only by a specific author.</li>
<li><code>--grep:</code> Filters commits by a keyword in the commit messages.</li>
<li><code>-S:</code> Shows commits changing</li>
</ul>
<p><strong>Example Usage:</strong> View the last 3 commits by author Abbey since a certain date, with patch details:</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">log</span> --author=<span class="hljs-string">"Abbey"</span> --since=<span class="hljs-string">"2024-01-01"</span> -p -3
</code></pre>
<h2 id="heading-how-to-undo-things-in-git">How to Undo Things in Git</h2>
<p>Undoing changes is a common need in Git, and several options are available for this purpose.</p>
<h3 id="heading-how-to-undo-a-commit-in-git">How to Undo a Commit in Git</h3>
<p>If you've committed too early or need to make additional changes to the last commit, use this command:</p>
<pre><code class="lang-bash">$ git commit --amend
</code></pre>
<p>This opens the commit message editor allowing you to modify the message. If no changes were made since the last commit, it simply allows you to edit the commit message.</p>
<p><strong>Note</strong>: Only amend commits that are still local and haven't been pushed yet to avoid issues for collaborators.</p>
<h3 id="heading-how-to-unstage-a-staged-file-with-git-reset">How to Unstage a Staged File with <code>git reset</code></h3>
<p>To unstage a file that was accidentally included, you can use the <code>git reset HEAD &lt;file&gt;</code> command. For example:</p>
<pre><code class="lang-bash">$ git reset HEAD CONTRIBUTING.md
</code></pre>
<p>The file is unstaged, allowing you to make further changes without committing the unintended ones.</p>
<h3 id="heading-how-to-unmodify-a-modified-file-with-git-checkout">How to Unmodify a Modified File with <code>git checkout</code></h3>
<p>Suppose you made some modifications to files that you later realize you don't want to keep. Use <code>git checkout -- &lt;file&gt;</code> to discard the changes made to a file and revert it back to its previous state.</p>
<pre><code class="lang-bash">$ git checkout -- CONTRIBUTING.md
</code></pre>
<p>This will replace the modified file with the last staged or committed version. </p>
<h3 id="heading-undoing-things-with-git-restore">Undoing Things with <code>git restore</code></h3>
<p>Let's explore the alternatives introduced by Git version 2.23.0, <code>git restore</code>, which serves as an alternative to <code>git reset</code> for many undo operations.</p>
<h4 id="heading-how-to-unstage-a-staged-file-with-git-restore">How to unstage a staged file with <code>git restore</code></h4>
<p>If you accidentally stage a file that you didn't intend to commit, you can use <code>git restore --staged &lt;file&gt;</code> to unstage it.</p>
<pre><code class="lang-bash">$ git restore --staged CONTRIBUTING.md
</code></pre>
<p>The file is unstaged, similar to <code>git reset HEAD &lt;file&gt;</code>, allowing you to make further changes without committing the unintended ones.</p>
<h4 id="heading-how-to-unmodify-a-modified-file-with-git-restore">How to unmodify a modified file with <code>git restore</code></h4>
<p>To discard changes made to a file in the working directory, use <code>git restore &lt;file&gt;</code>:</p>
<pre><code class="lang-bash">$ git restore CONTRIBUTING.md
</code></pre>
<p>Similar to <code>git checkout -- &lt;file&gt;</code>, this command discard the changes made to the specified file, reverting it back to the state it was in at the last commit.</p>
<p><strong>Important Note:</strong> Use commands like <code>git reset</code>, <code>git checkout --</code>,<code>git restore</code> cautiously as they can discard local changes permanently. Use these commands when you're certain that the changes are not needed and you don't have any unsaved local changes. </p>
<p><strong>Alternatives:</strong> Stashing and branching are alternative methods to temporarily set aside changes without discarding them entirely. These methods are safer if you're unsure about discarding changes.</p>
<h2 id="heading-how-to-work-with-remotes-in-git">How to Work with Remotes in Git</h2>
<p>Remote repositories are versions of your project hosted on the internet or a network. Collaborating with others involves managing these remote repositories, including adding, removing, and inspecting them. Let's learn how to manage them effectively.</p>
<h3 id="heading-how-to-show-your-remotes-in-git">How to Show Your Remotes in Git</h3>
<p>To start, let's see which remote servers are configured for our project using:</p>
<pre><code class="lang-bash">$ git remote
</code></pre>
<p>This command lists the shortnames of all remote handles we've specified. For instance, if we've cloned a repository, we'll typically see <code>origin</code>, the default name Git assigns to the server we cloned from.</p>
<p>Adding the <code>-v</code> option provides additional details, such as the URLs associated with each remote.</p>
<pre><code class="lang-bash">$ git remote -v
</code></pre>
<p>This displays both the fetch and push URLs for each remote, allowing us to understand where our project is hosted and how we interact with it.</p>
<h3 id="heading-how-to-add-remote-repositories-in-git">How to Add Remote Repositories in Git</h3>
<p>To explicitly add a new remote repository, use <code>git remote add &lt;shortname&gt; &lt;url&gt;</code>:</p>
<pre><code class="lang-bash">$ git remote add example https://github.com/example/example.git
</code></pre>
<p>Here, we've added a remote named <code>example</code> with the specified URL. This allows us to reference this remote repository using the shortname <code>example</code> in our commands.</p>
<h3 id="heading-how-to-fetch-and-pull-from-remotes-in-git">How to Fetch and Pull from Remotes in Git</h3>
<p>To fetch data from a remote repository, we use the <code>git fetch</code> command followed by the remote name:</p>
<pre><code class="lang-bash">$ git fetch origin // Here we are not specifying any particular branch.
</code></pre>
<p>It downloads any new changes from the <code>origin</code> remote repository to our local repository, allowing us to stay up-to-date with the latest developments. </p>
<p>Alternatively, if we want to fetch and merge changes from a remote branch into our current branch in a single step, we use the <code>git pull</code> command:</p>
<pre><code class="lang-bash">$ git pull origin master
</code></pre>
<p>Here, we're specifically pulling changes from the <code>master</code> branch of the <code>origin</code> remote repository into our current branch.</p>
<h3 id="heading-how-to-push-changes-to-remotes-in-git">How to Push Changes to Remotes in Git</h3>
<p>To share our work with others, we push our changes to a remote repository using:</p>
<pre><code class="lang-bash">$ git push origin main
</code></pre>
<p>In this example, we're pushing our local changes to the <code>main</code> branch of the <code>origin</code> remote repository.</p>
<h3 id="heading-how-to-inspect-a-remote-in-git">How to Inspect a Remote in Git</h3>
<p>Lastly, we can inspect a remote repository to gather more information about it using:</p>
<pre><code class="lang-bash">$ git remote show origin
</code></pre>
<p>This command displays details such as the fetch and push URLs, the tracked branches, and local branch configurations associated with the <code>origin</code> remote repository.</p>
<h3 id="heading-how-to-rename-remotes-in-git">How to Rename Remotes in Git</h3>
<p>Now Suppose we want to rename a remote's shortname from <code>example</code> to <code>new-example</code>:</p>
<pre><code class="lang-bash">$ git remote rename example new-example
</code></pre>
<h3 id="heading-how-to-remove-remotes-in-git">How to Remove Remotes in Git</h3>
<p>If, for some reason, we no longer need a remote repository and want to remove it from our project:</p>
<pre><code class="lang-bash">$ git remote remove new-example
or
$ git remote rm new-example
</code></pre>
<p>After removal, the remote-tracking branches and associated configuration settings are also deleted.</p>
<h2 id="heading-tagging-in-git">Tagging in Git</h2>
<p>Tagging in Git is a fundamental feature allowing developers to mark specific points in a repository's history as significant. Typically, tags are used to denote release points, such as v1.0, v2.0, and so forth.</p>
<h3 id="heading-how-to-list-existing-tags-in-git">How to List Existing Tags in Git</h3>
<p>Imagine you're working on a project with multiple release versions. To list existing tags:</p>
<pre><code class="lang-bash">$ git tag
</code></pre>
<p>Also, you can search for tags matching a specific pattern using the <code>-l</code> or <code>--list</code> option. For Example:</p>
<pre><code class="lang-bash">$ git tag -l <span class="hljs-string">"v2.0*"</span>
</code></pre>
<p>This command will list tags like <code>v2.0</code>, <code>v2.0-beta</code>, and so on, matching the specified pattern.</p>
<h3 id="heading-how-to-create-tags-in-git">How to Create Tags in Git</h3>
<p>Git supports two types of tags: lightweight and annotated.</p>
<h4 id="heading-lightweight-tags">Lightweight Tags</h4>
<p>Use lightweight tags when you want to mark a specific commit without adding any additional information. Example:</p>
<pre><code class="lang-bash">$ git tag v1.1-lw
</code></pre>
<p>To view commit information associated with this tag, use:</p>
<pre><code class="lang-bash">$ git show v1.1-lw
</code></pre>
<h4 id="heading-annotated-tags">Annotated Tags</h4>
<p>Annotated tags, on the other hand, contain additional info such as tagger information, date, and a tagging message.</p>
<p>Creating an annotated tag involves using the <code>-a</code> option with the <code>git tag</code> command, along with a tagging message. e.g:</p>
<pre><code class="lang-bash">$ git tag -a v2.0 -m <span class="hljs-string">"Release version 2.0"</span>
</code></pre>
<p>To view detailed information about this tag, including the commit it points to and the tagging message, use:</p>
<pre><code class="lang-bash">$ git show v2.0
</code></pre>
<h3 id="heading-how-to-tag-an-older-commit-in-git">How to tag an older commit in Git</h3>
<p>Sometimes, you might forget to tag a specific commit. Not to worry, you can tag it later by specifying the commit checksum</p>
<p>Example: suppose you forgot to tag a commit with ID <code>abcdefg</code>. You can tag it as follows:</p>
<pre><code class="lang-bash">$ git tag -a v1.2 abcdefg
</code></pre>
<h4 id="heading-how-to-push-tag-to-a-remote-repo-in-git">How to Push Tag to a Remote repo in Git</h4>
<p>To push a specific tag to a remote server, you can use:</p>
<pre><code class="lang-bash">$ git push origin &lt;tagname&gt;
</code></pre>
<p>If you have multiple tags and want to push them all at once, you can use the <code>--tags</code> option:</p>
<pre><code class="lang-bash">$ git push origin --tags
</code></pre>
<h4 id="heading-how-to-delete-tags-in-git">How to Delete Tags in Git</h4>
<p>To delete a tag locally (removing from local repo):</p>
<pre><code class="lang-bash">$ git tag -d &lt;tagname&gt;
</code></pre>
<p>For Example, to delete a lightweight tag named <code>v1.4-lw</code>:</p>
<pre><code class="lang-bash">$ git tag -d v1.4-lw
</code></pre>
<p>On the other hand, you can delete a tag from a remote server in two ways:</p>
<ol>
<li>Using the <code>git push</code> command with a refspec:</li>
</ol>
<pre><code class="lang-bash">$ git push origin :refs/tags/v1.1-lw
</code></pre>
<ol start="2">
<li>Using the <code>--delete</code> option with <code>git push</code>:</li>
</ol>
<pre><code class="lang-bash">$ git push origin --delete v1.1-lw
</code></pre>
<h4 id="heading-how-to-check-out-tags-in-git">How to Check Out Tags in Git</h4>
<p>To view the state of files at a specific tag, you can check out that tag:</p>
<pre><code class="lang-bash">$ git checkout v2.0
</code></pre>
<p>This command puts your repository in a "detached HEAD" state, where you can view files but cannot make changes directly.</p>
<p>If you need to work on files at that tag, it's better to create a new branch:</p>
<pre><code class="lang-bash">$ git checkout -b v2.0-branch v2.0
</code></pre>
<p>Now you can make changes and commits without altering the original tag.</p>
<h2 id="heading-git-aliases">Git Aliases</h2>
<p>Git aliases are shortcuts or custom commands that you can create to simplify and streamline your Git workflow.  </p>
<p>To create a Git alias, you use the <code>git config</code> command with the <code>--global</code> flag to make the alias available across all your Git repositories. </p>
<h3 id="heading-basic-aliases-for-common-commands">Basic Aliases for Common Commands</h3>
<p>You can create aliases for frequently used Git commands to make them easier to remember and type. For example:</p>
<pre><code class="lang-bash">$ git config --global alias.co checkout
$ git config --global alias.br branch
$ git config --global alias.ci commit
</code></pre>
<p>Now, instead of typing out the full commands, you can use shorter aliases like <code>git co</code>, <code>git br</code>, and <code>git ci</code> respectively.</p>
<p>You can also <strong>create custom aliases for actions you frequently perform</strong> or for improving command readability. Example:</p>
<pre><code class="lang-bash">$ git config --global alias.unstage <span class="hljs-string">'reset HEAD --'</span>
</code></pre>
<p>Now, you can use <code>git unstage &lt;file&gt;</code> instead of <code>git reset HEAD -- &lt;file&gt;</code> to unstage a file.</p>
<h4 id="heading-how-to-combine-multiple-commands-in-git">How to Combine Multiple Commands in Git</h4>
<p>Aliases can also be used to combine multiple Git commands into a single alias. For example, let's create an alias to stage all changes and then commit them with a single command:</p>
<pre><code class="lang-bash">$ git config --global alias.commitall <span class="hljs-string">'!git add -A &amp;&amp; git commit'</span>
</code></pre>
<p>Now, running <code>git commitall</code> will stage all changes (<code>git add -A</code>) and then commit them, saving you time and keystrokes.</p>
<h2 id="heading-git-branching">Git Branching</h2>
<p>Branches in Git provide a powerful way to manage your project's codebase, allowing for parallel development and experimentation without affecting the main codebase.</p>
<p>Git branching allows you to diverge from the main line of development, work on features or fixes, and then merge your changes back. Unlike many other version control systems, Git's branching model is lightweight and efficient, making branching operations nearly instantaneous.</p>
<h3 id="heading-what-are-branches-in-git">What are Branches in Git?</h3>
<p>A branch is a lightweight, movable pointer to a commit. The default branch name is often "master," but it's not special – it's like any other branch.</p>
<p>Creating and switching between branches allows you to work on different features simultaneously.</p>
<h3 id="heading-how-to-create-a-new-branch-in-git">How to Create a New Branch in Git:</h3>
<p>When you want to start working on a new feature or experiment with an idea, you can create a new branch in Git. This new branch serves as a separate line of development, allowing you to make changes without affecting the main branch.</p>
<pre><code class="lang-bash">$ git branch new_feature
</code></pre>
<p>This command creates a new branch named 'new-feature' pointing to the same commit as the current branch. Branches can coexist, and Git keeps a special pointer called <code>HEAD</code> to indicate the current branch.</p>
<h3 id="heading-understanding-branches">Understanding Branches</h3>
<p>Firstly, let's grasp the basics of branches in Git. When you initialize a Git repository, you start with a default branch, usually named 'master' or 'main'. Branches are essentially pointers to commits, enabling you to work on different features or fixes independently. </p>
<p>To view all branches in your repository, use the command:</p>
<pre><code class="lang-bash">$ git branch
</code></pre>
<p>This will display a list of branches with an asterisk (*) indicating the currently checked out branch. For additional information like the last commit on each branch, utilize:</p>
<pre><code class="lang-bash">$ git branch -v
</code></pre>
<h3 id="heading-how-to-switch-to-another-branch-in-git">How to Switch to Another Branch in Git:</h3>
<p>To switch to an existing different branch, use <code>git checkout</code>. </p>
<pre><code class="lang-bash">$ git checkout new_feature
</code></pre>
<p>This command switches the 'HEAD' pointer to the 'new-feature' branch, making it the currently active branch.</p>
<p>To create and switch to a new branch in one operation:</p>
<pre><code class="lang-bash">$ git checkout -b &lt;newbranchname&gt;
</code></pre>
<p>In Git version 2.23 onwards, you can use <code>git switch</code> instead of <code>git checkout</code>.</p>
<ul>
<li>Switch to an existing branch: <code>git switch existing-branch</code>.</li>
<li>Create and switch to new branch: <code>git switch -c new-branch</code>.</li>
</ul>
<h3 id="heading-how-to-visualize-branches-in-git">How to Visualize Branches in Git:</h3>
<p>After creating and switching branches, you can visualize the branch structure using:</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">log</span> --oneline --decorate --graph --all
</code></pre>
<p>This command displays a concise and graphical representation of the commit history and branch pointers, allowing you to see how branches diverge and merge over time.</p>
<h2 id="heading-how-to-manage-branches-in-git">How to Manage Branches in Git</h2>
<h3 id="heading-how-to-manage-merged-branches">How to Manage Merged Branches</h3>
<p>As your project evolves, you'll merge branches back into the main branch once their changes are finalized. To identify merged branches, execute:</p>
<pre><code class="lang-bash">$ git branch --merged
</code></pre>
<p>This command lists branches that have been successfully merged into the current branch. These branches are generally safe to delete using:</p>
<pre><code class="lang-bash">$ git branch -d branch_name
</code></pre>
<p>However, for branches containing unmerged work, use:</p>
<pre><code class="lang-bash">$ git branch --no-merged
</code></pre>
<p>Deleting such branches requires the '-D' flag:</p>
<pre><code class="lang-bash">$ git branch -D branch_name
</code></pre>
<p>This ensures that you don't inadvertently lose any unmerged changes.</p>
<h3 id="heading-how-to-rename-branches">How to Rename Branches</h3>
<p>To rename a local branch:</p>
<pre><code class="lang-bash">$ git branch --move old_branch_name new_branch_name
</code></pre>
<p>This command updates the branch name locally. To reflect the change on the remote repository, push the renamed branch:</p>
<pre><code class="lang-bash">$ git push --set-upstream origin new_branch_name
</code></pre>
<p>Verify the changes using: </p>
<pre><code class="lang-bash">$ git branch --all
</code></pre>
<p>Ensure to delete the old branch on the remote:</p>
<pre><code class="lang-bash">$ git push origin --delete old_branch_name
</code></pre>
<p>This ensures uniformity across local and remote repositories.</p>
<h3 id="heading-how-to-change-the-default-branch-name">How to Change the Default Branch Name</h3>
<p>Renaming the default branch, often 'master', requires caution and coordination, as it impacts project integrations and collaborators.</p>
<pre><code class="lang-bash">$ git branch --move master main
</code></pre>
<p>Once renamed, push the updated branch to the remote repo:</p>
<pre><code class="lang-bash">$ git push --set-upstream origin main
</code></pre>
<p>Make sure you remember to update references and configurations across dependencies, tests, scripts, and repository hosts. Once done, delete the old master branch on the remote:</p>
<pre><code class="lang-bash">$ git push origin --delete master
</code></pre>
<p>This is <strong>different from <code>$ git config --global init.defaultBranch main</code></strong> that we discussed in the configuration part in the following ways:</p>
<ul>
<li><code>$ git branch --move master main</code>: This command renames the existing branch named "master" to "main" within the current repository. It is a sort of local operation that affects only the repository.</li>
<li><code>$ git config --global init.defaultBranch main</code>: This command sets the default branch name for new repositories globally. It does not rename existing branches but ensures that any new repositories created thereafter will use "main" as the default branch name instead of "master".</li>
</ul>
<p><strong>Additional Resource</strong>: Consider checking out this official Git <a target="_blank" href="https://git-scm.com/book/en/v2/Git-Branching-Remote-Branches">resource</a> for its informative visuals and diagrams which can provide you more clarity on remote branches and branch management concepts.</p>
<h2 id="heading-branching-workflow">Branching Workflow</h2>
<p>Let's understand branches in more detail and look at a common branching workflow that is used in large projects.</p>
<h3 id="heading-long-running-branches">Long-Running Branches:</h3>
<p>In Git, long-running branches are branches that remain open over an extended period. </p>
<h3 id="heading-topic-branches">Topic Branches:</h3>
<p><code>Topic</code>/<code>Feature</code> branches are short-lived branches created for specific features or pieces of work. Unlike long-running branches, which persist over time, topic branches are created, used, and often deleted once the work is complete. </p>
<p><strong>Example:</strong> Let's consider a scenario where a team maintains two long-running branches: <code>master</code> and <code>develop</code>.</p>
<ul>
<li>The <code>master</code> branch contains only stable code, possibly what has been released or will be released.</li>
<li>The <code>develop</code> branch acts as a staging area for ongoing development. While it might not always be stable, it serves as a testing ground for new features.</li>
</ul>
<p>Developers merge changes from feature branches into the <code>develop</code> branch for testing. Once features are thoroughly tested and stable, they are merged into <code>master</code>.</p>
<p>Note how changes progress through different levels of stability, moving from the least stable (feature branches) to more stable ones (such as the develop branch), as they undergo testing and refinement, and are finally merged into the most stable main/master branch. </p>
<p>This maintains a clear separation between stable and development code, ensuring that only thoroughly tested features make their way into the stable release.</p>
<h3 id="heading-branching-best-practices">Branching Best Practices</h3>
<ol>
<li><strong>Create Descriptive Branch Names</strong>: Use meaningful branch names that reflect the purpose or feature being developed.</li>
<li><strong>Delete Unused Branches</strong>: Once a branch has served its purpose and its changes have been merged into the main branch, consider deleting it to keep the repository clean and manageable.</li>
</ol>
<h2 id="heading-rebasing-in-git">Rebasing in Git</h2>
<p>In Git, when you're working with branches, there are two primary ways to integrate changes from one branch into another: merging and rebasing. </p>
<p>Unlike merging, which can create a cluttered history with multiple merge commits, rebasing produces a linear history, making it easier to understand the sequence of changes made over time. </p>
<h3 id="heading-basic-rebase-example">Basic Rebase Example:</h3>
<p>Imagine you're working on a project with two branches: "feature" and "master". You've made some commits on the "feature" branch and now want to integrate these changes into the "master" branch using rebasing.</p>
<p>First, you switch to your "feature" branch:</p>
<pre><code class="lang-bash">$ git checkout feature
</code></pre>
<p>Then, you rebase your feature branch onto the master branch: </p>
<pre><code class="lang-bash">$ git rebase master
</code></pre>
<p>This command takes all the commits/changes you made on your "feature" branch and applies them on top of the latest commits in the "master" branch, and replays the commits one by one.</p>
<p>Not only master branch, you can also rebase a topic branch onto another topic branch. Example:</p>
<p>Suppose you're working on a project with two feature branches: "frontend" and "backend". You made some commits on the "frontend" branch and now want to integrate these changes into the "backend" branch.</p>
<p>Let's use a different approach this time -<br>use <code>--onto</code> option of <code>git rebase</code> to rebase the "frontend" branch onto the "backend" branch:</p>
<pre><code class="lang-bash">$ git rebase --onto backend frontend
</code></pre>
<p>After rebasing, switch back to the "backend" branch and perform a fast-forward merge:</p>
<pre><code class="lang-bash">$ git checkout backend
$ git merge frontend
</code></pre>
<p>Now, your project history appears linear, reflecting the sequential integration of changes from the "frontend" branch into the "backend" branch.</p>
<h3 id="heading-rebasing-vs-merging-which-is-better">Rebasing vs Merging: Which is Better?</h3>
<h4 id="heading-rebasing-use-cases">Rebasing Use Cases:</h4>
<ul>
<li>Suitable for feature branches that need a clean integration into the mainline branch.</li>
<li>Preferred for open-source contributions where a clean commit history is valued.</li>
</ul>
<h4 id="heading-merging-use-cases">Merging Use Cases:</h4>
<ul>
<li>Appropriate for collaborative environments where transparency in the project's development process is crucial.</li>
<li>Useful for projects where maintaining an accurate historical record is a priority.</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This handbook serves as a comprehensive guide to understanding and utilizing Git, a powerful version control system widely used in software development. </p>
<p>From basic workflows to setting up a repository, tagging, and branching remote repositories, we have learnt a comprehensive suite of features that will help streamlining the development process.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Client-Side Form Handling with JavaScript – Explained with Example Code ]]>
                </title>
                <description>
                    <![CDATA[ HTML forms are essential components of most websites and web apps. They enable interaction between users and those websites, and are a key concept for web developers to understand.  This comprehensive guide covers various aspects of HTML forms, from ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/form-validation-in-javascript/</link>
                <guid isPermaLink="false">66c72185783c8978e5e7647a</guid>
                
                    <category>
                        <![CDATA[ Form validations ]]>
                    </category>
                
                    <category>
                        <![CDATA[ forms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Samyak Jain ]]>
                </dc:creator>
                <pubDate>Fri, 08 Mar 2024 21:10:35 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/07/form-handling-in-javascript.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>HTML forms are essential components of most websites and web apps. They enable interaction between users and those websites, and are a key concept for web developers to understand. </p>
<p>This comprehensive guide covers various aspects of HTML forms, from how to create and structure forms to JavaScript interaction and form validation. </p>
<p>Understanding how to work with forms programmatically allows you to validate and capture user input, handle submissions, and enhance the overall user experience. </p>
<p>By following the examples and best practices provided in this guide, you'll be equipped with the knowledge necessary to build robust web forms that enhance user experience and facilitate seamless data collection and submission. </p>
<p>Whether you're a beginner or an experienced developer, this guide serves as a valuable resource for understanding and implementing HTML forms effectively in your web projects. </p>
<h3 id="heading-prerequisites"><strong>Prerequisites:</strong></h3>
<p>A basic understanding of JavaScript fundamentals is recommended to fully comprehend the concepts discussed in this tutorial. Familiarity with HTML forms will also be beneficial for understanding and applying the material covered.</p>
<p>If you're new to JavaScript, it's recommended to acquaint yourself with variables, data types, functions, loops, and basic DOM manipulation techniques before diving into this tutorial. This foundational knowledge will facilitate a smoother learning experience as we explore more advanced topics related to form handling in JavaScript.</p>
<p>Starting Note: For your convenience, all the examples and code discussed here can be accessed on <a target="_blank" href="https://github.com/theSamyak/FCC-Blog-CodeArchive/tree/main/Client-Side%20Form%20Handling%20with%20JavaScript">GitHub</a>.</p>
<h2 id="heading-table-of-contents"><strong>Table of Contents</strong></h2>
<ol>
<li><a class="post-section-overview" href="#heading-understanding-html-forms">Understanding HTML Forms</a><br>– <a class="post-section-overview" href="#heading-introduction-to-html-form-elements">Introduction to HTML form elements</a><br>– <a class="post-section-overview" href="#heading-javascript-and-form-handling">JavaScript and Form Handling</a><br>– <a class="post-section-overview" href="#accessing-form-fields">Accessing Form Fields</a><br>– <a class="post-section-overview" href="#heading-lets-see-an-example-registration-form">Example: Registration Form</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-radio-buttons">How to Create Radio Buttons</a><br>– <a class="post-section-overview" href="#javascript-to-handle-radio-button-selection">JavaScript to Handle Radio Button Selection</a><br>– <a class="post-section-overview" href="#heading-radio-button-change-event">Radio Button Change Event</a></li>
<li><a class="post-section-overview" href="#heading-checkboxes">Checkboxes</a><br>– <a class="post-section-overview" href="#heading-how-to-check-if-a-checkbox-is-checked">How to Check if a Checkbox is Checked</a><br>– <a class="post-section-overview" href="#heading-how-to-get-checkbox-values">How to Get Checkbox Values</a><br>– <a class="post-section-overview" href="#heading-how-to-handle-multiple-checkboxes">How to Handle Multiple Checkboxes</a><br>– <a class="post-section-overview" href="#heading-how-to-check-uncheck-all-checkboxes">How to Check / Uncheck All Checkboxes</a><br>– <a class="post-section-overview" href="#heading-how-to-dynamically-generate-checkboxes">How to Dynamically Generate CheckBoxes</a></li>
<li><a class="post-section-overview" href="#select-element">Select Element</a><br>– <a class="post-section-overview" href="#how-to-interact-with-a-select-element">How to Interact with a Select Element</a><br>– <a class="post-section-overview" href="#heading-how-to-access-options-with-javascript">How to Access Options with JavaScript</a><br>– <a class="post-section-overview" href="#how-to-handle-multiple-selections">How to Handle Multiple Selections</a><br>– <a class="post-section-overview" href="#lets-see-an-example-task-manager-adding-and-removing-tasks">Example: Task Manager</a></li>
<li><a class="post-section-overview" href="#heading-difference-between-change-and-input-event">Difference Between Change and Input Event</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<p>Before we start, here's something to note:</p>
<p>This is a follow up blog on this <a target="_blank" href="https://www.freecodecamp.org/news/javascript-in-the-browser-dom-and-events/">DOM and Events Handbook</a> and not cover server-side communication/server-side form handling in this blog as it involves advanced topics such as AJAX (Asynchronous JavaScript and XML), Promises, error handling, and handling asynchronous operations in JavaScript.</p>
<p>In this tutorial, we'll instead focuses on how to work with various form elements including radio buttons, checkboxes, and select elements, as well as dynamically generating and interacting with them using JavaScript. </p>
<p>Delving into server-side communication would extend beyond the scope of this article, which aims to provide a comprehensive understanding of DOM manipulation and event handling within the context of form elements.</p>
<h2 id="heading-understanding-html-forms">Understanding HTML Forms</h2>
<p>HTML forms are fundamental elements used for collecting and submitting user data on the web. They enable interaction between users and websites by allowing users to input information, make selections, and submit data to servers for processing.</p>
<h4 id="heading-introduction-to-html-form-elements">Introduction to HTML Form Elements</h4>
<p>HTML forms are created using the <code>&lt;form&gt;</code> element, which acts as a container for various input elements. Common form elements include text fields, checkboxes, radio buttons, dropdown menus, and buttons.</p>
<p>To reference a form in JS, you can use DOM methods like <code>getElementById()</code> or <code>document.forms</code>. <code>document.forms</code> returns a collection of forms, and you can access a specific form using an index, name, or id.    </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> form = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'signup'</span>);
<span class="hljs-keyword">const</span> firstForm = <span class="hljs-built_in">document</span>.forms[<span class="hljs-number">0</span>]; <span class="hljs-comment">// accessing first form</span>
<span class="hljs-keyword">const</span> formByName = <span class="hljs-built_in">document</span>.forms[<span class="hljs-string">'formName'</span>]; <span class="hljs-comment">// accessing form by name</span>
<span class="hljs-keyword">const</span> formById = <span class="hljs-built_in">document</span>.forms[<span class="hljs-string">'formId'</span>]; <span class="hljs-comment">// accessing form by id</span>
</code></pre>
<p>Let's see a basic example of an HTML form:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"username"</span>&gt;</span>Username:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"password"</span>&gt;</span>Password:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Submit"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<p>In this example, we have a form with two input fields for username and password, along with a submit button.</p>
<h3 id="heading-form-structure-and-attributes">Form Structure and Attributes</h3>
<p>HTML forms can have various attributes that control their behavior and appearance. Some common attributes include:</p>
<ul>
<li><strong>action:</strong> Specifies the URL where the form data should be submitted.</li>
<li><strong>method:</strong> Specifies the HTTP method used to send form data (<code>post</code> or <code>get</code>).</li>
<li><strong>target</strong>: Specifies where to display the response after form submission (for example, <code>_self</code>, <code>_blank</code>, <code>_parent</code>, <code>_top</code>).</li>
<li><strong>name</strong>: Assigns a name to the form for identification purposes.</li>
</ul>
<p>Here's an example of a form with action, method, and target attributes:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"/submit-form"</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"POST"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"myForm"</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>&gt;</span>
  <span class="hljs-comment">&lt;!-- Form elements go here --&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<h3 id="heading-javascript-and-form-handling">JavaScript and Form Handling</h3>
<p>JavaScript uses the <code>HTMLFormElement</code> object to represent a form. This object has properties corresponding to the HTML attributes <code>action</code> and <code>method</code>.</p>
<p>Methods like <code>submit()</code> and <code>reset()</code> are used for submitting and resetting forms.</p>
<pre><code class="lang-html">const form = document.getElementById('signup');
form.action; // returns the action attribute
form.method; // returns the method attribute
form.submit(); // submits the form
</code></pre>
<p>JavaScript provides Event Handlers to add interactivity to HTML forms. By leveraging these events, you can execute custom scripts in response to user actions within the form:</p>
<p><strong>Submit Event</strong>: A form typically has a submit button, which when clicked, sends the form data to the server. This is achieved using an <code>&lt;input&gt;</code> or <code>&lt;button&gt;</code> element with <code>type="submit"</code>.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Sign Up"</span>&gt;</span>
// or
<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Sign Up<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>To attach an event listener to the submit event, you use the <code>addEventListener()</code> method. Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> form = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'signup'</span>);
form.addEventListener(<span class="hljs-string">'submit'</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    <span class="hljs-comment">// Custom validation and submission logic here</span>
});
</code></pre>
<p>In many cases, you may want to intercept the default form submission behavior and execute custom logic before allowing the form to be submitted to the server. You can use <code>preventDefault()</code> for this. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> form = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'signup'</span>);
form.addEventListener(<span class="hljs-string">'submit'</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    event.preventDefault(); <span class="hljs-comment">// Prevents the default form submission</span>
    <span class="hljs-comment">// Custom validation and submission logic here</span>
});
</code></pre>
<p>Without <code>event.preventDefault()</code>, any custom validation and submission logic would still execute within the event listener, but the default form submission behavior would not be prevented.</p>
<p><strong>Reset Event</strong>: The <code>reset</code> event is triggered when the form is reset using a reset button or programmatically. We use <code>reset()</code> method to clear all form fields and reset them to their default values.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'form'</span>).addEventListener(<span class="hljs-string">'reset'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>{
    <span class="hljs-comment">// Custom form reset logic here</span>
});
</code></pre>
<h3 id="heading-how-to-access-form-fields">How to Access Form Fields</h3>
<p>You can access form fields using DOM methods like <code>getElementsByName()</code>, <code>getElementById()</code>, <code>querySelector()</code>, and so on</p>
<p>The <code>form.elements</code> property stores a collection of form elements. You can access these Elements by index, id, or name. Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> form = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'signup'</span>);
<span class="hljs-keyword">const</span> nameField = form.elements[<span class="hljs-string">'name'</span>]; <span class="hljs-comment">// accessing element by name</span>
<span class="hljs-keyword">const</span> emailField = form.elements[<span class="hljs-string">'email'</span>]; <span class="hljs-comment">// accessing element by name</span>
<span class="hljs-keyword">const</span> firstElement = form.elements[<span class="hljs-number">0</span>]; <span class="hljs-comment">// accessing first element by index no.</span>
</code></pre>
<p>Once you've accessed a form field, you can use the <code>value</code> property to access its value. Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> nameValue = nameField.value;
<span class="hljs-keyword">const</span> emailValue = emailFieldByName.value;
</code></pre>
<h3 id="heading-form-validation">Form Validation</h3>
<p>Form validation is an essential aspect of web development that ensures the data submitted by users is accurate and meets specified criteria before being processed by the server. Common validations include checking for empty fields, valid email formats, and so on.</p>
<h4 id="heading-html-form-validation">HTML Form Validation</h4>
<p>HTML5 provides built-in form validation through various attributes:</p>
<ul>
<li><strong>required</strong>: Specifies that a field must be filled out.</li>
<li><strong>pattern</strong>: Specifies a regular expression pattern that the input value must match.</li>
<li><strong>min</strong> and <strong>max</strong>: Specify the minimum and maximum values for an input field.</li>
<li><strong>maxlength</strong> and <strong>minlength</strong>: Specify the maximum and minimum length of the input</li>
<li><strong>type</strong>: Specifies the type of input expected (for example, email, number, date).</li>
</ul>
<p>Here's an example of HTML form validation using these attributes:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"username"</span>&gt;</span>Username:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">required</span> <span class="hljs-attr">minlength</span>=<span class="hljs-string">"3"</span> <span class="hljs-attr">maxlength</span>=<span class="hljs-string">"15"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"email"</span>&gt;</span>Email:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">required</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"age"</span>&gt;</span>Age:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"number"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"age"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"age"</span> <span class="hljs-attr">min</span>=<span class="hljs-string">"18"</span> <span class="hljs-attr">max</span>=<span class="hljs-string">"99"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Submit"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<h4 id="heading-javascript-form-validation">JavaScript Form Validation</h4>
<p>JavaScript allows developers to perform more sophisticated validation logic beyond what HTML attributes offer. Event listeners can be attached to form elements to handle validation dynamically. </p>
<p>Here's a basic example of JavaScript form validation:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> form = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'form'</span>);

form.addEventListener(<span class="hljs-string">'submit'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>{
    event.preventDefault(); <span class="hljs-comment">// Prevent form submission</span>

    <span class="hljs-comment">// Perform custom validation logic</span>
    <span class="hljs-keyword">const</span> email = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'email'</span>).value;
    <span class="hljs-keyword">const</span> password = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'password'</span>).value;

    <span class="hljs-keyword">if</span> (!emailIsValid(email)) {
        alert(<span class="hljs-string">'Please enter a valid email address.'</span>);
        <span class="hljs-keyword">return</span>;
    }

    <span class="hljs-keyword">if</span> (password.length &lt; <span class="hljs-number">6</span>) {
        alert(<span class="hljs-string">'Password must be at least 6 characters long.'</span>);
        <span class="hljs-keyword">return</span>;
    }

    <span class="hljs-comment">// If validation passes, submit the form</span>
    form.submit();
});

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">emailIsValid</span>(<span class="hljs-params">email</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-regexp">/^[^\s@]+@[^\s@]+\.[^\s@]+$/</span>.test(email);
}
</code></pre>
<p>In this example, the JavaScript function <code>emailIsValid()</code> uses a regular expression to validate the email format. The <code>submit</code> event listener prevents the form from being submitted if the validation fails, and custom error messages are displayed to the user.</p>
<h3 id="heading-lets-see-an-example-registration-form">Let's See an Example: Registration Form</h3>
<p>Now, let's combine all the concepts we've covered into a complete example of a Registration form with client-side validation using JavaScript:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>User Registration<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"registrationForm"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"username"</span>&gt;</span>Username:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"email"</span>&gt;</span>Email:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"password"</span>&gt;</span>Password:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Register"</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"errorMessages"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p><strong>HTML Structure</strong>: We have a simple registration form with fields for username, email, password, and a submit button. There's also a container div (<code>errorMessages</code>) to display validation error messages.</p>
<p>Now let's write JavaScript code to handle form submission and perform client-side validation:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> registrationForm = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"registrationForm"</span>);
<span class="hljs-keyword">const</span> errorMessages = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"errorMessages"</span>);

registrationForm.addEventListener(<span class="hljs-string">"submit"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">event</span>) </span>{
  event.preventDefault();

  <span class="hljs-keyword">const</span> { username, email, password } = registrationForm.elements;

  errorMessages.innerHTML = <span class="hljs-string">""</span>;

  <span class="hljs-keyword">if</span> (!username.value.trim()) {
    displayError(<span class="hljs-string">"Username is required."</span>);
    <span class="hljs-keyword">return</span>;
  }

  <span class="hljs-keyword">if</span> (!email.value.trim() || !isValidEmail(email.value)) {
    displayError(<span class="hljs-string">"Please enter a valid email address."</span>);
    <span class="hljs-keyword">return</span>;
  }

  <span class="hljs-keyword">if</span> (!password.value.trim() || !isStrongPassword(password.value)) {
    displayError(
      <span class="hljs-string">"Password must be at least 8 characters long and contain at least one uppercase letter, one lowercase letter, one digit, and one special character."</span>
    );
    <span class="hljs-keyword">return</span>;
  }

  alert(<span class="hljs-string">"Registration successful!"</span>);
  registrationForm.reset();
});

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayError</span>(<span class="hljs-params">message</span>) </span>{
  errorMessages.innerHTML += <span class="hljs-string">`&lt;div class="error"&gt;<span class="hljs-subst">${message}</span>&lt;/div&gt;`</span>;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isValidEmail</span>(<span class="hljs-params">email</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-regexp">/^[^\s@]+@[^\s@]+\.[^\s@]+$/</span>.test(email);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isStrongPassword</span>(<span class="hljs-params">password</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-regexp">/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&amp;*]).{8,}$/</span>.test(password);
}
</code></pre>
<p><strong>JavaScript Handling</strong>: We select the form and the error message container using <code>getElementById</code>. We attach an event listener to the form's submit event. When the form is submitted, we prevent its default behavior using <code>event.preventDefault()</code> to handle form submission manually.</p>
<p><strong>Form Validation</strong>: We retrieve the values of username, email, and password.</p>
<p>We perform basic validation: Username must not be empty, Email must be in a valid format, Password must be at least 8 characters long and contain at least one uppercase letter, one lowercase letter, one digit, and one special character.</p>
<p><strong>Error Handling</strong>: If any validation fails, we display the corresponding error message. Error messages are displayed in the <code>errorMessages</code> div.</p>
<p><strong>Form Reset</strong>: Upon successful registration (in this case, a simple alert), we reset the form using <code>registrationForm.reset()</code></p>
<p>Currently, the code uses an <code>alert</code> to indicate successful registration. In a real scenario, you might want to implement an AJAX call to submit the data to a server for processing and handle the response accordingly But that's not what we're going to discuss, as mentioned at the start of this tutorial.</p>
<p>Overall this example covers form creation, form handling with JavaScript, form validation using regular expressions, and dynamic custom error message display, demonstrating a basic user registration form with client-side validation.</p>
<h2 id="heading-radio-buttons">Radio Buttons</h2>
<p>Radio buttons are a common form element used to select one option from a set of options. In JavaScript, you can manipulate radio buttons to retrieve user selections and perform actions based on those selections.</p>
<h3 id="heading-how-to-create-radio-buttons">How to Create Radio Buttons</h3>
<p>You can use radio buttons you want users to select only one option from a set of choices. In HTML, you can create radio buttons using the <code>&lt;input&gt;</code> element with the <code>type</code> attribute set to "radio". A group of radio buttons with the same <code>name</code> attribute forms a radio group. </p>
<p>Here's an example:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"languageForm"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Select your favorite programming language:<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"radio"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"language"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"JavaScript"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"js"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"js"</span>&gt;</span>JavaScript<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"radio"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"language"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Python"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"python"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"python"</span>&gt;</span>Python<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"radio"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"language"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Java"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"java"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"java"</span>&gt;</span>Java<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-comment">&lt;!-- More language options can be added here --&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>You use the <code>id</code> and <code>for</code> attributes for accessibility, linking the label to the corresponding radio button.</p>
<h3 id="heading-how-to-retreive-the-selected-radio-button-value">How to Retreive the Selected Radio Button Value</h3>
<p>Now, let's discuss how to retrieve the value of the selected radio button using JavaScript.</p>
<pre><code class="lang-html">    <span class="hljs-comment">&lt;!-- HTML --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btn"</span>&gt;</span>Show Selected Language<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"output"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
      <span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#btn"</span>);
      <span class="hljs-keyword">const</span> radioButtons = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'input[name="language"]'</span>);
      <span class="hljs-keyword">const</span> output = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"output"</span>);

      btn.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">let</span> selectedLanguage;
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> radioButton <span class="hljs-keyword">of</span> radioButtons) {
          <span class="hljs-keyword">if</span> (radioButton.checked) {
            selectedLanguage = radioButton.value;
            <span class="hljs-keyword">break</span>;
          }
        }
        <span class="hljs-comment">// Displaying the output:</span>
        output.innerText = selectedLanguage
          ? <span class="hljs-string">`You selected <span class="hljs-subst">${selectedLanguage}</span>`</span>
          : <span class="hljs-string">`You haven't selected any language`</span>;
      });
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>Here's how this the code works: the JavaScript code initializes by selecting the button, radio buttons, and output elements from the HTML document. We add a click event listener to the button element. When the button is clicked, the function inside the event listener is executed.</p>
<p>Inside the click event listener, we iterate over all radio buttons in the <code>radioButtons</code> collection. We check if a radio button is checked using its <code>checked</code> property. If a radio button is checked, we assign its value to the <code>selectedLanguage</code> variable and exit the loop using <code>break</code>.</p>
<p>We update the content of the output element (<code>&lt;p&gt;</code> tag with id <code>output</code>) based on whether a language is selected. If a language is selected (<code>selectedLanguage</code> is truthy), we display a message indicating the selected language. Otherwise, we prompt the user to select a language.</p>
<h3 id="heading-radio-button-change-event">Radio Button Change Event</h3>
<p>When a radio button is checked or unchecked, it fires a <code>change</code> event. You can listen to this event using <code>addEventListener()</code>. Inside the event handler, you can access the checked state and value of the radio button using <code>this.checked</code> and <code>this.value</code>.</p>
<pre><code class="lang-javascript">radioButton.addEventListener(<span class="hljs-string">'change'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{
  <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.checked) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.value);
  }
});
</code></pre>
<h3 id="heading-how-to-dynamically-generate-radio-buttons">How to Dynamically Generate Radio Buttons</h3>
<p>Now, let's explore how to dynamically generate radio buttons using JavaScript. This is useful when you want to create radio button options dynamically based on certain criteria or data.</p>
<p>Suppose we have an array of languages, and we want to dynamically generate radio buttons for each language option:</p>
<pre><code class="lang-javascript">&lt;!DOCTYPE html&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"languages"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
      <span class="hljs-keyword">const</span> languageOptions = [<span class="hljs-string">"Python"</span>, <span class="hljs-string">"Javascript"</span>, <span class="hljs-string">"C++"</span>, <span class="hljs-string">"Java"</span>];

      <span class="hljs-comment">// Generate the radio buttons</span>
      <span class="hljs-keyword">const</span> languages = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#languages"</span>);
      languages.innerHTML = languageOptions.map(<span class="hljs-function">(<span class="hljs-params">language</span>) =&gt;</span> <span class="hljs-string">`
          &lt;div&gt;
              &lt;input type="radio" name="language" value="<span class="hljs-subst">${language}</span>" id="<span class="hljs-subst">${language}</span>"&gt;
              &lt;label for="<span class="hljs-subst">${language}</span>"&gt;<span class="hljs-subst">${language}</span>&lt;/label&gt;
          &lt;/div&gt;`</span>).join(<span class="hljs-string">' '</span>);
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span></span>
</code></pre>
<p>It dynamically generates radio buttons based on the <code>languageOptions</code> array and inserts them into the container element (<code>&lt;div id="languages"&gt;&lt;/div&gt;</code>). Each radio button has a unique ID and value corresponding to the language name, and the labels are associated with their respective radio buttons using the <code>for</code> attribute.</p>
<p>After dynamically generating the radio buttons, Now let's add <code>change</code> event listeners to them to handle changes in selection.</p>
<pre><code class="lang-javascript">    &lt;!-- HTML --&gt;
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"languages"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"languageOutput"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span> <span class="hljs-comment">// we create this one to fetch our selected language output</span>

    &lt;!-- Generate the radio buttons --&gt;

<span class="hljs-comment">// Attaching Change Event Listeners</span>
<span class="hljs-keyword">const</span> radioButtons = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'input[name="language"]'</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> radioButton <span class="hljs-keyword">of</span> radioButtons) {
    radioButton.addEventListener(<span class="hljs-string">'change'</span>, showSelectedlanguage);
}        

<span class="hljs-comment">// Handling the Change Event</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">showSelectedlanguage</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.checked) {
        <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#languageOutput'</span>).innerText = <span class="hljs-string">`You selected <span class="hljs-subst">${<span class="hljs-built_in">this</span>.value}</span>`</span>;
    }
}
</code></pre>
<p>Here's what's happening:</p>
<ul>
<li>We select all radio buttons with the <code>name</code> attribute set to <code>"language"</code>.</li>
<li>We use a <code>for...of</code> loop to iterate over each radio button and add a <code>change</code> event listener to each radio button. This listener listens for changes in the state of the radio buttons, i.e., when a radio button is selected or deselected.</li>
<li>We define a function named <code>showSelectedLanguage</code> to handle the change event triggered by selecting a radio button. </li>
<li>Inside the <code>showSelectedLanguage</code> function, we first check if the current radio button (<code>this</code>) is checked using the <code>checked</code> property. If the radio button is checked, we update the text content of an element with the id <code>languageOutput</code> using <code>document.querySelector('#languageOutput')</code>. This element serves as a placeholder to display the selected language.</li>
</ul>
<p>This setup ensures that dynamically generated radio buttons have <code>change</code> event listeners attached to them, allowing for dynamic handling of user selections.</p>
<h2 id="heading-checkboxes">Checkboxes</h2>
<h3 id="heading-how-to-create-an-html-checkbox">How to Create an HTML Checkbox</h3>
<p>Let's first create a checkbox using the <code>&lt;input&gt;</code> element and type attribute set to "checkbox". let's associate it with label for better accessibility.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"agree"</span>&gt;</span>
   <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"agree"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"agree"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"yes"</span>&gt;</span> I agree to the terms
<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
</code></pre>
<h3 id="heading-how-to-check-if-a-checkbox-is-checked">How to Check if a Checkbox is Checked</h3>
<p>A checkbox in HTML can exist in two states: checked and unchecked. And we can determine which is active using <code>checked</code> property. If it's <code>true</code>, the checkbox is checked – otherwise, it's unchecked. Example:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"agree"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"agree"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"agree"</span>&gt;</span> I agree to the terms
    <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
        <span class="hljs-keyword">const</span> checkbox = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'agree'</span>);
        <span class="hljs-built_in">console</span>.log(checkbox.checked);
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<h3 id="heading-how-to-get-checkbox-values">How to Get Checkbox Values</h3>
<p>In HTML forms, when a checkbox is checked and the form is submitted, the browser includes the checkbox in the form data with its <code>name</code> attribute as the key and the <code>value</code> attribute (if specified) as the value. But if the checkbox is unchecked, it's not included in the form data at all.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"agree"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"agree"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"agree"</span>&gt;</span> I agree to the terms
<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btn"</span>&gt;</span>Show Value<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
    <span class="hljs-keyword">const</span> checkbox = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#agree'</span>);
    <span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#btn'</span>);
    btn.onclick = <span class="hljs-function">() =&gt;</span> {
       alert(checkbox.value);
    };
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>So basically the point is: When a checkbox is checked and included in form submissions, the browser defaults to sending <code>'on'</code> as the value if no <code>value</code> attribute is explicitly defined for the checkbox input element. To accurately handle the checked state of a checkbox using JavaScript, use the <code>checked</code> property instead of relying solely on the <code>value</code> attribute.</p>
<h3 id="heading-how-to-handle-multiple-checkboxes">How to Handle Multiple Checkboxes</h3>
<p>Sometimes, you may need to work with multiple checkboxes with the same name and you want to retrieve the values of the selected checkboxes. Here's an example:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Select your preferred languages:<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"l1"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"language"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"C++"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"l1"</span> /&gt;</span>C++
    <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"l2"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"language"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Python"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"l2"</span> /&gt;</span>Python
    <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"l3"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"language"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Java"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"l3"</span> /&gt;</span>Java
    <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btn"</span>&gt;</span>Get Selected Languages<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
      <span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#btn"</span>);
      btn.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">const</span> checkboxes = <span class="hljs-built_in">document</span>.querySelectorAll(
          <span class="hljs-string">'input[name="language"]:checked'</span>
        );
        <span class="hljs-keyword">const</span> selectedLanguages = <span class="hljs-built_in">Array</span>.from(checkboxes).map(
          <span class="hljs-function">(<span class="hljs-params">checkbox</span>) =&gt;</span> checkbox.value
        );
        alert(<span class="hljs-string">"Selected Languages: "</span> + selectedLanguages.join(<span class="hljs-string">", "</span>));
      });
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>In this example, we have checkboxes for selecting preferred programming languages.</p>
<ul>
<li>When the button is clicked, it triggers an event listener. Inside the event listener, we select all checkboxes with the name attribute "language" that are checked.</li>
<li>We then convert the NodeList returned by <code>querySelectorAll()</code> into an array using <code>Array.from()</code>.</li>
<li>Finally, we map over the array to retrieve the values of selected checkboxes and display them using <code>alert()</code>.</li>
</ul>
<h3 id="heading-how-to-check-uncheck-all-checkboxes">How to Check / Uncheck All Checkboxes</h3>
<p>Now, let's create a functionality to check or uncheck all checkboxes at once:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btn"</span>&gt;</span>Check / Uncheck All<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Select your preferred languages:<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"l1"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"language"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"C++"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"l1"</span> /&gt;</span>C++
    <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"l2"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"language"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Python"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"l2"</span> /&gt;</span>Python
    <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"l3"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"language"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Java"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"l3"</span> /&gt;</span>Java
    <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Javascript code:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// function to check or uncheck all checkboxes</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">check</span>(<span class="hljs-params">checked = true</span>) </span>{
  <span class="hljs-keyword">const</span> checkboxes = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'input[name="language"]'</span>);

  <span class="hljs-comment">// Iterate through each checkbox</span>
  checkboxes.forEach(<span class="hljs-function">(<span class="hljs-params">checkbox</span>) =&gt;</span> {
    <span class="hljs-comment">// Set the checked property of each checkbox to the value of the 'checked' parameter</span>
    checkbox.checked = checked;
  });
}

<span class="hljs-comment">// function to check all checkboxes and change button behavior to uncheck all</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">checkAll</span>(<span class="hljs-params"></span>) </span>{
  check();
  <span class="hljs-built_in">this</span>.onclick = uncheckAll;
}

<span class="hljs-comment">// function to uncheck all checkboxes and change button behavior to check all</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">uncheckAll</span>(<span class="hljs-params"></span>) </span>{
  check(<span class="hljs-literal">false</span>);
  <span class="hljs-built_in">this</span>.onclick = checkAll;
}

<span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#btn"</span>);

btn.onclick = checkAll;
</code></pre>
<p>In this example, we have a button labeled "Check / Uncheck All".</p>
<ul>
<li>When the button is first clicked, it's intended to check all the checkboxes. Therefore, the <code>checkAll</code> function is assigned to handle this action (<code>const btn = document.querySelector("#btn");</code>).</li>
<li>If the button is clicked again, it unchecks all checkboxes. We define functions <code>check()</code>, <code>checkAll()</code>, and <code>uncheckAll()</code> to handle the checking and unchecking of checkboxes.</li>
<li>We assign <code>checkAll()</code> to the button's <code>onclick</code> event initially, and then switch between <code>checkAll()</code> and <code>uncheckAll()</code> based on the current state of the checkboxes.</li>
</ul>
<p>Alternate approach could be:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">checkAll</span>(<span class="hljs-params">checked = true</span>) </span>{
  <span class="hljs-keyword">const</span> checkboxes = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'input[name="language"]'</span>);
  checkboxes.forEach(<span class="hljs-function">(<span class="hljs-params">checkbox</span>) =&gt;</span> {
    checkbox.checked = checked;
  });
}

<span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#btn"</span>);

btn.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// Find the first checkbox with the name attribute set to 'language'</span>
  <span class="hljs-keyword">const</span> firstCheckbox = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'input[name="language"]'</span>);
  <span class="hljs-comment">// Check if the first checkbox is checked</span>
  <span class="hljs-keyword">const</span> isChecked = firstCheckbox.checked;
  <span class="hljs-comment">// Call the checkAll function with the opposite state of the first checkbox</span>
  checkAll(!isChecked);
});
</code></pre>
<p>Here, we select the first checkbox with the name "language" to determine its current checked state. Then, we call <code>checkAll()</code> with the opposite state.</p>
<h3 id="heading-how-to-dynamically-generate-checkboxes">How to Dynamically Generate CheckBoxes</h3>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"languages"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
      <span class="hljs-keyword">const</span> languageOptions = [<span class="hljs-string">"Python"</span>, <span class="hljs-string">"Javascript"</span>, <span class="hljs-string">"C++"</span>, <span class="hljs-string">"Java"</span>];

      <span class="hljs-comment">// Generate the checkboxes</span>
      <span class="hljs-keyword">const</span> html = languageOptions
        .map(
          <span class="hljs-function">(<span class="hljs-params">language</span>) =&gt;</span> <span class="hljs-string">`&lt;label for="language-<span class="hljs-subst">${language}</span>"&gt;
                &lt;input type="checkbox" name="language" id="language-<span class="hljs-subst">${language}</span>" value="<span class="hljs-subst">${language}</span>"&gt; <span class="hljs-subst">${language}</span>
            &lt;/label&gt;`</span>
        )
        .join(<span class="hljs-string">" "</span>);
      <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#languages"</span>).innerHTML = html;
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Here's how it works:</p>
<ul>
<li>We define an array <code>languageOptions</code> containing language names.</li>
<li>We use the <code>map()</code> method to iterate through the <code>languageOptions</code> array and generate an array of HTML strings for each language.</li>
<li>Each HTML string comprises a <code>label</code> element associated with an <code>input</code> checkbox. The <code>input</code> checkbox includes appropriate attributes such as <code>type</code>, <code>name</code>, <code>id</code>, and <code>value</code>, dynamically derived from the language name.</li>
<li>We join the array of HTML strings into a single string using <code>join(' ')</code>.</li>
<li>Finally, we set the <code>innerHTML</code> property of the root <code>&lt;div&gt;</code> element with the id <code>languages</code> to the generated HTML string, thereby rendering checkboxes for each programming language.</li>
</ul>
<h2 id="heading-select-element">Select Element:</h2>
<p>The <code>&lt;select&gt;</code> element in HTML provides a dropdown list of options for users to choose from. It allows for single or multiple selections. Example:</p>
<pre><code class="lang-javascript">&lt;select id=<span class="hljs-string">"cities"</span>&gt;
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"JAI"</span>&gt;</span>Jaipur<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span></span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"DEL"</span>&gt;</span>New Delhi<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span></span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"UDR"</span>&gt;</span>Udaipur<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span></span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"MUM"</span>&gt;</span>Mumbai<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span></span>
&lt;/select&gt;
</code></pre>
<p>By default, a <code>&lt;select&gt;</code> element allows for a single selection. To enable multiple selections, add the <code>multiple</code> attribute. </p>
<pre><code class="lang-javascript">&lt;select id=<span class="hljs-string">"cities"</span> multiple&gt;
</code></pre>
<p>Users can now select multiple fruits by holding down the Ctrl (or Cmd on Mac) key while clicking.</p>
<h3 id="heading-how-to-interact-with-a-select-element">How to Interact with a Select Element:</h3>
<p>To interact with a <code>&lt;select&gt;</code> element using JavaScript, we use the <code>HTMLSelectElement</code> type, which provides useful properties like <code>selectedIndex</code> and <code>value</code>. Example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
<span class="hljs-keyword">const</span> selectElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'cities'</span>);
<span class="hljs-built_in">console</span>.log(selectElement.selectedIndex); <span class="hljs-comment">// Returns the index of the selected option</span>
<span class="hljs-built_in">console</span>.log(selectElement.value); <span class="hljs-comment">// Returns the value of the selected option</span>
<span class="hljs-built_in">console</span>.log(selectElement.multiple); <span class="hljs-comment">// Returns true if multiple selections are allowed</span>
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>JavaScript allows you to handle events on the <code>&lt;select&gt;</code> element, such as when a user selects an option. Example:</p>
<pre><code class="lang-javascript">&lt;button id=<span class="hljs-string">"btn"</span>&gt;Get Selected City&lt;/button&gt;
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
      <span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#btn"</span>);
      <span class="hljs-keyword">const</span> selectElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"cities"</span>);
      btn.onclick = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
        event.preventDefault();
        <span class="hljs-keyword">const</span> selectedCity =
          selectElement.options[selectElement.selectedIndex].text;
        alert(<span class="hljs-string">`Selected city: <span class="hljs-subst">${selectedCity}</span>, 
        Index: <span class="hljs-subst">${selectElement.selectedIndex}</span>`</span>);
      };
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>
</code></pre>
<p><strong>Using the <code>value</code> property:</strong> The <code>value</code> property represents the value of the selected option. Let's understand it with example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"cities"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">""</span>&gt;</span>Jaipur<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span> 
    <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"DEL"</span>&gt;</span>New Delhi<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"UDR"</span>&gt;</span>Udaipur<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">option</span>&gt;</span>Mumbai<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#btn"</span>);
<span class="hljs-keyword">const</span> selectElement = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#cities"</span>);

btn.onclick = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    event.preventDefault();
    alert(selectElement.value);
};
</code></pre>
<ul>
<li>If "Jaipur" is selected, this means we have an empty string since the value attribute is empty in our Html.</li>
<li>If an option lacks a value attribute, the select box's value property becomes the text of the selected option. Example: if "Mumbai" is selected, the value property is "Mumbai".</li>
<li>If multiple options are selected, the <code>value</code> property of the select box is derived from the first selected option based on the previous rules.</li>
</ul>
<h3 id="heading-how-to-access-options-with-javascript">How to Access Options with JavaScript</h3>
<p>The <code>HTMLOptionElement</code> type represents individual <code>&lt;option&gt;</code> elements within a <code>&lt;select&gt;</code> element in JavaScript. It provides properties like <code>index</code>, <code>selected</code>, <code>text</code>, and <code>value</code> to access information about each option. </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> selectElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'cities'</span>);
<span class="hljs-keyword">const</span> secondOptionText = selectElement.options[<span class="hljs-number">1</span>].text; <span class="hljs-comment">// Accessing text of the second option</span>
<span class="hljs-keyword">const</span> secondOptionValue = selectElement.options[<span class="hljs-number">1</span>].value; <span class="hljs-comment">// Accessing value of the second option</span>
</code></pre>
<h3 id="heading-how-to-handle-multiple-selections">How to Handle Multiple Selections:</h3>
<p>When a <code>&lt;select&gt;</code> element allows multiple selections, you can iterate through its options to find which ones are selected and retrieve their text values. </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> selectElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'cities'</span>);
<span class="hljs-keyword">const</span> selectedOptions = <span class="hljs-built_in">Array</span>.from(selectElement.options).filter(<span class="hljs-function"><span class="hljs-params">option</span> =&gt;</span> option.selected);
<span class="hljs-keyword">const</span> selectedValues = selectedOptions.map(<span class="hljs-function"><span class="hljs-params">option</span> =&gt;</span> option.text);
</code></pre>
<p>The output will be an array containing text of selected options. We can use <code>option.value</code> to get an array of values instead. Example:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"cities"</span> <span class="hljs-attr">multiple</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"JAI"</span>&gt;</span>Jaipur<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"DEL"</span>&gt;</span>New Delhi<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"UDR"</span>&gt;</span>Udaipur<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"MUM"</span>&gt;</span>Mumbai<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btn"</span>&gt;</span>Get Selected Cities<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
      <span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#btn"</span>);
      <span class="hljs-keyword">const</span> selectElement = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#cities"</span>);

      btn.onclick = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
        event.preventDefault();
        <span class="hljs-keyword">const</span> selectedOptions = <span class="hljs-built_in">Array</span>.from(selectElement.options)
          .filter(<span class="hljs-function">(<span class="hljs-params">option</span>) =&gt;</span> option.selected)
          .map(<span class="hljs-function">(<span class="hljs-params">option</span>) =&gt;</span> option.text);
        alert(<span class="hljs-string">"Selected City: "</span> + selectedOptions.join(<span class="hljs-string">", "</span>));
      };
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<ul>
<li>When the button is clicked, the script collects the selected options by filtering the options based on the <code>selected</code> property. It then maps over the selected options to retrieve their text content.</li>
<li>Finally, it displays the selected languages in an alert message.</li>
</ul>
<h3 id="heading-lets-see-an-example-task-manager-adding-and-removing-tasks">Let's See an Example: Task Manager (Adding and Removing Tasks)</h3>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
    <span class="hljs-selector-id">#container</span> {
      <span class="hljs-attribute">max-width</span>: <span class="hljs-number">540px</span>;
      <span class="hljs-attribute">margin</span>: <span class="hljs-number">50px</span> auto;
    }

    <span class="hljs-selector-tag">form</span> {
      <span class="hljs-attribute">display</span>: flex;
      <span class="hljs-attribute">flex-direction</span>: column;
    }
  </span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"container"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"task"</span>&gt;</span>Task:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
          <span class="hljs-attr">id</span>=<span class="hljs-string">"task"</span>
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter a task"</span>
          <span class="hljs-attr">autocomplete</span>=<span class="hljs-string">"off"</span>
        /&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btnAdd"</span>&gt;</span>Add Task<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"taskList"</span>&gt;</span>Task List:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"taskList"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"taskList"</span> <span class="hljs-attr">multiple</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btnRemove"</span>&gt;</span>Remove Selected Tasks<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>This HTML structure includes input fields for entering task descriptions, buttons for adding and removing tasks, and a <code>&lt;select&gt;</code> element to display the list of tasks. We added a little css for clarity. Let's see Javascript code now:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> btnAdd = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#btnAdd'</span>);
<span class="hljs-keyword">const</span> btnRemove = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#btnRemove'</span>);
<span class="hljs-keyword">const</span> taskList = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#taskList'</span>);
<span class="hljs-keyword">const</span> taskInput = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#task'</span>);

btnAdd.onclick = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    e.preventDefault();

    <span class="hljs-comment">// Validate the task input</span>
    <span class="hljs-keyword">if</span> (taskInput.value.trim() === <span class="hljs-string">''</span>) {
        alert(<span class="hljs-string">'Please enter a task description.'</span>);
        <span class="hljs-keyword">return</span>;
    }

    <span class="hljs-comment">// Create a new task option</span>
    <span class="hljs-keyword">const</span> option = <span class="hljs-keyword">new</span> Option(taskInput.value, taskInput.value);
    taskList.add(option, <span class="hljs-literal">undefined</span>);

    <span class="hljs-comment">// Reset the task input</span>
    taskInput.value = <span class="hljs-string">''</span>;
    taskInput.focus();
};

btnRemove.onclick = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    e.preventDefault();

    <span class="hljs-comment">// Save the selected tasks</span>
    <span class="hljs-keyword">let</span> selectedTasks = [];

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; taskList.options.length; i++) {
        selectedTasks[i] = taskList.options[i].selected;
    }

    <span class="hljs-comment">// Remove selected tasks</span>
    <span class="hljs-keyword">let</span> index = taskList.options.length;
    <span class="hljs-keyword">while</span> (index--) {
        <span class="hljs-keyword">if</span> (selectedTasks[index]) {
            taskList.remove(index);
        }
    }
};
</code></pre>
<p>Explaination: we select the necessary elements from the HTML and attach event listeners to the "Add Task" and "Remove Selected Tasks" buttons. When the "Add Task" button is clicked, we create a new task option based on the input field value and add it to the <code>&lt;select&gt;</code> element. When the "Remove Selected Tasks" button is clicked, we remove the selected tasks from the <code>&lt;select&gt;</code> element.</p>
<h2 id="heading-difference-between-change-and-input-event">Difference Between Change and Input Event</h2>
<p>The input event in JavaScript is triggered whenever the value of an input, <code>&lt;select&gt;</code>, or <code>&lt;textarea&gt;</code> element changes. Unlike the change event, which waits for a value to be committed (for example, when an input loses focus), the input event fires continuously as the value changes. The input event basically provides a way to respond to user input in real-time. Example: </p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"userInput"</span>&gt;</span>Enter Your Name:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"userInput"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Your name"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Your name is: <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"displayName"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript">&lt;script&gt;
    <span class="hljs-keyword">const</span> userInput = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'userInput'</span>);
    <span class="hljs-keyword">const</span> Name = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'displayName'</span>);

    userInput.addEventListener(<span class="hljs-string">'input'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        Name.textContent = userInput.value || <span class="hljs-string">'Guest!'</span>;
    });
&lt;/script&gt;
</code></pre>
<ul>
<li>This JavaScript code selects the input field with the ID "userInput" and the span element with the ID "displayName".</li>
<li>An event listener is attached to the input event of the userInput field.</li>
<li>When the input event is triggered (for example, when typing in the input field), the event handler updates the text content of the <code>displayName</code> span dynamically to reflect the entered name, or it displays "Anonymous" if the input field is empty.</li>
<li>Now, if you change 'input' to 'change' here <code>userInput.addEventListener('input', function()</code> like this: <code>userInput.addEventListener('change', function()</code>, the event listener will be triggered only when the input field loses focus after a value has been entered (as opposed to continuously while the value is being changed in real-time).</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>By understanding the fundamentals of HTML form elements, attributes, and events, you can create dynamic and user-friendly web forms that enhance the user experience. </p>
<p>JavaScript plays a crucial role in handling form submissions, validating user input, and providing real-time feedback to users.</p>
<p>Through practical examples and detailed explanations, in this guide you've learned about working with radio buttons, checkboxes, select elements, and handling multiple selections. </p>
<p>Keep exploring and experimenting with the concepts presented here to create robust and intuitive forms for your web applications.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Regular Expressions (RegEx) in JavaScript – A Handbook for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ Regular expressions, also known as regex, are powerful tools for pattern matching and text manipulation. Whether you're validating user input, extracting data from strings, or performing advanced text processing tasks, understanding regex is essentia... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/regex-in-javascript/</link>
                <guid isPermaLink="false">66c72195e39cd88fc3e1ccfe</guid>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Regex ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Samyak Jain ]]>
                </dc:creator>
                <pubDate>Tue, 27 Feb 2024 20:17:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/Regular-Expressions-in-JavaScript-Cover-2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Regular expressions, also known as regex, are powerful tools for pattern matching and text manipulation. Whether you're validating user input, extracting data from strings, or performing advanced text processing tasks, understanding regex is essential for developers.</p>
<p>This comprehensive guide will walk you through the fundamentals of regular expressions in JavaScript, including how to create and use them, their special characters, flags, and practical examples. </p>
<h3 id="heading-prerequisites">Prerequisites:</h3>
<p>While this tutorial is designed to be beginner-friendly, having a basic understanding of JavaScript fundamentals will be beneficial. Familiarity with variables, data types, functions, and string manipulation in JavaScript will help you grasp the concepts covered.</p>
<h2 id="heading-table-of-contents">Table of Contents:</h2>
<ol>
<li><a class="post-section-overview" href="#heading-what-are-regex">What are Regex</a>?<br>– <a class="post-section-overview" href="#heading-how-to-write-regular-expression-patterns">How to Write Regular Expression Patterns</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-regular-expressions-in-javascript">How to Use Regular Expressions in JavaScript</a><br>– RegEx Methods in JavaScript<br>– <a class="post-section-overview" href="#heading-advanced-searching-with-flags">Advanced Searching with Flags</a></li>
<li><a class="post-section-overview" href="#heading-anchors-in-regex">Anchors in Regex</a><br>– <a class="post-section-overview" href="#heading-multiline-mode-of-anchors-and">Multiline Mode(m) of Anchors</a><br>– <a class="post-section-overview" href="#heading-word-boundaries-b">Word Boundaries (<code>\b</code>)</a></li>
<li><a class="post-section-overview" href="#heading-quantifiers-in-regex">Quantifiers in Regex</a><br>– <a class="post-section-overview" href="#heading-greedy-quantifiers">Greedy Quantifiers</a><br>– [Non Greedy Quantifiers (Lazy Mode)](#Non Greedy Quantifiers (Lazy Mode))</li>
<li><a class="post-section-overview" href="#heading-sets-and-ranges-in-regex">Sets and Ranges in Regex</a><br>– <a class="post-section-overview" href="#heading-sets">Sets</a><br>– <a class="post-section-overview" href="#heading-ranges">Ranges</a><br>– <a class="post-section-overview" href="#heading-negating-excluding-ranges">Negating / Excluding Ranges</a><br>– <a class="post-section-overview" href="#heading-predefined-character-classes">Predefined Character Classes</a></li>
<li><a class="post-section-overview" href="#heading-special-characters-and-escaping-in-regex">Special Characters and Escaping in Regex</a><br>– <a class="post-section-overview" href="#heading-metacharacters">Metacharacters</a><br>– <a class="post-section-overview" href="#heading-escape-special-characters">Escaping Special Characters</a></li>
<li><a class="post-section-overview" href="#heading-groupings-in-regex">Groupings in RegEx</a><br>– <a class="post-section-overview" href="#heading-capturing-groups">Capturing Groups</a><br>– <a class="post-section-overview" href="#heading-non-capturing-groups">Non-Capturing Groups</a><br>– <a class="post-section-overview" href="#heading-backreferences">Backreferences</a><br>– <a class="post-section-overview" href="#heading-regex-alternation">Regex Alternation</a></li>
<li><a class="post-section-overview" href="#heading-lookahead-and-lookbehind-in-regex">Lookahead and Lookbehind Assertions in Regex</a><br>– <a class="post-section-overview" href="#heading-lookahead">Lookahead (?=)</a><br>– <a class="post-section-overview" href="#heading-negative-lookaheads">Negative Lookahead (?!)</a><br>– <a class="post-section-overview" href="#heading-lookbehind">Lookbehind (?&lt;=)</a><br>– <a class="post-section-overview" href="#heading-negative-lookbehind">Negative Lookbehind (?&lt;!)</a></li>
<li><a class="post-section-overview" href="#heading-practical-examples-and-use-cases-of-regex">Practical Examples and Use Cases of Regex</a><br>– <a class="post-section-overview" href="#heading-password-strength-checking">Password Strength Checking</a><br>– <a class="post-section-overview" href="#heading-email-validation-function">Email Validation</a><br>– <a class="post-section-overview" href="#heading-phone-number-formatting-function">Phone Number Formatting</a></li>
<li><a class="post-section-overview" href="#heading-tips-and-best-practices-for-using-regular-expressions">RegEx Tips and Best Practices</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<h2 id="heading-what-are-regex">What Are Regex?</h2>
<p>A regular expression, often abbreviated as "regex," is a sequence of characters that define a search pattern. This pattern is used to find matches within strings, helping you identify specific text or patterns of characters, providing a powerful way to search, replace, and manipulate text.</p>
<p>In JavaScript, you can create regular expressions using either a literal notation or the <code>RegExp</code> constructor:</p>
<ul>
<li><strong>Using a Regular Expression Literal</strong>: This involves enclosing the pattern between slashes ("/").</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/pattern/</span>;

<span class="hljs-comment">// example</span>
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/ab+c/</span>;
</code></pre>
<ul>
<li><strong>Using the Constructor Function: <code>RegExp</code></strong> constructor. This allows runtime compilation of the regular expression and is useful when the pattern may change.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> re = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">"pattern"</span>);

<span class="hljs-comment">// example</span>
<span class="hljs-keyword">const</span> re = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">"ab+c"</span>);
</code></pre>
<p>Both methods produce the same result – it's a matter of preference which one you choose.</p>
<h3 id="heading-how-to-write-regular-expression-patterns">How to Write Regular Expression Patterns</h3>
<p>A regular expression pattern can consist of simple characters or a combination of simple and special characters. </p>
<ol>
<li><strong>Simple Pattern</strong>: They match exact character sequences. For example, the pattern <code>/abc/</code> matches the sequence "abc" in a string.</li>
<li><strong>Special Characters</strong>: They enhance pattern matching with capabilities like repetition or matching specific types of characters, allowing for more flexible and powerful pattern matching. For example, <code>*</code> matches zero or more occurrences of the preceding item. <code>/ab*c/</code> matches "ac", "abc", "abbc", and so on.</li>
</ol>
<h2 id="heading-how-to-use-regular-expressions-in-javascript">How to Use Regular Expressions in JavaScript</h2>
<p>You can use regular expressions with various methods available for both the <code>RegExp</code> and <code>String</code> objects in JavaScript. Some methods like <code>test()</code>, <code>exec()</code>, and others have this syntax:</p>
<pre><code class="lang-javascript">regex.methodname(string)

<span class="hljs-comment">// example</span>
regex.test(string)
</code></pre>
<p>While some methods like <code>match()</code>, <code>replace()</code>, and so on have this syntax:</p>
<pre><code class="lang-javascript">string.methodname(regex)

<span class="hljs-comment">// example</span>
string.replace(regex, replacement)
</code></pre>
<p>Here, <code>string</code> is the string and <code>regex</code> is a regular expression pattern.</p>
<p>Let's explore how these methods are used in practice.</p>
<p><strong>The <code>test()</code> Method</strong>: checks whether a particular string matches a specified pattern or regular expression. It returns <code>true</code> if the pattern is found in the string, otherwise, it returns <code>false</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> pattern = <span class="hljs-regexp">/hello/</span>;
<span class="hljs-keyword">let</span> str = <span class="hljs-string">"hello world"</span>;

<span class="hljs-keyword">let</span> result = pattern.test(str);
<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: true</span>
</code></pre>
<p><strong>The <code>exec()</code> Method</strong>: searches for a match of a pattern within a string. It returns an array containing details like the matched text, index of the match within the string, and the input string itself. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> pattern = <span class="hljs-regexp">/world/</span>;
<span class="hljs-keyword">let</span> str = <span class="hljs-string">"hello world"</span>;

<span class="hljs-keyword">let</span> result = pattern.exec(str);
<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: ["world", index: 6, input: "hello world"]</span>
</code></pre>
<p><strong>The <code>match()</code> Method</strong>: Searches for occurrences of a pattern within a string. It returns the first element matched. If has the global flag (<code>g</code>), it returns an array containing all matches found, or <code>null</code> if no matches are found.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">"The quick brown fox jumps over the lazy dog."</span>;
<span class="hljs-keyword">let</span> matches = str.match(<span class="hljs-regexp">/the/gi</span>);

<span class="hljs-built_in">console</span>.log(matches); <span class="hljs-comment">// Output: ["The", "the"]</span>
</code></pre>
<p><strong>The <code>matchAll()</code> Method</strong>: Returns an iterator of all results matching a regular expression against a string. Each element of the iterator is an array containing details about the match, including captured groups.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">"Hello world! This is a test string."</span>;
<span class="hljs-keyword">let</span> regex = <span class="hljs-regexp">/[a-zA-Z]+/g</span>;

<span class="hljs-keyword">let</span> matches = str.matchAll(regex);

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> match <span class="hljs-keyword">of</span> matches) {
    <span class="hljs-built_in">console</span>.log(match);
}
</code></pre>
<p>This method is useful when you need detailed information about all matches found in a string.</p>
<p><strong>The <code>search()</code> Method</strong>: Searches for a specified pattern within a string. It returns the index of the first occurrence of the pattern within the string, or <code>-1</code> if the pattern is not found.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">"The quick brown fox jumps over the lazy dog"</span>;
<span class="hljs-keyword">let</span> pattern = <span class="hljs-regexp">/brown/</span>;

<span class="hljs-keyword">let</span> result = str.search(pattern);
<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: 10</span>
</code></pre>
<p><strong>The <code>replace()</code> Method</strong>: Replaces the first occurrence of a specified pattern in a string with another substring or value. To replace all occurrences, you can use the global flag (<code>g</code>) in the regular expression.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">"Hello, World!"</span>;
<span class="hljs-keyword">let</span> newStr = str.replace(<span class="hljs-regexp">/o/g</span>, <span class="hljs-string">"0"</span>);

<span class="hljs-built_in">console</span>.log(newStr); <span class="hljs-comment">// Output: "Hell0, W0rld!"</span>
</code></pre>
<p><strong>The <code>replaceAll()</code> Method</strong>: Replaces all occurrences of a specified substring or pattern with a replacement string. It differs from <code>replace()</code> in that it replaces all occurrences by default, without the need for a global flag (<code>g</code>).</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">"apple,banana,apple,grape"</span>;
<span class="hljs-keyword">let</span> newStr = str.replaceAll(<span class="hljs-string">"apple"</span>, <span class="hljs-string">"orange"</span>);
<span class="hljs-built_in">console</span>.log(newStr); <span class="hljs-comment">// Output: "orange,banana,orange,grape"</span>
</code></pre>
<p>This method simplifies the process of replacing all occurrences of a substring within a string.</p>
<p><strong>The <code>split()</code> Method</strong>: Though not exclusively a RegEx method, <code>split()</code> can accept a RegEx pattern as its argument to split a string into an array of substrings based on the specified patterns or delimiters. For instance:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">"apple,banana,grape"</span>;
<span class="hljs-keyword">let</span> arr = str.split(<span class="hljs-regexp">/,/</span>);
<span class="hljs-built_in">console</span>.log(arr); <span class="hljs-comment">// Output: ["apple", "banana", "grape"]</span>
</code></pre>
<p>These methods offer different functionalities based on your needs. For example, if you only need to know whether a pattern is found in a string, <code>test()</code> or <code>search()</code> methods are efficient. If you require more information about matches, the <code>exec()</code> or <code>match()</code> methods are suitable.</p>
<h2 id="heading-advanced-searching-with-flags">Advanced Searching with Flags</h2>
<p>In JavaScript, regular expressions support pattern flags, which are optional parameters that modify the behavior of the pattern matching. </p>
<p>Let's delve into two common flags: the ignore flag (<code>i</code>) and the global flag (<code>g</code>).</p>
<h3 id="heading-the-ignore-flag-i">The Ignore Flag (<code>i</code>):</h3>
<p>The ignore flag (<code>i</code>) instructs the regular expression to ignore case sensitivity when searching for matches. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/hello/i</span>;
<span class="hljs-keyword">let</span> testString = <span class="hljs-string">"Hello, World!"</span>;
<span class="hljs-keyword">let</span> result = re.test(testString);

<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: true</span>
</code></pre>
<p>In this case, the regular expression <code>/hello/i</code> matches the string <code>"Hello"</code> despite differences in case because we used the ignore flag.</p>
<h3 id="heading-the-global-flag-g">The Global Flag (<code>g</code>):</h3>
<p>The global flag (<code>g</code>) allows the regular expression to find all matches within a string, rather than stopping after the first match. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/hi/g</span>;
<span class="hljs-keyword">let</span> testString = <span class="hljs-string">"hi there, hi again!"</span>;
<span class="hljs-keyword">let</span> result = testString.match(re);

<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: ["hi", "hi"]</span>
</code></pre>
<p>In this example, the regular expression <code>/hi/g</code> finds both occurrences of <code>"hi"</code> in the string <code>"hi there, hi again!"</code>.</p>
<h3 id="heading-combining-flags">Combining Flags</h3>
<p>You can combine flags to achieve specific matching behavior. For instance, using both the ignore flag (<code>i</code>) and the global flag (<code>g</code>) together allows for case-insensitive matching while finding all occurrences of the pattern.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/hi/gi</span>;
<span class="hljs-keyword">let</span> testString = <span class="hljs-string">"Hi there, HI again!"</span>;
<span class="hljs-keyword">let</span> result = testString.match(re);

<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: ["Hi", "HI"]</span>
</code></pre>
<p>Here, the regular expression <code>/hi/gi</code> matches both <code>"Hi"</code> and <code>"HI"</code> in the string <code>"Hi there, HI again!"</code>.</p>
<h3 id="heading-the-u-flag">The <code>u</code> Flag:</h3>
<p>Though not commonly used, the <code>u</code> flag handles Unicode characters, especially surrogate pairs, correctly. Surrogate pairs are used to represent characters outside the Basic Multilingual Plane (BMP) in UTF-16 encoding.</p>
<p><strong>Example:</strong> Let's consider a string containing emoji characters and try to match them using a regular expression without and with the <code>u</code> flag.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Without the u flag</span>
<span class="hljs-keyword">let</span> result1 = <span class="hljs-string">'Smile Please 😊'</span>.match(<span class="hljs-regexp">/[😒😊🙄]/</span>);
<span class="hljs-built_in">console</span>.log(result1); <span class="hljs-comment">// Output: ["�"]</span>

<span class="hljs-comment">// With the u flag</span>
<span class="hljs-keyword">let</span> result2 = <span class="hljs-string">'Smile Please 😊'</span>.match(<span class="hljs-regexp">/[😒😊🙄]/u</span>);
<span class="hljs-built_in">console</span>.log(result2); <span class="hljs-comment">// Output: ["😊"]</span>
</code></pre>
<p>Without the <code>u</code> flag, the regex fails to match the emoji correctly because they are represented as surrogate pairs in UTF-16 encoding. However, with the <code>u</code> flag, it correctly matches the emoji <code>'😊'</code>.</p>
<h2 id="heading-anchors-in-regex">Anchors in Regex</h2>
<p>Anchors are special characters in regex that do not represent actual characters but instead indicate positions within a string. There are two main anchors: <code>^</code> and <code>$</code>.</p>
<p><strong>The <code>^</code> Anchor</strong>: The <code>^</code> anchor matches the beginning of the text. Basically, it checks if a string starts with a specific character or pattern.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'Mountain'</span>;
<span class="hljs-built_in">console</span>.log(<span class="hljs-regexp">/^S/</span>.test(str)); <span class="hljs-comment">// Output: false</span>
</code></pre>
<p><strong>The <code>$</code> Anchor</strong>: The <code>$</code> anchor matches the end of the text. It checks if a string ends with a specific character or pattern.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'Ocean'</span>;
<span class="hljs-built_in">console</span>.log(<span class="hljs-regexp">/n$/</span>.test(str)); <span class="hljs-comment">// Output: true</span>
</code></pre>
<p>You may often use <code>^</code> and <code>$</code> together to check if a string fully matches a pattern.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> isValid = <span class="hljs-regexp">/^\d\d:\d\d$/</span>.test(<span class="hljs-string">'10:01'</span>);
<span class="hljs-built_in">console</span>.log(isValid); <span class="hljs-comment">// Output: true</span>
</code></pre>
<ul>
<li>In the code above, <code>^\d\d:\d\d$</code> ensures that the string contains exactly two digits, followed by a colon, and then exactly two more digits.</li>
</ul>
<h3 id="heading-multiline-mode-of-anchors-and">Multiline Mode of Anchors (<code>^</code> and <code>$</code>):</h3>
<p>By default, the <code>^</code> and <code>$</code> anchors in regular expressions operate in single-line mode, meaning they match the beginning and end of the entire string. But in some cases, you might want to match the beginning and end of individual lines within a multiline string. This is where the multiline mode, indicated by the <code>m</code> flag, comes into play.</p>
<p>Since single-line mode is the default, it only matches the first digit "1" at the beginning of the string.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">`1st line
2nd line
3rd line`</span>;

<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/^\d/g</span>; <span class="hljs-comment">// "^\d" matches the digit at the beginning of the string</span>
<span class="hljs-keyword">let</span> matches = str.match(re);

<span class="hljs-built_in">console</span>.log(matches); <span class="hljs-comment">// Output: ["1"]</span>
</code></pre>
<ul>
<li><strong>multiline mode(m)</strong>: <code>/^\d/gm</code> is the regex pattern with the <code>m</code> flag enabled. By utilizing the <code>m</code> flag, you can ensure that <code>^</code> and <code>$</code> match the beginning and end of individual lines within a multiline string, rather than just the entire string itself.</li>
</ul>
<p>As a result, it matches "1" from the first line, "2" from the second line, and "3" from the third line:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">`1st line
2nd line
3rd line`</span>;

<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/^\d/gm</span>;
<span class="hljs-keyword">let</span> matches = str.match(re);

<span class="hljs-built_in">console</span>.log(matches); <span class="hljs-comment">// Output: ["1", "2", "3"]</span>
</code></pre>
<p> This is particularly useful when working with text that contains multiple lines or line breaks.</p>
<h3 id="heading-word-boundaries-b">Word Boundaries (<code>\b</code>) :</h3>
<p>The <code>\b</code> is a special character in regular expressions called an anchor, just like <code>^</code> and <code>$</code>. It's used to match a position in the string where a word character (such as a letter, digit, or underscore) is not followed or preceded by another word character. For instance:</p>
<ul>
<li><code>\bword\b</code> matches the word "word" in the string, but not substrings like "wording" or "swordfish".</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> pattern = <span class="hljs-regexp">/\bword\b/</span>;
<span class="hljs-keyword">let</span> pattern2 = <span class="hljs-regexp">/word/</span>;
<span class="hljs-built_in">console</span>.log(pattern.test(<span class="hljs-string">"This is a word."</span>)); <span class="hljs-comment">// Output: true</span>
<span class="hljs-built_in">console</span>.log(pattern.test(<span class="hljs-string">"This is wording."</span>)); <span class="hljs-comment">// Output: false (doesn't match "wording")</span>
<span class="hljs-built_in">console</span>.log(pattern2.test(<span class="hljs-string">"This is wording"</span>)); <span class="hljs-comment">// Output: True</span>
</code></pre>
<p><code>/word/</code> matches the substring "word" anywhere within the string. It matches "word" in "This is wording." because it doesn't include any word boundary assertions.</p>
<p>Other examples can be:</p>
<ul>
<li><code>\b\d+\b</code> matches whole numbers in the string, but doesn't include non-numeric characters adjacent to the numbers.</li>
<li><code>^\bword\b$</code> matches a string that consists solely of the word "word".</li>
</ul>
<h2 id="heading-quantifiers-in-regex">Quantifiers in Regex</h2>
<p>In regex, quantifiers enable you to specify the quantity of characters or character classes you want to match within a string. They are symbols or characters that define how many instances of a character or group you're looking for.</p>
<h3 id="heading-exact-count-n">Exact Count <code>{n}</code>:</h3>
<p>The simplest quantifier is <code>{n}</code>, which specifies an exact count of characters or character classes you want to match. Let's say we have a string "Year: 2022" and we want to extract the year from it:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'Year: 2022'</span>;
<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/\d{4}/</span>; <span class="hljs-comment">// Matches a four-digit number ; basically concise &amp; better way to write \d\d\d\d</span>

<span class="hljs-keyword">let</span> result = str.match(re);

<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: ["2022"]</span>
</code></pre>
<h3 id="heading-the-range-nm">The Range <code>{n,m}</code>:</h3>
<p>The range quantifier <code>{n,m}</code> matches a character or character class from n to m times, inclusively. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">"The meeting is scheduled for 10:30 AM and ends at 2 PM"</span>;
<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/\d{2,4}/g</span>; <span class="hljs-comment">// Matches numbers with 2 to 4 digits</span>

<span class="hljs-keyword">let</span> result = str.match(re);
<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: [ '10', '30' ]</span>
</code></pre>
<h3 id="heading-n-and-shorthands"><code>{n,}</code> and Shorthands:</h3>
<p>The <code>{n,}</code> quantifier matches a character or character class at least n times. Additionally, there are shorthand notations for common quantifiers. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'The price of the item is $2500'</span>;
<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/\d{2,}/g</span>; <span class="hljs-comment">// Matches numbers with 2 or more digits</span>

<span class="hljs-keyword">let</span> result = str.match(re);
<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: ["2500"]</span>
</code></pre>
<h3 id="heading-shorthands">Shorthands: <code>+</code>, <code>?</code>, <code>*</code>:</h3>
<p>The quantifiers <code>+</code>, <code>?</code>, and <code>*</code> are shorthand notations for common use cases. Let's use the shorthand <code>+</code> to match one or more digits in a phone number:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> phone = <span class="hljs-string">"+1-(103)-777-0101"</span>;
<span class="hljs-keyword">let</span> result = phone.match(<span class="hljs-regexp">/\d+/g</span>); <span class="hljs-comment">// Matches one or more digits</span>

<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: ["1", "103", "777", "0101"]</span>
</code></pre>
<h3 id="heading-quantifiers-zero-or-one">Quantifiers: Zero or One (<code>?</code>):</h3>
<p>The quantifier <code>?</code> in regular expressions means zero or one occurrence of the preceding character or group. It's equivalent to {0,1}. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'The sky is blue in color, but the ocean is blue in colour'</span>;
<span class="hljs-keyword">let</span> result = str.match(<span class="hljs-regexp">/colou?r/g</span>); <span class="hljs-comment">// Matches "color" and "colour"</span>

<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: ["color", "colour"]</span>
</code></pre>
<p>In this example, the regular expression <code>/colou?r/g</code> matches both "color" and "colour" in the given string, allowing for zero or one occurrence of the letter "u".</p>
<h3 id="heading-quantifiers-zero-or-more">Quantifiers: Zero or More (<code>*</code>):</h3>
<p>The quantifier <code>*</code> in regular expressions means zero or more occurrences of the preceding character or group. It's equivalent to {0,}. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'Computer science is fascinating, but computational engineering is equally interesting'</span>;
<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/comput\w*/g</span>; <span class="hljs-comment">// Matches "computer" and "computational"</span>

<span class="hljs-keyword">let</span> results = str.match(re);

<span class="hljs-built_in">console</span>.log(results); <span class="hljs-comment">// Output: ["computer", "computational"]</span>
</code></pre>
<h3 id="heading-greedy-quantifiers">Greedy Quantifiers:</h3>
<p>In regular expressions, quantifiers determine how many times a particular element can occur in a match. </p>
<p>By default, quantifiers operate in what's called a "greedy" mode. This means they try to match as much of the preceding element as possible. For instance:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> regexp = <span class="hljs-regexp">/".+"/g</span>;
<span class="hljs-keyword">let</span> str = <span class="hljs-string">'The "Boy" and his "Friends" were here'</span>;
<span class="hljs-built_in">console</span>.log( str.match(regexp) ); <span class="hljs-comment">// "Boy" and his "Friends"</span>
</code></pre>
<p>Instead of finding two separate matches ("Boy" and "Friends"), it finds one match encompassing both ("Boy" and his "Friends").</p>
<h4 id="heading-understanding-greedy-search">Understanding Greedy Search</h4>
<p>To understand why the initial attempt failed, let's delve into how the regular expression engine conducts its search. </p>
<ol>
<li>The engine starts from the beginning of the string and finds the opening quote.</li>
<li>It proceeds to match characters following the opening quote. Since the pattern is <code>".+"</code>, where <code>.</code> matches any character and <code>+</code> quantifies it to match one or more times, the engine continues matching characters until it reaches the end of the string.</li>
<li>The engine then backtracks to find the end quote <code>"</code> that would complete the match. It starts by assuming the maximum possible characters matched by <code>".+"</code> and gradually reduces the number of characters until it finds a valid match.</li>
<li>Eventually, the engine finds a match encompassing the entire substring "Boy" and his "Friends".</li>
</ol>
<p>This behavior of greedily matching as many characters as possible is the default mode of quantifiers in regular expressions and doesn't always yield the desired results. You can see this in the example where it results in a single match instead of multiple separate matches for quoted strings.</p>
<h3 id="heading-non-greedy-quantifiers-lazy-mode">Non Greedy Quantifiers (Lazy Mode):</h3>
<p>To address the limitations of greedy mode, regular expressions also support a lazy mode for quantifiers. In lazy mode, quantified characters are repeated the minimal number of times necessary to satisfy the pattern.</p>
<p>We can enable the lazy mode by appending a question mark <code>?</code> after the quantifier. For example, <code>*?</code> or <code>+?</code> denotes lazy repetition.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> regexp = <span class="hljs-regexp">/".+?"/g</span>;
<span class="hljs-keyword">let</span> str = <span class="hljs-string">'The "Boy" and his "Friends" were here'</span>;
<span class="hljs-built_in">console</span>.log( str.match(regexp) ); <span class="hljs-comment">// "Boy" "Friends"</span>
</code></pre>
<p>In this example, the lazy quantifier <code>".+?"</code> ensures that each quoted string is matched separately by minimizing the number of characters matched between the opening and closing quotes.</p>
<p>Let's trace the search process step by step to understand how the lazy quantifier works:</p>
<ul>
<li>The engine starts from the beginning of string and finds the opening quote.</li>
<li>Instead of greedily matching all characters until the end of the string, the lazy quantifier <code>".+?"</code> matches only the characters necessary to satisfy the pattern. It stops as soon as it encounters the closing quote <code>"</code>.</li>
<li>The engine repeats this process for each quoted string in the text, resulting in separate matches for "Boy" and "Friends".</li>
</ul>
<h2 id="heading-sets-and-ranges-in-regex">Sets and Ranges in Regex</h2>
<p>In regular expressions, you use sets and ranges to match specific characters or a range of characters within a given pattern.</p>
<h3 id="heading-sets">Sets:</h3>
<p>A set is defined using square brackets <code>[...]</code>. It allows you to match any character within the set. For example, <code>[aeiou]</code> matches any of the vowels 'a', 'e', 'i', 'o', or 'u'.</p>
<p><strong>Example:</strong> Suppose we have a string <code>'The quick brown fox jumps over the lazy dog.'</code>. To match all vowels in this string, we can use the regular expression <code>/[aeiou]/g</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'The quick brown fox jumps over the lazy dog.'</span>;
<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/[aeiou]/g</span>;
<span class="hljs-keyword">let</span> results = str.match(re);

<span class="hljs-built_in">console</span>.log(results); <span class="hljs-comment">// Output: ['e', 'u', 'i', 'o', 'o', 'u', 'o', 'e', 'e', 'a', 'o']</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'The cat chased the rats in the backyard'</span>;;
<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/[cr]at/g</span>;
<span class="hljs-keyword">let</span> results = str.match(re);

<span class="hljs-built_in">console</span>.log(results); <span class="hljs-comment">// Output: ['cats', 'rats']</span>
</code></pre>
<p>Here, the RegEx <code>[cr]at</code> matches words that start with either 'c', or 'r' and are followed by 'at'.</p>
<h3 id="heading-ranges">Ranges:</h3>
<p>Ranges allow you to specify a range of characters within a set. For example, <code>[a-z]</code> matches any lowercase letter from 'a' to 'z', and <code>[0-9]</code> matches any digit from '0' to '9'. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'Hello World!'</span>;
<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/[a-z]/g</span>;
<span class="hljs-keyword">let</span> results = str.match(re);

<span class="hljs-built_in">console</span>.log(results); <span class="hljs-comment">// Output: ['e', 'l', 'l', 'o', 'o', 'r', 'l', 'd']</span>
</code></pre>
<h3 id="heading-negating-excluding-ranges">Negating / Excluding Ranges:</h3>
<p>To exclude certain characters from a set, you can use the <code>^</code> symbol inside the square brackets. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'The price is $19.99'</span>;
<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/[^0-9]/g</span>;
<span class="hljs-keyword">let</span> results = str.match(re);

<span class="hljs-built_in">console</span>.log(results); <span class="hljs-comment">// Output: ['T', 'h', 'e', ' ', 'p', 'r', 'i', 'c', 'e', ' ', 'i', 's', ' ', '$', '.']</span>
</code></pre>
<p>Similarly <code>[^a-z]</code> will match any character that is not a lowercase letter:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'The price is $19.99'</span>;
<span class="hljs-keyword">let</span> results2 = str.match(<span class="hljs-regexp">/[^a-z]/g</span>);

<span class="hljs-built_in">console</span>.log(results2); <span class="hljs-comment">// Output: ['T', ' ', ' ', ' ', '$', '1', '9', '.', '9', '9']</span>
</code></pre>
<h3 id="heading-predefined-character-classes">Predefined Character Classes:</h3>
<p>Some character classes have predefined shorthand notations for common ranges of characters. </p>
<p><strong><code>\d</code> class</strong>: It matches any digit character, equivalent to the range <code>[0-9]</code>. Example: </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> phone = <span class="hljs-string">'+1-(103)-777-0101'</span>;
<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/\d/g</span>;
<span class="hljs-keyword">let</span> numbers = phone.match(re);
<span class="hljs-keyword">let</span> phoneNo = numbers.join(<span class="hljs-string">''</span>);
<span class="hljs-built_in">console</span>.log(phoneNo); <span class="hljs-comment">// Output: 11037770101</span>
</code></pre>
<p>We used the <code>match()</code> and <code>join()</code> methods to format the phone number. This approach simplifies the process of formatting and cleaning up data, making it suitable for various text processing applications.</p>
<p>Similarly, <code>**\s**</code> matches a single whitespace character, including spaces, tabs, and newline characters, and <code>**\w**</code> matches any word character (alphanumeric character or underscore), equivalent to the range <code>[a-zA-Z0-9_]</code>.</p>
<p>Combining these classes allows for more flexible and precise pattern matching, enabling a wide range of text processing tasks. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'O2 is oxygen'</span>;
<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/\w\d/g</span>;
<span class="hljs-built_in">console</span>.log(str.match(re)); <span class="hljs-comment">// Output: ["O2"]</span>
</code></pre>
<p>These predefined character classes provide convenient shortcuts for commonly used character ranges.</p>
<p><strong>Inverse classes</strong>, denoted by uppercase letters (for example, <code>\D</code>), match any character not included in the corresponding lowercase class. This provides a convenient way to match characters outside specific sets, such as non-digit characters, non-whitespace characters, or non-word characters. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> phone = <span class="hljs-string">'+1-(103)-777-0101'</span>;
<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/\D/g</span>;
<span class="hljs-built_in">console</span>.log(phone.replace(re,<span class="hljs-string">''</span>)); <span class="hljs-comment">// Output: 11037770101</span>
</code></pre>
<h2 id="heading-special-characters-and-escaping-in-regex">Special Characters and Escaping in Regex</h2>
<h3 id="heading-metacharacters">Metacharacters:</h3>
<p>Metacharacters are characters that have special meanings in Regular Expressions and are used to construct patterns for matching text. </p>
<p>Anchors (<code>^</code> and <code>$</code>), Alternation(<code>|</code>), quantifiers (<code>+</code>, <code>?</code>, <code>{}</code>), and predefined character classes ( <code>\d</code>, <code>\w</code>, <code>\s</code>) are all considered metacharacters, each serving distinct purposes in pattern definition. We also have a few more, which we'll cover now.</p>
<p><strong>Dot (<code>.</code>)</strong> is a metacharacter with a special meaning. It's used to match any single character except newline characters (<code>\n</code>). It serves as a wildcard, allowing for flexible pattern matching when the exact character is unknown or irrelevant. </p>
<p>If you need the dot to match newline characters as well, you can use the <code>/s</code> flag in JavaScript, which enables the "single line" mode, making the dot match any character including newline characters. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> regex = <span class="hljs-regexp">/a.b/</span>; 

<span class="hljs-built_in">console</span>.log(regex.test(<span class="hljs-string">'acb'</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(regex.test(<span class="hljs-string">'aXb'</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(regex.test(<span class="hljs-string">'a\nb'</span>)); <span class="hljs-comment">// false (newline character not matched)</span>
<span class="hljs-built_in">console</span>.log(regex.test(<span class="hljs-string">'a\nb'</span>, <span class="hljs-string">'s'</span>)); <span class="hljs-comment">// true (with 's' flag, newline character matched)</span>
<span class="hljs-built_in">console</span>.log(regex.test(<span class="hljs-string">'ab'</span>)); <span class="hljs-comment">// false (missing character between 'a' and 'b')</span>
</code></pre>
<p>The dot (<code>.</code>) can be combined with other regex elements to form more complex patterns. For example, <code>/.at/</code> matches any three-character sequence ending with 'at', such as 'cat', 'bat', or 'hat'.</p>
<h3 id="heading-escape-special-characters">Escape Special Characters:</h3>
<p>Escaping special characters is essential when you want to search for or match these characters in input strings without invoking their special regex meanings. </p>
<p>To match a special character literally in a regex pattern, you need to escape it by preceding it with a backslash (). This tells the regex engine to treat the special character as a regular character. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'This ^ symbol is called Caret '</span>;
<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/[\^]/g</span>;
<span class="hljs-keyword">let</span> results = str.match(re);

<span class="hljs-built_in">console</span>.log(results); <span class="hljs-comment">// Output: ['^']</span>
</code></pre>
<p>Fun fact: the <code>/</code> we use to escape metacharacters is itself a metacharacter and can be escaped with another backslash as <code>//</code>.</p>
<h2 id="heading-groupings-in-regex">Groupings in RegEx</h2>
<h3 id="heading-capturing-groups">Capturing Groups:</h3>
<p>In JavaScript regular expressions, capturing groups are used to extract specific parts of a matched string. Imagine you have a path like "resource/id", for instance, "posts/123". To match this path, you can use a regular expression like <code>/\w+\/\d+/</code>.</p>
<ul>
<li><code>\w+</code> matches one or more word characters.</li>
<li><code>\/</code> matches the forward slash <code>/</code>.</li>
<li><code>\d+</code> matches one or more digits.</li>
</ul>
<p>Let's say you have a path like "posts/123" and you want to capture the <code>id</code> part (123). We can use capturing groups for this.</p>
<p>To create a capturing group, you enclose the part of the regex pattern you want to capture in parentheses. For example, <code>(\d+)</code> captures one or more digits.</p>
<p>Here's how it works:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> path = <span class="hljs-string">'posts/123'</span>;
<span class="hljs-keyword">const</span> pattern = <span class="hljs-regexp">/\w+\/(\d+)/</span>;

<span class="hljs-keyword">const</span> match = path.match(pattern);
<span class="hljs-built_in">console</span>.log(match);
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">[ <span class="hljs-string">'posts/123'</span>, <span class="hljs-string">'123'</span>, index: 0, input: <span class="hljs-string">'posts/123'</span>, groups: undefined ]
</code></pre>
<p>Here, <code>'123'</code> is captured by the capturing group <code>(\d+)</code>.</p>
<p><strong>Using Multiple Capturing Groups</strong>: You can have multiple capturing groups in a regex pattern. For example, to capture both the resource (like "posts") and the id (like "123") from the path "posts/123", you can use <code>/(\w+)\/(\d+)/</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> path = <span class="hljs-string">'posts/123'</span>;
<span class="hljs-keyword">const</span> pattern = <span class="hljs-regexp">/(\w+)\/(\d+)/</span>;

<span class="hljs-keyword">const</span> match = path.match(pattern);
<span class="hljs-built_in">console</span>.log(match);
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">[<span class="hljs-string">'posts/123'</span>, <span class="hljs-string">'posts'</span>, <span class="hljs-string">'123'</span>, index: 0, input: <span class="hljs-string">'posts/123'</span>, groups: undefined]
</code></pre>
<p>Here, <code>'posts'</code> and <code>'</code>123<code>'</code> are captured by the two capturing groups <code>(\w+)</code> and <code>(\d+)</code> respectively.</p>
<p><strong>Named Capturing Groups</strong> allow you to assign names to capturing groups, which makes it easier to reference them later in your code.</p>
<p>The syntax for named capturing groups is <code>(?&lt;name&gt;rule)</code>, where:</p>
<ul>
<li><code>()</code> indicates a capturing group.</li>
<li><code>?&lt;name&gt;</code> specifies the name of the capturing group.</li>
<li><code>rule</code> is a rule in the pattern.</li>
</ul>
<p>For example, suppose we want to capture the resource (like "posts") and the id (like "123") from the path "posts/123" using named capturing groups.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> path = <span class="hljs-string">'posts/123'</span>;
<span class="hljs-keyword">const</span> pattern = <span class="hljs-regexp">/(?&lt;resource&gt;\w+)\/(?&lt;id&gt;\d+)/</span>;

<span class="hljs-keyword">const</span> match = path.match(pattern);
<span class="hljs-built_in">console</span>.log(match);
</code></pre>
<p>Output:</p>
<pre><code class="lang-javascript">[
  <span class="hljs-string">'posts/123'</span>,
  <span class="hljs-string">'posts'</span>,
  <span class="hljs-string">'123'</span>,
  <span class="hljs-attr">index</span>: <span class="hljs-number">0</span>,
  <span class="hljs-attr">input</span>: <span class="hljs-string">'posts/123'</span>,
  <span class="hljs-attr">groups</span>: [<span class="hljs-built_in">Object</span>: <span class="hljs-literal">null</span> prototype] { <span class="hljs-attr">resource</span>: <span class="hljs-string">'posts'</span>, <span class="hljs-attr">id</span>: <span class="hljs-string">'10'</span> }
]
</code></pre>
<p>Here, <code>resource</code> and <code>id</code> are the names assigned to the capturing groups. We can access them using <code>match.groups</code>.</p>
<p><strong>Another Example</strong>: Let's say we have a path like "posts/2022/02/18" and we want to capture the resource (like "posts"), year (like "2022"), month (like "02"), and day (like "18") using named capturing groups.</p>
<p>The regex pattern for this would be:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> path = <span class="hljs-string">'posts/2024/02/22'</span>;
<span class="hljs-keyword">const</span> pattern =
  <span class="hljs-regexp">/(?&lt;resource&gt;\w+)\/(?&lt;year&gt;\d{4})\/(?&lt;month&gt;\d{2})\/(?&lt;day&gt;\d{2})/</span>;

<span class="hljs-keyword">const</span> match = path.match(pattern);
<span class="hljs-built_in">console</span>.log(match.groups);
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">{resource: <span class="hljs-string">'posts'</span>, year: <span class="hljs-string">'2024'</span>, month: <span class="hljs-string">'02'</span>, day: <span class="hljs-string">'22'</span>}
</code></pre>
<p>Here, each part of the path is captured using named capturing groups, making it easy to access them by their respective names.</p>
<h3 id="heading-non-capturing-groups">Non-capturing groups:</h3>
<p>In regular expressions, non-capturing groups are used to group parts of a pattern together for applying quantifiers or alternation, without capturing the matched substring. </p>
<p>To create a non-capturing group, you add <code>?:</code> at the beginning of the parentheses. So, <code>/(?:\d)+/</code> is the non-capturing version of the previous example. The <code>?:</code> tells the regex engine not to capture the matched substring.</p>
<p>Let's see the difference between capturing and non-capturing groups with an example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// capturing group</span>
<span class="hljs-keyword">const</span> regexWithCapture = <span class="hljs-regexp">/(\d{2})\/(\d{2})\/(\d{4})/</span>;
<span class="hljs-keyword">const</span> matchWithCapture = regexWithCapture.exec(<span class="hljs-string">'02/26/2024'</span>);

<span class="hljs-built_in">console</span>.log(matchWithCapture); <span class="hljs-comment">// ["02/26/2024", "02", "26", "2024"]</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">// non-capturing group</span>
<span class="hljs-keyword">const</span> regexWithoutCapture = <span class="hljs-regexp">/(?:\d{2})\/(?:\d{2})\/(?:\d{4})/</span>;
<span class="hljs-keyword">const</span> matchWithoutCapture = regexWithoutCapture.exec(<span class="hljs-string">'02/26/2024'</span>);

<span class="hljs-built_in">console</span>.log(matchWithoutCapture); <span class="hljs-comment">// ["02/26/2024"]</span>
</code></pre>
<p>In summary, non-capturing groups <code>(?:pattern)</code> behave like regular capturing groups <code>()</code> in terms of matching patterns, but they don't store the matched text in memory for later retrieval. This makes them useful when you don't need to extract specific parts of the matched text.</p>
<h3 id="heading-backreferences">Backreferences:</h3>
<p>Backreferences enable you to refer to previously captured groups within a regular expression. Think of them as variables that store matched patterns. </p>
<p>In JavaScript, the syntax for a backreference is <code>\N</code>, where <code>N</code> is an integer representing the capturing group number.</p>
<p>For instance, consider a string with a duplicate word "Lion" and we want to remove the duplicate word to get <code>'Lion is the King'</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> s = <span class="hljs-string">'Lion Lion is the King'</span>;
</code></pre>
<ul>
<li>First, we match a word using <code>\w+\s+</code>.</li>
<li>Then, we create a capturing group to capture the word using <code>(\w+)\s+</code>.</li>
<li>Next, we use a backreference (<code>\1</code>) to reference the first capturing group.</li>
<li>Finally, we replace the entire match with the first capturing group using <code>String.replace()</code>.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> pattern = <span class="hljs-regexp">/(\w+)\s+\1/</span>;
<span class="hljs-keyword">const</span> result = s.replace(pattern, <span class="hljs-string">'$1'</span>);
<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: 'Lion is the King'</span>
</code></pre>
<h3 id="heading-regex-alternation">Regex Alternation:</h3>
<p>Regex alternation is a feature that allows you to match different patterns within a single regular expression. It works similarly to the logical OR operator. In regex, you use the pipe symbol <code>|</code> to denote alternation, where you can match either A or B.</p>
<pre><code>A | B <span class="hljs-comment">// This means you can match either pattern A or pattern B.</span>
</code></pre><p>Now, let's explore some practical applications of regex alternation:</p>
<p><strong>Matching Time String in the hh:mm Format</strong>: Suppose we want to match time strings in the format hh:mm, where hh represents hours and mm represents minutes. A basic regular expression to match this format would be <code>/\d{2}:\d{2}/</code>. </p>
<p>However, this basic pattern matches invalid times like "99:99". To ensure we match valid times (hours ranging from 00 to 23 and minutes ranging from 00 to 59), we need to refine our regex using alternation.</p>
<p>To match valid hours (00 to 23), we can use the following pattern:</p>
<ul>
<li><code>[01]\d</code> matches numbers from 00 to 19.</li>
<li><code>2[0-3]</code> matches numbers from 20 to 23.</li>
</ul>
<p>So, the pattern for hours becomes <code>[01]\d|2[0-3]</code>.</p>
<p>To match valid minutes (00 to 59), we can use the pattern <code>[0-5]\d</code>.</p>
<p>Now, we can combine the hour and minute patterns using alternation to get the final regex pattern:</p>
<p><code>/([01]\d|2[0-3]):[0-5]\d/g</code></p>
<p>In this pattern:</p>
<ul>
<li><code>([01]\d|2[0-3])</code> matches valid hours.</li>
<li><code>:</code> matches the colon.</li>
<li><code>[0-5]\d</code> matches valid minutes.</li>
</ul>
<p>This regex pattern ensures that we only match valid time strings in the <code>hh:mm</code> format. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> timeString = <span class="hljs-string">'07:23 33:71 21:17 25:81'</span>;
<span class="hljs-keyword">const</span> pattern = <span class="hljs-regexp">/([01]\d|2[0-3]):[0-5]\d/g</span>;
<span class="hljs-keyword">const</span> matches = timeString.match(pattern);

<span class="hljs-built_in">console</span>.log(matches);
</code></pre>
<p><strong>Expected Output</strong>:</p>
<pre><code>[<span class="hljs-string">'07:23'</span>, <span class="hljs-string">'21:17'</span>]
</code></pre><h2 id="heading-lookahead-and-lookbehind-in-regex">Lookahead and Lookbehind in Regex</h2>
<h3 id="heading-lookahead">Lookahead:</h3>
<p>Lookahead in regular expressions allows matching a pattern (X) only if it's followed by another specific pattern (Y). The syntax is <code>X(?=Y)</code>, where:</p>
<ul>
<li><strong>X</strong> is the pattern you want to match.</li>
<li><strong>(?=Y)</strong> is the lookahead assertion indicating that <code>X</code> should be followed by <code>Y</code>.</li>
</ul>
<p><strong>Example</strong>: Let's say we have a string describing various distances, and we want to identify numbers followed by the units "miles" but not "kilometers". We can use lookahead in a regex pattern:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> dist = <span class="hljs-string">"He ran 5 miles, but not 10 kilometers."</span>;

<span class="hljs-keyword">const</span> regex = <span class="hljs-regexp">/\d+(?=\s*miles)/g</span>;

<span class="hljs-built_in">console</span>.log(dist.match(regex)); <span class="hljs-comment">// Output: ["5"]</span>
</code></pre>
<p><strong>Multiple Lookaheads</strong>: It's possible to have multiple lookaheads in a regular expression using the syntax <code>X(?=Y)(?=Z)</code>. This allows us to impose multiple conditions for matching.</p>
<p><strong>Example:</strong> Let's say we want to match strings that contain both "foo" and "bar", but in any order:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> regex = <span class="hljs-regexp">/(?=.*foo)(?=.*bar)/</span>;

<span class="hljs-built_in">console</span>.log(regex.test(<span class="hljs-string">"foobar"</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(regex.test(<span class="hljs-string">"barfoo"</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(regex.test(<span class="hljs-string">"foo"</span>));    <span class="hljs-comment">// false</span>
<span class="hljs-built_in">console</span>.log(regex.test(<span class="hljs-string">"bar"</span>));    <span class="hljs-comment">// false</span>
</code></pre>
<h3 id="heading-negative-lookaheads">Negative Lookaheads:</h3>
<p>To negate a lookahead, use a negative lookahead with the syntax <code>(?!Y)</code>, where the regex engine matches X only if it is not followed by Y.</p>
<p><strong>Example</strong>: Suppose we want to match numbers but not if they are followed by "miles":</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> text = <span class="hljs-string">"He ran 5 miles, but not 10 kilometers."</span>;

<span class="hljs-keyword">const</span> regex = <span class="hljs-regexp">/\d+(?!\s*miles)/g</span>;

<span class="hljs-built_in">console</span>.log(text.match(regex)); <span class="hljs-comment">// Output: ["10"]</span>
</code></pre>
<h3 id="heading-lookbehind">Lookbehind:</h3>
<p>Lookbehinds provide a way to match patterns based on what precedes them, essentially matching an element if there is another specific element before it.</p>
<p><strong>Example</strong>: Suppose we have a string containing prices, and we want to match numbers preceded by the currency symbol "$" but not preceded by "€". We can use a lookbehind in a regex pattern</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> priceString = <span class="hljs-string">"The price is $100, but €200."</span>;

<span class="hljs-keyword">const</span> regex = <span class="hljs-regexp">/(?&lt;=\$)\d+/g</span>;

<span class="hljs-built_in">console</span>.log(priceString.match(regex)); <span class="hljs-comment">// Output: ["100"]</span>
</code></pre>
<p><strong>Explaination</strong>: <code>(?&lt;=\$)</code> matches an element if there is a literal string "$" before it. The backslash <code>\</code> is used to escape the special character "$", treating it as a literal character.</p>
<h3 id="heading-negative-lookbehind">Negative Lookbehind:</h3>
<p>Negative lookbehinds allow you to match a pattern only if it is not preceded by a specific pattern. This is useful for excluding certain patterns from matches based on what precedes them. </p>
<p>Example: Suppose we have a string containing various prices in different currencies, and we want to match the numbers not preceded by the currency symbol "$". We can use a negative lookbehind in a regex pattern:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> priceString = <span class="hljs-string">"The price is $50, but not €100."</span>;

<span class="hljs-keyword">const</span> regex = <span class="hljs-regexp">/(?&lt;!\$)\b\d+\b/g</span>;

<span class="hljs-built_in">console</span>.log(priceString.match(regex)); <span class="hljs-comment">// Output: ["100"]</span>
</code></pre>
<p><strong>Explanation:</strong> <code>(?&lt;!\$)</code> is the negative lookbehind syntax, which matches the following pattern only if it is not preceded by the literal string "$".</p>
<h2 id="heading-practical-examples-and-use-cases-of-regex">Practical Examples and Use Cases of Regex</h2>
<p>Now, Let's explore some practical examples of using regular expressions in JavaScript applications to solve common problems and perform text manipulation tasks.</p>
<h3 id="heading-password-strength-checking">Password Strength Checking:</h3>
<p>You can use regular expressions to enforce password strength requirements, such as minimum length and the presence of special characters.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">checkPasswordStrength</span>(<span class="hljs-params">password</span>) </span>{
    <span class="hljs-keyword">let</span> pattern = <span class="hljs-regexp">/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&amp;*]).{8,}$/</span>;
    <span class="hljs-keyword">return</span> pattern.test(password);
}

<span class="hljs-built_in">console</span>.log(checkPasswordStrength(<span class="hljs-string">"Passw0rd!"</span>));    <span class="hljs-comment">// Output: true</span>
<span class="hljs-built_in">console</span>.log(checkPasswordStrength(<span class="hljs-string">"weakpassword"</span>)); <span class="hljs-comment">// Output: false</span>
</code></pre>
<p>Here's what this pattern does:</p>
<ul>
<li><code>(?=.*\d)</code>: Requires at least one digit.</li>
<li><code>(?=.*[a-z])</code>: Requires at least one lowercase letter.</li>
<li><code>(?=.*[A-Z])</code>: Requires at least one uppercase letter.</li>
<li><code>(?=.*[!@#$%^&amp;*])</code>: Requires at least one special character.</li>
<li><code>.{8,}</code>: Requires a minimum length of 8 characters.</li>
</ul>
<h3 id="heading-email-validation-function">Email Validation Function:</h3>
<p>Email validation is crucial for ensuring data integrity and security in web applications. With regex methods, we can easily implement robust email validation mechanisms.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">validateEmail</span>(<span class="hljs-params">email</span>) </span>{
    <span class="hljs-keyword">const</span> emailRegex = <span class="hljs-regexp">/^[^\s@]+@[^\s@]+\.[^\s@]+$/</span>;
    <span class="hljs-keyword">return</span> emailRegex.test(email);
}

<span class="hljs-built_in">console</span>.log(validateEmail(<span class="hljs-string">"example@email.com"</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(validateEmail(<span class="hljs-string">"invalid-email"</span>));      <span class="hljs-comment">// false</span>
</code></pre>
<p>Here's what this pattern does:</p>
<ul>
<li><code>^</code>: Asserts the start of the string.</li>
<li><code>[^\s@]+</code>: Matches one or more characters that are not whitespace or '@'.</li>
<li><code>@</code>: Matches the '@' symbol.</li>
<li><code>[^\s@]+</code>: Matches one or more characters that are not whitespace or '@'.</li>
<li><code>\.</code>: Matches the '.' symbol (escaped because '.' has a special meaning in RegEx).</li>
<li><code>[^\s@]+</code>: Matches one or more characters that are not whitespace or '@'.</li>
<li><code>$</code>: Asserts the end of the string.</li>
</ul>
<h3 id="heading-phone-number-formatting-function">Phone Number Formatting Function:</h3>
<p>Phone number formatting enhances user experience and readability in applications that involve phone number input and display.  </p>
<p>By defining a regex pattern that matches phone number components, we can easily format phone numbers into a desired pattern using the <code>replace()</code> method.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">formatPhoneNumber</span>(<span class="hljs-params">phoneNumber</span>) </span>{
    <span class="hljs-keyword">const</span> phoneRegex = <span class="hljs-regexp">/(\d{3})(\d{3})(\d{4})/</span>;
    <span class="hljs-keyword">return</span> phoneNumber.replace(phoneRegex, <span class="hljs-string">"($1) $2-$3"</span>);
}

<span class="hljs-keyword">const</span> formattedNumber = formatPhoneNumber(<span class="hljs-string">"9876543210"</span>);
<span class="hljs-built_in">console</span>.log(formattedNumber); <span class="hljs-comment">// (987) 654-3210</span>
</code></pre>
<p>In the <code>replace()</code> method, <code>$1</code>, <code>$2</code>, and <code>$3</code> represent the captured groups in the RegEx pattern, corresponding to the three sets of digits in the phone number.</p>
<h2 id="heading-tips-and-best-practices-for-using-regular-expressions">Tips and Best Practices for Using Regular Expressions</h2>
<h4 id="heading-1-understand-regular-expression-syntax">1. Understand Regular Expression Syntax:</h4>
<p>Understand the syntax and metacharacters of regular expressions for effective usage.</p>
<h4 id="heading-2-test-regular-expressions">2. Test Regular Expressions:</h4>
<p>Regular expressions can sometimes behave unexpectedly due to complex patterns or special characters. Always test your regular expressions with different input strings to ensure they behave as expected in various scenarios.</p>
<h4 id="heading-3-optimize-performance">3. Optimize Performance:</h4>
<p>Consider optimizing your regular expressions for performance by simplifying patterns or using more efficient alternatives where possible.</p>
<h4 id="heading-4-use-built-in-methods">4. Use Built-in Methods:</h4>
<p>JavaScript provides built-in methods like <code>String.prototype.match()</code>, <code>String.prototype.replace()</code>, and <code>String.prototype.split()</code> for common string manipulation tasks. Evaluate whether these methods can accomplish your task without the need for regular expressions.</p>
<h4 id="heading-5-comment-your-regular-expressions">5. Comment Your Regular Expressions:</h4>
<p>Add comments within your regex using <code>(?#comment)</code> syntax to explain explain parts of complex patterns. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> regex = <span class="hljs-regexp">/(\d{3})-(\d{3})-(\d{4})\s(?# Match a phone number in the format XXX-XXX-XXXX)/</span>;
</code></pre>
<h4 id="heading-6-break-down-complex-patterns">6. Break Down Complex Patterns:</h4>
<p>If your regular expression becomes too complex to understand or maintain, consider breaking it down into smaller, more manageable parts. Use variables to store individual components of the pattern and combine them as needed.</p>
<h4 id="heading-7-use-online-resources-and-keep-on-practicing">7. Use Online Resources and Keep on Practicing:</h4>
<p>There are several online resources and tools available for testing and learning regular expressions. Websites like <a target="_blank" href="https://regex101.com/">Regex101</a> and <a target="_blank" href="https://regexr.com/">RegExr</a> provide interactive platforms to test and debug regular expressions. Also leverage online tutorials and documentation to learn regex concepts.</p>
<p>The MDN Web Docs have a helpful guide to <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions">Regular Expressions here</a>. And here's a quick start guide to regular expressions in JavaScript: <a target="_blank" href="https://www.freecodecamp.org/news/a-quick-and-simple-guide-to-javascript-regular-expressions-48b46a68df29/">RegExp Tutorial</a>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Regular expressions are versatile tools for pattern matching and manipulation in JavaScript. </p>
<p>By understanding their methods, advanced features, and usage with flags, leveraging online resources and debugging tools, you can effectively learn and apply them in various scenarios, from simple pattern matching to complex text processing tasks.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript in the Browser – How the Document Object Model (DOM) and Events Work ]]>
                </title>
                <description>
                    <![CDATA[ In this in-depth tutorial, you'll learn all about the Document Object Model, or DOM for short. As a web developer, understanding the DOM is fundamental for interacting with web browsers and creating dynamic web applications.  Throughout this guide, w... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-in-the-browser-dom-and-events/</link>
                <guid isPermaLink="false">66c7218887ceefbdaf9b921b</guid>
                
                    <category>
                        <![CDATA[ browser ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Document Object Model ]]>
                    </category>
                
                    <category>
                        <![CDATA[ DOM ]]>
                    </category>
                
                    <category>
                        <![CDATA[ events ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Samyak Jain ]]>
                </dc:creator>
                <pubDate>Thu, 15 Feb 2024 20:07:14 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/JavaScript-in-the-Browser-with-Photo-Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this in-depth tutorial, you'll learn all about the Document Object Model, or DOM for short. As a web developer, understanding the DOM is fundamental for interacting with web browsers and creating dynamic web applications. </p>
<p>Throughout this guide, we will explore the DOM's hierarchical tree structure, essential properties, and methods for accessing and modifying nodes. We'll also dive into event handling and various techniques for efficient DOM manipulation.</p>
<p>By the end of this guide, you should be able to confidently manipulate the DOM to meet the demands of your web development projects.</p>
<h3 id="heading-prerequisites">Prerequisites:</h3>
<p>While this guide is designed to be beginner-friendly and accessible to anyone, having a basic understanding of JavaScript fundamentals will greatly enhance your ability to grasp the practical concepts covered. </p>
<p>Also, familiarity with HTML and CSS is a plus and will help you comprehend and apply the material we cover. </p>
<p>If you're new to JavaScript, consider familiarizing yourself with variables, data types, functions, loops, and basic DOM manipulation techniques before diving into this tutorial. This foundational knowledge will ensure a smoother learning experience as we explore more advanced topics related to the Document Object Model (DOM).</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#browser-object-model-bom-">What is the Browser Object Model (BOM)</a>?</li>
<li><a class="post-section-overview" href="#what-is-the-document-object-model-dom">What is the Document Object Model (DOM)?</a></li>
<li><a class="post-section-overview" href="#heading-dom-tree-structure">DOM Tree Structure</a><br>– <a class="post-section-overview" href="#heading-types-of-nodes-in-the-dom-tree">Types of Nodes in the DOM Tree</a><br>– <a class="post-section-overview" href="#heading-node-relationships">Node Relationships</a></li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-dom-elements">How to Work with DOM Elements</a><br>– <a class="post-section-overview" href="#methods-for-traversing-the-dom-">Traversing the DOM</a><br>– <a class="post-section-overview" href="#heading-methods-for-querying-dom-elements">Methods for Querying DOM Elements</a><br>– <a class="post-section-overview" href="#heading-matches-closest-and-contains">Specialized Selectors (Matches, Closest, Contains)</a><br>– <a class="post-section-overview" href="#heading-how-to-inspect-dom-elements">How to Inspect DOM Elements</a><br>– <a class="post-section-overview" href="#heading-table-navigation-in-the-dom">Table Navigation in the DOM</a></li>
<li><a class="post-section-overview" href="#heading-how-to-modify-dom-elements">How to Modify DOM Elements</a><br>– <a class="post-section-overview" href="#heading-how-to-manipulate-element-content-and-visibility">How to Manipulate Element Content and Visibility</a><br>– <a class="post-section-overview" href="#heading-how-to-modify-element-attributes">How to Modify Element Attributes</a><br>– <a class="post-section-overview" href="#heading-html-insertion-methods">HTML Insertion Methods</a><br>– <a class="post-section-overview" href="#heading-how-to-manipulate-classes-with-javascript">How to Manipulate Classes with JavaScript</a></li>
<li><a class="post-section-overview" href="#heading-event-handling-in-the-dom">Event Handling in the DOM</a><br>– <a class="post-section-overview" href="#heading-common-types-of-events">Common Types of Events</a><br>– <a class="post-section-overview" href="#heading-event-handlers">Event Handlers</a><br>– <a class="post-section-overview" href="#heading-event-propagation">Event Propagation</a><br>– <a class="post-section-overview" href="#heading-event-bubbling">Event Bubbling</a><br>– <a class="post-section-overview" href="#heading-event-delegation">Event Delegation</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<h2 id="heading-what-is-the-browser-object-model-bom">What is the Browser Object Model (BOM)?</h2>
<p>The Browser Object Model is like a set of tools provided by the browser itself. It's not part of the official DOM specification, but it's specific to web browsers. As a result, the objects and methods available in the BOM may vary between different browsers.</p>
<p>The BOM provides JavaScript access to browser-specific things like the browser's history, location, and browser window itself.</p>
<h3 id="heading-window-object">Window Object</h3>
<p>The <code>window</code> Object serves as a global object in the browser, representing the browser window and is the top-level object in JavaScript when we're working in a web browser. You can access it by typing <code>window</code> in the browser console:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">window</span>); <span class="hljs-comment">// prints the Window object</span>
</code></pre>
<p>Since, it's global, you can access it from anywhere and use it to access other global objects such as the console and the alert function.</p>
<p>The <code>window</code> object is a key part of the BOM and provides access to many browser-related things. For example, <code>window.location.href</code> gives you the URL of the current web page.</p>
<p>Functions like <code>alert()</code>, <code>prompt()</code>, and <code>confirm()</code> are also part of the BOM, allowing you to interact with users through pop-up dialogs.</p>
<h2 id="heading-what-is-the-document-object-model-dom">What is the Document Object Model (DOM)?</h2>
<p>The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of a web page, allowing interaction with its elements using programming languages like JavaScript.</p>
<p>The DOM contains the <code>document</code> object, which represents the DOM structure of the current web page and has properties and methods that allow you to manipulate the DOM.</p>
<p>You can access the <code>document</code> object by typing <code>document</code> in the browser console:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">document</span>); <span class="hljs-comment">// prints the DOM object</span>
</code></pre>
<p>You use <code>document</code> object to access and manipulate different parts of the HTML document. Elements within the DOM can be accessed using properties and methods of this object.</p>
<p>Examples include accessing the <code>body</code> or <code>title</code> element, retrieving HTML content (<code>innerHTML</code>), accessing text content (<code>innerText</code>) and changing <code>styles</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Accessing the document's title</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">document</span>.title);

<span class="hljs-comment">// Changing the document's title</span>
<span class="hljs-built_in">document</span>.title = <span class="hljs-string">"changed Title"</span>;

<span class="hljs-comment">// Accessing the document's body </span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">document</span>.body);
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">// Changing background color of body element using inline CSS</span>
<span class="hljs-built_in">document</span>.body.style.backgroundColor = <span class="hljs-string">"red"</span>;
</code></pre>
<p>You can use the DOM to interact with web pages dynamically. This allows JavaScript to access, modify, and manipulate the content, structure, and style of a web document in response to user actions or other events. </p>
<p>Let's illustrate the concept of DOM manipulation with a simple example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"container"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"message"</span>&gt;</span>Hello, World!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"changeText"</span>&gt;</span>Change Text<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
      <span class="hljs-comment">// we select the paragraph element by its ID</span>
      <span class="hljs-keyword">let</span> messageElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"message"</span>);

      <span class="hljs-comment">// let's add event listener to button element using ID</span>
      <span class="hljs-built_in">document</span>
        .getElementById(<span class="hljs-string">"changeText"</span>)
        .addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
          <span class="hljs-comment">// this  will change the text content of the paragraph element</span>
          messageElement.textContent = <span class="hljs-string">"Text Changed!"</span>;
        });
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>In this example, we have an HTML document with a <code>&lt;div&gt;</code> container containing a <code>&lt;p&gt;</code> element and a <code>&lt;button&gt;</code> element. </p>
<p>Using JavaScript, we can select the <code>&lt;p&gt;</code> element by its ID and attach an event listener to the <code>&lt;button&gt;</code> element. When the button is clicked, the text content of the paragraph element is changed dynamically.</p>
<h2 id="heading-dom-tree-structure">DOM Tree Structure</h2>
<p>The DOM represents the layout of HTML and XML documents as a tree-like structure, resembling the hierarchical arrangement of elements on a web page. In this tree, each node represents a part of the document, such as HTML elements, attributes, and text.</p>
<p>The top-level node in the tree is called the <strong>document node</strong>, which represents the entire HTML document. From there, it branches out to include all elements and their relationships within the document. Here's a visual representation of that:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/pic_htmltree-1.gif" alt="Image" width="600" height="400" loading="lazy">
<em>DOM Tree of Objects</em></p>
<h3 id="heading-types-of-nodes-in-the-dom-tree">Types of Nodes in the DOM Tree</h3>
<p>There are two main types of nodes in the DOM:</p>
<ol>
<li><strong>Element Nodes:</strong> Represent HTML elements such as <code>&lt;div&gt;</code>, <code>&lt;h1&gt;</code>, <code>&lt;p&gt;</code>, <code>&lt;span&gt;</code>, and so on. These nodes make up the backbone of the DOM tree and form the structure of the HTML document.</li>
<li><strong>Text Nodes:</strong> Represent text content within HTML elements. Text always serves as the last child (leaf node) of an element node and cannot contain any child nodes.</li>
</ol>
<p>In HTML, whitespace such as spaces, tabs, and line breaks are considered part of the text content within HTML elements and are represented as <strong>text nodes</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/image-62.png" alt="Image" width="600" height="400" loading="lazy">
<em>Linebreak is 1st child node, div (Blue) is 2nd, linebreak again 3rd</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/image-64.png" alt="Image" width="600" height="400" loading="lazy">
<em>We can see all the nodes here including non-element ones (like text nodes or comment nodes)</em></p>
<p>We also have:</p>
<ul>
<li><strong>Attribute Nodes:</strong> Represent attributes of HTML elements, for example <code>id</code>, <code>class</code>, <code>src</code>, <code>href</code>, and so on.</li>
<li><strong>Comment Nodes:</strong> Nodes representing comments within the HTML markup.</li>
</ul>
<p>To access and manipulate DOM elements, we can "walk" through the tree structure using JavaScript. For instance:</p>
<ul>
<li><code>document.head</code>: Selects the <code>&lt;head&gt;</code> element of the current HTML document.</li>
<li><code>document.body</code>: Selects the <code>&lt;body&gt;</code> element of the current HTML document.</li>
<li><code>document.documentElement</code>: Selects the root element of the DOM tree, that is <code>&lt;html&gt;</code>.</li>
</ul>
<p>Once we access an element, we can modify its attributes or properties accordingly. For example, we can alter the background color of the <code>&lt;body&gt;</code> element to red by executing <code>document.body.style.backgroundColor = "red"</code> in the console.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/image-80.png" alt="Image" width="600" height="400" loading="lazy">
<em>We can see the body color has changed to "red"</em></p>
<h3 id="heading-node-relationships">Node Relationships</h3>
<p>Nodes in the DOM tree have parent-child relationships, which form the hierarchical structure of the tree. A child is an element that directly resides within another element (the parent).</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"container"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Hello, World!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Click Me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>In the DOM tree, sibling elements are arranged linearly. The element to the right of the current element is called the next sibling, while the element to the left is called the previous sibling.</p>
<p>In the above example, the <code>&lt;p&gt;</code> element (previous sibling of ) and the <code>&lt;button&gt;</code> element (next sibling of </p><p>) are <strong>sibling nodes</strong> as they share the same parent. They are both <strong>children nodes</strong> of the <code>&lt;div&gt;</code> element with the ID "container". So the <code>&lt;div&gt;</code> element serves as the <strong>parent node</strong> of both the <code>&lt;p&gt;</code> and <code>&lt;button&gt;</code> elements.</p>
<p>Elements positioned above a given element in the DOM tree hierarchy are called ancestors. In the given code, the <code>&lt;html&gt;</code> element acts as the <strong>ancestor</strong> of the <code>&lt;body&gt;</code>, <code>&lt;h1&gt;</code>, and <code>&lt;p&gt;</code> elements, and they are <strong>descendants</strong> of the <code>&lt;html&gt;</code> element.</p>
<h2 id="heading-how-to-work-with-dom-elements">How to Work with DOM Elements</h2>
<p>Now, let's dive into accessing nodes in the DOM using various properties and methods.</p>
<h3 id="heading-traversing-the-dom">Traversing the DOM:</h3>
<p>When working with the Document Object Model (DOM), it's important to understand the distinction between element nodes (HTML elements) and non-element nodes (like text nodes, comments, and so on). Certain properties and methods specifically deal with either element nodes or all types of nodes, including non-element nodes.</p>
<p><strong>NodeList vs. HTMLCollection:</strong> Different properties return different collections of nodes. NodeList contains all types of nodes, while HTMLCollection specifically holds element nodes. Understanding this distinction is crucial for interpreting the results.</p>
<p><strong>Properties for All Nodes (Including Non-element Nodes):</strong> These properties return nodes of all types, including element nodes, text nodes, and comment nodes. </p>
<p><code>childNodes</code> returns a NodeList containing all child nodes and the <code>parentNode</code> property returns the parent node of the specified node. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Access the first child of the body node</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">document</span>.body.childNodes[<span class="hljs-number">0</span>]);


<span class="hljs-comment">// parentnode; the parent of a &lt;p&gt; element within a &lt;div&gt; would be the &lt;div&gt; itself.</span>
<span class="hljs-keyword">let</span> p = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'p'</span>); <span class="hljs-comment">// Select the &lt;p&gt; element</span>
<span class="hljs-built_in">console</span>.log(p.parentNode); <span class="hljs-comment">// Output: &lt;div&gt; element (parent of p);</span>
</code></pre>
<p>Spaces between tags and line returns in HTML code are considered text nodes by the browser. So, the actual first child node might not be what you expect.</p>
<p><code>firstChild</code>/<code>lastChild</code>: Returns the first/last child node, again including all types.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.body.firstChild; <span class="hljs-comment">// Outputs: First child node (likely a linebreak(text node))</span>
<span class="hljs-built_in">document</span>.body.lastChild; <span class="hljs-comment">// Outputs: Last child node (likely a script tag)</span>
</code></pre>
<p>So we can say the following:</p>
<pre><code class="lang-javascript">element.childNodes[<span class="hljs-number">0</span>] === element.firstChild;
element.childNodes[element.childNodes.length - <span class="hljs-number">1</span>] === element.lastChild;
</code></pre>
<p><code>nextSibling</code>/<code>previousSibling</code>: returns the next sibling/previous sibling node,  including all of them.</p>
<p><strong>Element specific properties or Element only navigation</strong>: These properties provide a convenient way to access only element nodes, excluding text nodes and comments.</p>
<p><code>children</code> returns a live HTMLCollection of direct child elements, and the <code>parentElement</code> property returns the parent element node of the specified node.</p>
<p>In the below screenshot, you can see the difference between <code>childNodes</code> and <code>children</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/image-62.png" alt="Image" width="600" height="400" loading="lazy">
<em>Here, Linebreak (text node) will be considered 1st child node of body element, whereas div.color (Blue) will be considered the 1st child.</em></p>
<p>For instance, let's say we have this code:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// childnode</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">document</span>.body.childNodes);

<span class="hljs-comment">// children</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">document</span>.body.children);
</code></pre>
<pre><code><span class="hljs-comment">// childnode</span>
NodeList(<span class="hljs-number">19</span>) [text, div.color, text, div.color, text, comment, text, div.color, text, div.color, text, div.color, text, script, text, comment, text, script, text]


<span class="hljs-comment">// children</span>
HTMLCollection(<span class="hljs-number">7</span>) [div.color, div.color, div.color, div.color, div.color, script, script]
</code></pre><p>and, if we refresh the page, the output gets:</p>
<pre><code>NodeList(<span class="hljs-number">14</span>) [text, div.color, text, div.color, text, comment, text, div.color, text, div.color, text, div.color, text, script]
HTMLCollection(<span class="hljs-number">6</span>) [div.color, div.color, div.color, div.color, div.color, script]
</code></pre><p>Initially, the <code>NodeList</code> contains 19 nodes. These nodes consist of text nodes, <code>div</code> elements with the class "color", a comment node, and <code>script</code> elements. The <code>HTMLCollection</code> contains 7 elements, which are the <code>div</code> elements with the class "color" and <code>script</code> elements.</p>
<p>When the page is refreshed, some elements or nodes are removed or modified dynamically through JavaScript or other means, leading to the observed changes in the DOM structure.</p>
<p><code>firstElementChild</code>/<code>lastElementChild</code> returns the first/last child, excluding non-element nodes.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Both will exclude text nodes and comment nodes.</span>
<span class="hljs-built_in">document</span>.body.firstElementChild; <span class="hljs-comment">// Outputs: &lt;div class="color"&gt;</span>
<span class="hljs-built_in">document</span>.body.lastElementChild; <span class="hljs-comment">// Outputs: &lt;script src="script.js"&gt;</span>
</code></pre>
<p><strong>Key Points:</strong></p>
<ul>
<li>Choose the right property based on whether you need to target all nodes or specifically element nodes.</li>
<li>Remember that properties like <code>firstChild</code> and <code>previousSibling</code> might return element and non-element nodes, while their element-specific counterparts (<code>firstElementChild</code> and <code>previousElementSibling</code>) focus only on elements.</li>
</ul>
<h3 id="heading-methods-for-querying-dom-elements">Methods for Querying DOM Elements:</h3>
<p>JavaScript provides several methods for accessing elements in the DOM:</p>
<ul>
<li><strong><code>getElementById</code>:</strong> This method retrieves an element by its unique ID attribute.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> element = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"myElement"</span>);
</code></pre>
<ul>
<li><strong><code>getElementsByClassName</code>:</strong> This method returns a collection of elements with the specified class name.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> elements = <span class="hljs-built_in">document</span>.getElementsByClassName(<span class="hljs-string">"myClass"</span>);
</code></pre>
<ul>
<li><strong><code>getElementsByTagName</code>:</strong> This method returns a list of collection of elements with the specified tag name.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> elements = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">"div"</span>);
</code></pre>
<ul>
<li><strong><code>querySelector</code>:</strong> This method retrieves the first element that matches a specified CSS selector.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> element = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"cssSelector"</span>);
</code></pre>
<ul>
<li><strong><code>querySelectorAll</code>:</strong>  This method retrieves all elements that match a CSS                 selector.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> elements = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">"cssSelector"</span>);
</code></pre>
<p>You might be wondering how <code>querySelector</code> differs from <code>querySelectorAll</code>.</p>
<p>Well, <code>querySelector</code> returns the first element within the document that matches the specified selector. On the other hand, <code>querySelectorAll</code> returns a static NodeList representing a list of the document's elements that match the specified group of selectors.</p>
<p>When you're using <code>querySelectorAll</code>, you receive a NodeList, which is similar to an array but not exactly the same. You cannot directly manupulate all elements like appling styles to all elements within a NodeList using methods like <code>style.backgroundColor = 'red'</code>. So we use a <code>forEach</code> loop. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">".box"</span>));

<span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'.box'</span>).forEach(<span class="hljs-function"><span class="hljs-params">element</span> =&gt;</span> {
    <span class="hljs-comment">// Within the forEach loop, we access each element and set its background color to green.</span>
    element.style.backgroundColor = <span class="hljs-string">"green"</span>;
});
</code></pre>
<p>Let's see what's going on in this code:</p>
<ul>
<li>In the first line, we directly change the background color of the element with the class 'box' using querySelector.</li>
<li>In the second line, we use querySelectorAll to select all elements with the class 'box' and log the NodeList to the console.</li>
<li>In third line, since <code>querySelectorAll</code> returns a NodeList, we need to iterate through each element in the NodeList in order to apply the background color to each element separately.</li>
<li>so  basically, we can say <code>querySelector</code> is equivalent to <code>querySelectorAll('section')[0]</code>.</li>
</ul>
<p>Alright, one last method to consider:</p>
<ul>
<li><strong><code>getElementsByName</code></strong>: This method returns a list of collection of elements with the specified name attribute.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> items = <span class="hljs-built_in">document</span>.getElementsByName(<span class="hljs-string">'some-name-attribute'</span>);
<span class="hljs-built_in">console</span>.log(items);
</code></pre>
<p>These methods are important to understand because they are used in various situations. </p>
<p>For example, when we want to select all the <code>div</code> elements in the document, we can use the <code>querySelectorAll</code> method or the <code>getElementsByTagName</code> method. Both methods will return the same result, but <code>querySelectorAll</code> is more flexible because it can select elements that match any CSS selector. <code>getElementsByTagName</code> can only select elements that have the same tag name.</p>
<h3 id="heading-matches-closest-and-contains">Matches, Closest, and Contains:</h3>
<p>When you're working with JavaScript and dealing with web pages, you often need to find specific parts of the page or do things with them. Three methods you might use are <code>matches()</code>, <code>closest()</code>, and <code>contains()</code>.</p>
<p><strong><code>matches()</code></strong> checks if an element matches a certain style rule. For example, if you have a button and you want to see if it has a class of "active", you could use <code>button.matches('.active')</code>. It will return true if the button has that class, and false if it doesn't.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> button = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'button'</span>);
<span class="hljs-keyword">if</span> (button.matches(<span class="hljs-string">'.active'</span>)) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The button is active'</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The button is not active'</span>);
}
</code></pre>
<p>If you have an element and you want to find its nearest parent with a certain class, you can use <code>**closest()**</code> like this: <code>element.closest('.classname')</code>. </p>
<p>For instance, if you have a  link inside a list item and you want to find the nearest list item, you could do <code>link.closest('li')</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> link = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'a'</span>);
<span class="hljs-keyword">const</span> listItem = link.closest(<span class="hljs-string">'li'</span>);
<span class="hljs-built_in">console</span>.log(listItem); <span class="hljs-comment">// This will give you the nearest list item</span>
</code></pre>
<p>And <strong><code>contains()</code></strong> checks if one element is inside another. For example, if you have a div and a paragraph inside it, you could check if the div contains the paragraph with <code>div.contains(paragraph)</code>. It will return true if the paragraph is inside the div, and false if it's not.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> div = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'div'</span>);
<span class="hljs-keyword">const</span> paragraph = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'p'</span>);
<span class="hljs-keyword">if</span> (div.contains(paragraph)) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The div contains a paragraph'</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The div does not contain any paragraph'</span>);
}
</code></pre>
<p>These methods are handy for navigating around your web page and doing different things with its elements.</p>
<h3 id="heading-how-to-inspect-dom-elements">How to Inspect DOM Elements</h3>
<p><strong>Using console.dir():</strong> <code>console.dir()</code> is not a method of the DOM. It's a method provided by the browser's Console API, specifically used for logging JavaScript objects to the console.</p>
<p>If we log an element using <code>console.log()</code>, we see its HTML representation. But with <code>console.dir()</code>, we get an interactive list showing all available attributes and functions for that element.</p>
<p><strong><code>tagName</code></strong> and <code>nodeName</code>: <code>tagName</code> is a property specific to HTML elements. It returns the tag name of an HTML element in uppercase letters. For example, if you have an HTML element <code>&lt;div&gt;</code>, <code>tagName</code> will return <code>"DIV"</code>.</p>
<p>On the other hand, <code>nodeName</code> is a property of DOM nodes that represents the name of the node. For element nodes, it returns the tag name in uppercase. For other types of nodes, it returns a string representing the type of node (for example, "#text" for text nodes, "#comment" for comment nodes).</p>
<p><strong>Discovering a node's type:</strong> Each node in the DOM has a <code>nodeType</code> property that indicates its type. It has a numeric value: <code>1</code> for elements, <code>2</code> for attributes, <code>3</code> for text nodes, <code>8</code> for comment and <code>9</code> for document. Read-only. This property can be used to distinguish between element nodes and text nodes. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> element = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>);
<span class="hljs-built_in">console</span>.log(element.nodeType); <span class="hljs-comment">// Output: 1</span>
</code></pre>
<h3 id="heading-table-navigation-in-the-dom">Table Navigation in the DOM</h3>
<p>Now, let's learn how to navigate a table element and its child nodes using the DOM. Here, instead of manually writing a table, we will use Bootstrap's pre-designed table.</p>
<p>Before diving into table navigation, let's discuss Bootstrap, a popular front-end framework offering pre-designed components and styles for building responsive web pages efficiently.</p>
<p>To integrate Bootstrap into our project, we'll:</p>
<ol>
<li>Copy the pre-designed table from <a target="_blank" href="https://getbootstrap.com/docs/5.3/content/tables/">here</a>.</li>
<li>Paste it into a container <code>&lt;div&gt;</code> in our HTML.</li>
<li>Include Bootstrap's CSS and JS files in our webpage (which you can copy from <a target="_blank" href="https://getbootstrap.com/docs/5.3/getting-started/introduction/">here</a>).</li>
</ol>
<p>Here's how our HTML code will look after integration:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Table Navigation<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"styles.css"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css"</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">integrity</span>=<span class="hljs-string">"sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ"</span> <span class="hljs-attr">crossorigin</span>=<span class="hljs-string">"anonymous"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
   <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- Bootstrap Table --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">table</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"table"</span>&gt;</span>
        <span class="hljs-comment">&lt;!-- Table Header --&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">thead</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">th</span> <span class="hljs-attr">scope</span>=<span class="hljs-string">"col"</span>&gt;</span>#<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">th</span> <span class="hljs-attr">scope</span>=<span class="hljs-string">"col"</span>&gt;</span>First<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">th</span> <span class="hljs-attr">scope</span>=<span class="hljs-string">"col"</span>&gt;</span>Last<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">th</span> <span class="hljs-attr">scope</span>=<span class="hljs-string">"col"</span>&gt;</span>Handle<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">thead</span>&gt;</span>
        <span class="hljs-comment">&lt;!-- Table Body --&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">tbody</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">th</span> <span class="hljs-attr">scope</span>=<span class="hljs-string">"row"</span>&gt;</span>1<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>Mark<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>Otto<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>@mdo<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">th</span> <span class="hljs-attr">scope</span>=<span class="hljs-string">"row"</span>&gt;</span>2<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>Jacob<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>Thornton<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>@fat<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">th</span> <span class="hljs-attr">scope</span>=<span class="hljs-string">"row"</span>&gt;</span>3<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">td</span> <span class="hljs-attr">colspan</span>=<span class="hljs-string">"2"</span>&gt;</span>Larry the Bird<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>@twitter<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">tbody</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">table</span>&gt;</span>
   <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js"</span> <span class="hljs-attr">integrity</span>=<span class="hljs-string">"sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe"</span> <span class="hljs-attr">crossorigin</span>=<span class="hljs-string">"anonymous"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<h4 id="heading-table-navigation-properties">Table navigation properties:</h4>
<p>The table element supports various properties for convenient navigation, such as:</p>
<ul>
<li><code>table.rows</code>: Returns an HTMLCollection of all rows in the table.</li>
<li><code>table.caption</code>: Returns the caption element of the table.</li>
<li><code>table.tHead</code>: Returns the thead element of the table.</li>
<li><code>table.tFoot</code>: Returns the tfoot element of the table.</li>
<li><code>table.tBodies</code>: Returns an HTMLCollection of all tbody elements in the table.</li>
</ul>
<p>Similarly, the tr (table row) element supports properties like:</p>
<ul>
<li><code>tr.cells</code>: Returns an HTMLCollection of all cells in the row.</li>
<li><code>tr.sectionRowIndex</code>: Returns the index of the row in the current section (thead, tbody, or tfoot).</li>
<li><code>tr.rowIndex</code>: Returns the index of the row in the table.</li>
</ul>
<p>The td (table cell) element also supports the <code>td.cellIndex</code> property, returning the index of the cell in the row.</p>
<p>For instance, to print all rows in the table:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> t = <span class="hljs-built_in">document</span>.body.firstElementChild.firstElementChild; <span class="hljs-comment">// Selecting the table</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; t.rows.length; i++) {
    <span class="hljs-keyword">let</span> row = t.rows[i];
    <span class="hljs-built_in">console</span>.log(row)
}
</code></pre>
<p>To print cells in the first row:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> t = <span class="hljs-built_in">document</span>.body.firstElementChild.firstElementChild; <span class="hljs-comment">// Selecting the table</span>
<span class="hljs-keyword">let</span> row = t.rows[<span class="hljs-number">0</span>]; <span class="hljs-comment">// Selecting the first row</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; row.cells.length; i++) {
    <span class="hljs-keyword">let</span> cell = row.cells[i];
    <span class="hljs-built_in">console</span>.log(cell)
}
</code></pre>
<h2 id="heading-how-to-modify-dom-elements">How to Modify DOM Elements</h2>
<p>Once you have access to DOM elements, you can modify them in various ways using JavaScript.</p>
<h3 id="heading-how-to-manipulate-element-content-and-visibility">How to Manipulate Element Content and Visibility</h3>
<h4 id="heading-innerhtml-and-outerhtml"><code>innerHTML</code> and <code>outerHTML</code></h4>
<p>You can use <code>innerHTML</code> to access or change the HTML content inside an element as a string. <code>outerHTML</code>, on the other hand, lets you get or set the HTML content of an element as a string, including the original element itself.</p>
<p>Here's an example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    Hello World
    <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>Hey I am span<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> first = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">"span"</span>)[<span class="hljs-number">0</span>]; <span class="hljs-comment">// </span>

<span class="hljs-comment">// log and change inner HTML</span>
<span class="hljs-built_in">console</span>.log(first.innerHTML); <span class="hljs-comment">// Output: Hey I am span</span>
first.innerHTML = <span class="hljs-string">"Hey I am changed"</span>; <span class="hljs-comment">// Modify the content of the &lt;span&gt; element</span>

<span class="hljs-comment">// log and change outer HTML</span>
<span class="hljs-built_in">console</span>.log(first.outerHTML); <span class="hljs-comment">// Output: &lt;span&gt;Hey I am span&lt;/span&gt;</span>
first.outerHTML = <span class="hljs-string">"&lt;h1&gt;Hey I am changed&lt;/h1&gt;"</span>; <span class="hljs-comment">// Reload the page to see the change</span>
</code></pre>
<h4 id="heading-textcontent-property"><code>textContent</code> property</h4>
<p>The <code>textContent</code> property allows you to set or retrieve the text content of an element, ignoring any HTML tags within it. It's useful when you want to update the text content of an element without affecting its HTML structure.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(first.textContent); <span class="hljs-comment">// output: Hey I am span</span>

<span class="hljs-comment">// change the text content</span>
first.textContent = <span class="hljs-string">"Hey I am changed"</span>;
</code></pre>
<h4 id="heading-innertext-property"><code>innerText</code> property</h4>
<p>The <code>innerText</code> property returns only the visible text content of an element, excluding any text within <code>&lt;script&gt;</code> and <code>&lt;style&gt;</code> elements, and accounting for CSS styling that affects visibility. It takes into account CSS styling, such as <code>display: none</code>, <code>visibility: hidden</code>, and so on and returns only the text that is rendered on the screen. </p>
<h4 id="heading-style-property"><code>style</code> property</h4>
<p>This property provides access to an object for manipulating an element's inline styles (for example, <code>element.style.color = "red"</code>).</p>
<h4 id="heading-hidden-property"><code>hidden</code> property</h4>
<p>The <code>hidden</code> provides a simple and convenient way to control the visibility of elements in the DOM without directly manipulating their style properties.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">'span'</span>)[<span class="hljs-number">0</span>].hidden = <span class="hljs-literal">true</span>;

<span class="hljs-comment">// When hidden is set to false, the element is visible.</span>
</code></pre>
<p>Note that setting an element's <code>hidden</code> property to <code>true</code> only hides it from view, but it still occupies space in the document layout. </p>
<h3 id="heading-how-to-modify-element-attributes">How to Modify Element Attributes</h3>
<p>The <code>getAttribute()</code> method retrieves the value of a specified attribute of an element, while <code>setAttribute()</code> sets or updates the value of a specified attribute. </p>
<p><code>hasAttribute()</code> checks whether an element has a specific attribute, returning true or false. The <code>removeAttribute()</code> method removes a specified attribute from an element.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/image-68.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In HTML5, it's possible to define custom attributes for elements. But to prevent potential conflicts with future HTML or JavaScript updates, you should prefix custom attributes with <code>data-</code>. For instance:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"element1"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"sample"</span> <span class="hljs-attr">data-category</span>=<span class="hljs-string">"music"</span> <span class="hljs-attr">data-rating</span>=<span class="hljs-string">"5"</span>&gt;</span>
    This is the first element.
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>To access these custom attributes using JavaScript, we can utilize the <code>dataset</code> property. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(element1.dataset);
</code></pre>
<p>This will display a <code>DOMStringMap</code> object containing all the custom attributes associated with the "element1" div. Specific custom attributes can also be accessed by their names. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(element1.dataset.category);

<span class="hljs-comment">// This code would output the value of the "category" custom attribute, which in this case is "music"</span>
</code></pre>
<h3 id="heading-html-insertion-methods">HTML Insertion Methods</h3>
<p>In HTML, there are several ways to insert new content or modify existing content dynamically using JavaScript. These are known as HTML insertion methods. </p>
<p>Consider the following HTML as our example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"first"</span>&gt;</span>first element<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<h4 id="heading-classic-way-to-insert-html">Classic Way to Insert HTML:</h4>
<p>A conventional way to insert HTML is by using the <code>innerHTML</code> property. For example, let's say we want to add an <code>h1</code> element with the text "Hello World" inside the first <code>div</code>. We can do this using the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> a = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">'div'</span>)[<span class="hljs-number">0</span>];
a.innerHTML = <span class="hljs-string">'&lt;h1&gt;Hello World&lt;/h1&gt;'</span>;
</code></pre>
<p>We could also append new HTML to the existing HTML inside the <code>div</code> element. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// This will retain the old content and add a new h1 element.</span>
<span class="hljs-keyword">let</span> a = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">'div'</span>)[<span class="hljs-number">0</span>];
a.innerHTML = a.innerHTML + <span class="hljs-string">'&lt;h1&gt;Hello World&lt;/h1&gt;'</span>;
</code></pre>
<h4 id="heading-using-createelement-to-insert-html">Using <code>createElement</code> to Insert HTML:</h4>
<p>Another method involves creating a new element using <code>createElement</code>, setting its content using <code>innerHTML</code>, and subsequently appending it to the target element using <code>appendChild</code>.</p>
<h4 id="heading-other-html-insertion-methods">Other HTML Insertion Methods:</h4>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
I am outside div (start)
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
    I am start of this container
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"first"</span>&gt;</span>I am first element<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    I am end of this container
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
I am outside div (end)
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Now, let's consider other methods for inserting HTML content dynamically:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> a = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">'div'</span>)[<span class="hljs-number">0</span>];

<span class="hljs-comment">// Using createElement and appendChild</span>
<span class="hljs-keyword">let</span> div = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>);
div.innerHTML = <span class="hljs-string">'&lt;h1&gt;Hello World (append)&lt;/h1&gt;'</span>;
a.appendChild(div);

<span class="hljs-comment">// Using prepend</span>
<span class="hljs-keyword">let</span> div = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>);
div.innerHTML = <span class="hljs-string">'&lt;h1&gt;Hello World (prepend)&lt;/h1&gt;'</span>;
a.prepend(div);

<span class="hljs-comment">// Using before</span>
<span class="hljs-keyword">let</span> div = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>);
div.innerHTML = <span class="hljs-string">'&lt;h1&gt;Hello World (before)&lt;/h1&gt;'</span>;
a.before(div);

<span class="hljs-comment">// Using after</span>
<span class="hljs-keyword">let</span> div = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>);
div.innerHTML = <span class="hljs-string">'&lt;h1&gt;Hello World (after)&lt;/h1&gt;'</span>;
a.after(div);

<span class="hljs-comment">// Using replaceWith</span>
<span class="hljs-keyword">let</span> div = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>);
div.innerHTML = <span class="hljs-string">'&lt;h1&gt;Hello World (replaced)&lt;/h1&gt;'</span>;
a.replaceWith(div);
</code></pre>
<p>This code demonstrates different methods for dynamically inserting HTML content into the DOM using JavaScript.</p>
<ul>
<li><code>a.append(div)</code>: This method appends the <code>div</code> element as the last child of the <code>a</code> element.</li>
<li><code>a.prepend(div)</code>: This method adds the <code>div</code> element as the first child of the <code>a</code> element.</li>
<li><code>a.before(div)</code>: This method adds the <code>div</code> element before the <code>a</code> element.</li>
<li><code>a.after(div)</code>: This method adds the <code>div</code> element after the <code>a</code> element.</li>
<li><code>a.replaceWith(div)</code>: This method replaces the <code>a</code> element with the <code>div</code> element.</li>
</ul>
<h3 id="heading-the-insertadjacenthtml-insertadjacentelement-and-insertadjacenttext-methods">The <code>insertAdjacentHTML</code>, <code>insertAdjacentElement</code>, and <code>insertAdjacentText</code> Methods</h3>
<p>These methods are used to insert content into the DOM at a specified position relative to a given element. They are helpful when you need to dynamically add new elements or text to your webpage.</p>
<h4 id="heading-insertadjacenthtml"><code>insertAdjacentHTML</code>:</h4>
<p><code>insertAdjacentHTML</code> allows you to insert a string of HTML at a specified position relative to the element.</p>
<p>The first parameter specifies where the HTML string will be inserted:</p>
<ul>
<li><code>beforebegin</code>: Before the element itself.</li>
<li><code>afterbegin</code>: Just inside the element, before its first child.</li>
<li><code>beforeend</code>: Just inside the element, after its last child.</li>
<li><code>afterend</code>: After the element itself.</li>
</ul>
<p>Example usage:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> element = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'example'</span>);
element.insertAdjacentHTML(<span class="hljs-string">'beforebegin'</span>, <span class="hljs-string">'&lt;div&gt;New content&lt;/div&gt;'</span>);
</code></pre>
<h4 id="heading-insertadjacentelement"><code>insertAdjacentElement</code>:</h4>
<p>It's similar to <code>insertAdjacentHTML</code>, but instead of inserting HTML, you can insert a DOM element.</p>
<p>Example usage:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> element = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'example'</span>);
<span class="hljs-keyword">let</span> newElement = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>);
newElement.textContent = <span class="hljs-string">'New content'</span>;
element.insertAdjacentElement(<span class="hljs-string">'beforebegin'</span>, newElement);
</code></pre>
<h4 id="heading-insertadjacenttext"><code>insertAdjacentText</code>:</h4>
<p>It's similar to <code>insertAdjacentHTML</code>, but instead of inserting HTML, you can insert plain text.</p>
<p>Example usage:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> element = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'example'</span>);
element.insertAdjacentText(<span class="hljs-string">'beforebegin'</span>, <span class="hljs-string">'New content'</span>);
</code></pre>
<h4 id="heading-node-removal">Node Removal:</h4>
<p>The <code>remove</code> method removes the element from the DOM.</p>
<p>Example usage:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> element = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'example'</span>);
element.remove();
</code></pre>
<p>These methods allow you to manipulate the DOM dynamically, adding or removing content based on certain conditions or user interactions.</p>
<p>When using <code>insertAdjacentHTML</code>, <code>insertAdjacentElement</code>, or <code>insertAdjacentText</code>, you specify where the new content should be inserted relative to the given element.</p>
<p>When using <code>remove</code>, you simply remove the element from the DOM entirely.</p>
<p>These methods are helpful for dynamically updating the content of your webpage without having to reload the entire page.</p>
<h3 id="heading-how-to-manipulate-classes-with-javascript">How to Manipulate Classes with JavaScript</h3>
<p>In HTML, we use classes to group elements and apply styles using CSS. For example, we have a div with an id of "first" in our HTML.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"first"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>Hello, this is text<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>We also have CSS styles for classes like "yellow", "red", and "text-dark" to change background color and text color.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.yellow</span> {
    <span class="hljs-attribute">background-color</span>: yellow;
    <span class="hljs-attribute">color</span>: white;
}
<span class="hljs-selector-class">.red</span> {
    <span class="hljs-attribute">background-color</span>: red;
    <span class="hljs-attribute">color</span>: white;
}
<span class="hljs-selector-class">.text-dark</span> {
    <span class="hljs-attribute">color</span>: black;
}
</code></pre>
<p><strong><code>className</code>:</strong> In JavaScript, we can change the class of an element using the <code>className</code> property. For instance, if we want to change the class of the element with the id "first" to "red text-dark", we would do:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// we are applying 2 classes here</span>
first.className = <span class="hljs-string">"red text-dark"</span>;
</code></pre>
<p>If we want to add another class without removing the existing ones, we use the <code>+=</code> operator:</p>
<pre><code class="lang-javascript">first.className += <span class="hljs-string">" yellow"</span>; <span class="hljs-comment">// Adds the class "yellow" without removing existing classes</span>
</code></pre>
<p><strong><code>classList</code>:</strong> The <code>classList</code> property allows you to manipulate the classes of an element. We can use methods like <code>add</code>, <code>remove</code>, <code>toggle</code>, and <code>contains</code> to add, remove, toggle, or check the presence of a class.</p>
<ul>
<li><code>classList.remove()</code>: Removes a specific class from the element:</li>
</ul>
<pre><code class="lang-javascript">first.classList.remove(<span class="hljs-string">'text-dark'</span>); <span class="hljs-comment">// Removes the class "text-dark"</span>
</code></pre>
<ul>
<li><code>classList.add()</code>: But wait, it looked better with that class! We can also add it back with:</li>
</ul>
<pre><code class="lang-javascript">first.classList.add(<span class="hljs-string">'text-dark'</span>); <span class="hljs-comment">// Adds the class "text-dark"</span>
</code></pre>
<ul>
<li><code>classList.toggle()</code>: Toggles a class on or off based on its presence:</li>
</ul>
<pre><code class="lang-javascript">first.classList.toggle(<span class="hljs-string">'text-dark'</span>); <span class="hljs-comment">// Toggles the class "text-dark" (adds if absent, removes if present)</span>
</code></pre>
<ul>
<li><code>classList.contains()</code>: Checks if a class is present on the element:</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(first.classList.contains(<span class="hljs-string">'text-dark'</span>)); <span class="hljs-comment">// Returns true if the class "text-dark" is present</span>
</code></pre>
<h2 id="heading-event-handling-in-the-dom">Event Handling in the DOM</h2>
<p>Events are actions or occurrences that happen in the system you are programming, that the system may need to respond to in some way. </p>
<p>In the context of web development, events (<strong>Browser Events</strong>) can be user interactions like clicks, mouse movements, key presses, and so on. JavaScript allows you to handle these events and perform actions in response to them.</p>
<p>In HTML, you can directly specify what should happen when an event occurs using attributes like <code>onclick</code>, <code>onmouseover</code>, and so on. For example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"alert('hello')"</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>While you can write JavaScript directly in HTML attributes, it's always better to keep your HTML clean and handle events in JavaScript code separately. This makes your code easier to read and maintain.</p>
<p>You can do this by selecting elements from the webpage using JavaScript and then attaching an event handler to them. Here's how you might do it:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> container = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"container"</span>);
container.onclick = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hey, this is logged from the script!"</span>);
}
</code></pre>
<p>In this code, we select the element with the id "container" using <code>document.getElementById()</code>. Then, we attach a function to the <code>onclick</code> event of that element. This function will be executed whenever the element is clicked.</p>
<h3 id="heading-common-types-of-events">Common Types of Events:</h3>
<ol>
<li><p><strong>Mouse Events</strong>: These events are related to interactions with the mouse. </p>
</li>
<li><p><strong>click</strong>: When you click on an element.</p>
</li>
<li><strong>contextmenu</strong>: When you right-click on an element.</li>
<li><strong>mouseover / mouseout</strong>: When the mouse cursor enters or leaves an element.</li>
<li><strong>mousedown / mouseup</strong>: When you press or release a mouse button over an element.</li>
<li><strong>mousemove</strong>: When the mouse is moved.</li>
</ol>
<p>Some Examples of Mouse Events:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Mouse Button Property Example:</span>

&lt;div onmousedown=<span class="hljs-string">"console.log('Mouse button:', event.button)"</span>&gt;Click me&lt;/div&gt;
</code></pre>
<p>In this example, the event.button property is used to log which mouse button was pressed.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Modifier Keys Example:</span>

&lt;div onclick=<span class="hljs-string">"if(event.ctrlKey) console.log('Ctrl + Click!')"</span>&gt;Ctrl + Click Me&lt;/div&gt;
</code></pre>
<p>This example logs a message when the user clicks the element while holding the Ctrl key.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Coordinates Example:</span>

&lt;div onmousemove=<span class="hljs-string">"console.log('clientX:', event.clientX, 'clientY:', event.clientY)"</span>&gt;Move your mouse here&lt;/div&gt;
</code></pre>
<p>This example logs the clientX and clientY coordinates of the mouse pointer as it moves over the element.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Preventing Selection Example:</span>

&lt;span ondblclick=<span class="hljs-string">"console.log('Double clicked!')"</span> onmousedown=<span class="hljs-string">"return false;"</span>&gt;Double-click me&lt;/span&gt;
</code></pre>
<p>In this example, the return false statement in the onmousedown event handler prevents the default selection behavior when the element is double-clicked.</p>
<ol start="2">
<li><strong>Keyboard Events –</strong> <strong>keydown / keyup</strong>: When a key is pressed or released on the keyboard.</li>
</ol>
<p>Some Examples of Keyboard Events:</p>
<pre><code class="lang-javascript">&lt;input type=<span class="hljs-string">"text"</span> onkeydown=<span class="hljs-string">"console.log('Key pressed!')"</span> onkeyup=<span class="hljs-string">"console.log('Key released!')"</span>&gt;
</code></pre>
<p>In this example, the input field triggers events when a key is pressed (keydown) and released (keyup).</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Event Modifiers Example:</span>

&lt;input type=<span class="hljs-string">"text"</span> onkeydown=<span class="hljs-string">"if(event.ctrlKey &amp;&amp; event.key === 'c') console.log('Ctrl + C pressed!')"</span>&gt;
</code></pre>
<p>This example logs a message when the user presses the Ctrl key and 'c' key simultaneously in the input field.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Accessing Key Information Example:</span>

&lt;input type=<span class="hljs-string">"text"</span> onkeydown=<span class="hljs-string">"console.log('Key pressed:', event.key)"</span>&gt;
</code></pre>
<p>This example logs the key that was pressed in the input field.</p>
<ol start="3">
<li><p><strong>Form Element Events</strong>: These events occur when you interact with form elements, like submitting a form, focusing on an input field, and so on.</p>
</li>
<li><p><strong>Document Events</strong>: These events are related to the document object itself. Example: <strong>DOMContentLoaded</strong> (when the HTML is fully loaded and the DOM is ready)</p>
</li>
<li><p><strong>CSS Events</strong>: These events are related to CSS animations. Example: <strong>transitionend</strong> (When a CSS animation finishes)</p>
</li>
</ol>
<p>Now, let's see an example demonstrating the practical application of event handling and input validation in web development:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Input Validation Example<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">checkPhoneNumber</span>(<span class="hljs-params">event</span>) </span>{
  <span class="hljs-keyword">const</span> validKeys = [<span class="hljs-string">'0'</span>, <span class="hljs-string">'1'</span>, <span class="hljs-string">'2'</span>, <span class="hljs-string">'3'</span>, <span class="hljs-string">'4'</span>, <span class="hljs-string">'5'</span>, <span class="hljs-string">'6'</span>, <span class="hljs-string">'7'</span>, <span class="hljs-string">'8'</span>, <span class="hljs-string">'9'</span>, <span class="hljs-string">'+'</span>, <span class="hljs-string">'('</span>, <span class="hljs-string">')'</span>, <span class="hljs-string">'-'</span>];
  <span class="hljs-keyword">if</span> (!validKeys.includes(event.key)) {
    event.preventDefault(); <span class="hljs-comment">// Prevent default action for invalid keys</span>
  }
}
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"phone"</span>&gt;</span>Enter Phone Number:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"tel"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"phone"</span> <span class="hljs-attr">onkeydown</span>=<span class="hljs-string">"checkPhoneNumber(event)"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Only digits, +, (, ), and - are allowed.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>In this example, we're implementing input validation for a phone number input field. The <code>onkeydown</code> event triggers the <code>checkPhoneNumber</code> function, which checks if the pressed key is valid (digits, plus sign, parentheses, or hyphen). If the key is not valid, the default action (character input) is prevented.</p>
<p>You can <a target="_blank" href="https://www.freecodecamp.org/news/dom-events-and-javascript-event-listeners/">explore more about events here</a>.</p>
<h3 id="heading-event-handlers">Event Handlers</h3>
<p>To react to these events, we use event handlers. An event handler is simply a function that runs when a specific event occurs. There are different ways to assign event handlers in JavaScript:</p>
<ol>
<li><strong>HTML Attribute</strong>: You can set an event handler directly in the HTML code using an attribute like <code>onclick</code>, <code>onmouseover</code>, etc.</li>
</ol>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"alert('Button clicked!')"</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<ol start="2">
<li><strong>DOM Property</strong>: You can assign a handler using a DOM property like <code>onclick</code>, <code>onmouseover</code>, and so on.</li>
</ol>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"myButton"</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"myButton"</span>).onclick = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    alert(<span class="hljs-string">'Button clicked!'</span>);
  };
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<ol start="3">
<li><strong>Event Listeners</strong>: Event listeners are functions that wait for a specific event to occur and then execute a designated function. This is typically done using the <code>addEventListener</code> method. </li>
</ol>
<h3 id="heading-addeventlistener-and-removeeventlistener"><code>addEventListener()</code> and <code>removeEventListener()</code>:</h3>
<p>These are methods used to assign and remove event handlers, respectively, in JavaScript.</p>
<ul>
<li><code>**addEventListener()**</code> is used to attach an event listener to an element, which listens for a specific event (for example, a click or mouseover). It provides more flexibility, especially when you need to add multiple handlers to the same event.</li>
</ul>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"myButton"</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"myButton"</span>).addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    alert(<span class="hljs-string">'Button clicked!'</span>);
  });
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'btn'</span>);

<span class="hljs-comment">// Example 1: Adding event listeners directly with anonymous functions</span>
btn.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">e</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Button clicked!"</span>); <span class="hljs-comment">// Logs a message when the button is clicked</span>
});

<span class="hljs-comment">// Example 2: Defining functions separately and then adding event listeners</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello!"</span>);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">farewell</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Goodbye!"</span>);
}
btn.addEventListener(<span class="hljs-string">'mouseenter'</span>, greet); <span class="hljs-comment">// Greets when the mouse enters the button</span>
btn.addEventListener(<span class="hljs-string">'mouseleave'</span>, farewell); <span class="hljs-comment">// Says goodbye when the mouse leaves the button</span>
</code></pre>
<p>With <code>addEventListener</code>, you can also specify additional options as a third argument. Some common options are:</p>
<ul>
<li><code>once</code>: A boolean value that specifies whether the event listener should be removed after it is invoked once.</li>
<li><code>capture</code>: A boolean value that specifies whether the event should be captured during the capturing phase. The capturing phase happens before the bubbling phase.</li>
</ul>
<p>For example:</p>
<pre><code class="lang-javascript">btn.addEventListener(<span class="hljs-string">'click'</span>, handleClick, { <span class="hljs-attr">once</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">capture</span>: <span class="hljs-literal">true</span> });
</code></pre>
<p>This will add a click event listener to the button element that is triggered only once and captures the event during the capturing phase.</p>
<ul>
<li><code>**removeEventListener()**</code> is used to remove a previously attached event listener from an element. </li>
</ul>
<pre><code class="lang-html">// Example 1

<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"myButton"</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleClick</span>(<span class="hljs-params"></span>) </span>{
    alert(<span class="hljs-string">'Button clicked!'</span>);
  }

  <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"myButton"</span>).addEventListener(<span class="hljs-string">'click'</span>, handleClick);
  <span class="hljs-comment">// Remove the event handler</span>
  <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"myButton"</span>).removeEventListener(<span class="hljs-string">'click'</span>, handleClick);
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example 2</span>
<span class="hljs-comment">// Assume a user preference</span>
<span class="hljs-keyword">const</span> allowGreetings = <span class="hljs-literal">true</span>;

<span class="hljs-comment">// Removing event listeners based on user preference</span>
<span class="hljs-keyword">if</span> (!allowGreetings) {
    btn.removeEventListener(<span class="hljs-string">'mouseenter'</span>, greet);
}
</code></pre>
<h3 id="heading-object-handlers-handleevent">Object Handlers: <code>handleEvent</code></h3>
<p>Instead of assigning a function as an event handler, you can also assign an object that has a <code>handleEvent</code> method. When the event occurs, the <code>handleEvent</code> method of the object will be called.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"myButton"</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">let</span> myObject = {
    <span class="hljs-attr">handleEvent</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>{
      alert(<span class="hljs-string">'Button clicked!'</span>);
    }
  };

  <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"myButton"</span>).addEventListener(<span class="hljs-string">'click'</span>, myObject);
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>In this example, when the button is clicked, the <code>handleEvent</code> method of <code>myObject</code> is called.</p>
<h3 id="heading-event-object">Event Object:</h3>
<p>When an event occurs, the browser creates an event object that contains information about the event, such as the type of event, the target element, and any additional data. </p>
<p>This object is passed as an argument to the event handler function which can be accessed within the callback function of an event listener.</p>
<pre><code class="lang-javascript">element.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>{
    <span class="hljs-built_in">console</span>.log(event.type); <span class="hljs-comment">// Output: "click"</span>
    <span class="hljs-built_in">console</span>.log(event.target); <span class="hljs-comment">// Output: The element that was clicked</span>
     <span class="hljs-comment">// We can access more properties like event.clientX, event.clientY, etc.</span>
});
</code></pre>
<h3 id="heading-event-propagation">Event Propagation:</h3>
<p>Events in the DOM can propagate through the DOM tree in two phases: the capturing phase and bubbling phase. </p>
<p>When an event happens on an element, like a click or a key press, the browser needs to decide which elements should be notified about the event. </p>
<p>Event capturing and bubbling describe the order in which elements are notified about the event. Understanding event propagation is important when dealing with nested elements and event delegation.</p>
<ol>
<li><strong>Capturing Phase</strong>: In the capturing phase, the event starts from the top of the DOM hierarchy (usually the <code>&lt;html&gt;</code> element) and travels down to the target element. During this phase, event handlers attached with <code>addEventListener</code> and the <code>capture</code> option set to <code>true</code> are triggered. These handlers are executed before the event reaches the target element.</li>
<li><strong>Target Phase</strong>: Once the event reaches the target element, it enters the target phase. Event handlers attached with <code>addEventListener</code> without the <code>capture</code> option (or with <code>false</code> as the value) are triggered during this phase. Handlers attached in this phase are executed when the event is directly targeting the element.</li>
<li><strong>Bubbling Phase</strong>: After the target phase, the event bubbles up from the target element to the top of the DOM hierarchy. During this phase, event handlers attached with <code>addEventListener</code> without the <code>capture</code> option (or with <code>false</code> as the value) are triggered again. Handlers attached in this phase are executed as the event travels up from the target element.</li>
</ol>
<p>Let's look at an example. Consider a <code>&lt;div&gt;</code> nested inside another <code>&lt;div&gt;</code>. If a click event occurs on the inner <code>&lt;div&gt;</code>, the capturing phase starts from the outer <code>&lt;div&gt;</code> and goes down to the inner <code>&lt;div&gt;</code>. Then, the target phase happens on the inner <code>&lt;div&gt;</code>, and finally, the bubbling phase occurs from the inner <code>&lt;div&gt;</code> back up to the outer <code>&lt;div&gt;</code>.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"outerDiv"</span>&gt;</span>
  Outer Div
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"innerDiv"</span>&gt;</span>Inner Div<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">const</span> outerDiv = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'outerDiv'</span>);
  <span class="hljs-keyword">const</span> innerDiv = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'innerDiv'</span>);

  outerDiv.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Capturing: Outer Div'</span>), <span class="hljs-literal">true</span>);
  innerDiv.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Target: Inner Div'</span>));
  outerDiv.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Bubbling: Outer Div'</span>));
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>Let's understand Bubbling in detail.</p>
<h3 id="heading-event-bubbling">Event Bubbling:</h3>
<p>Event bubbling is a mechanism in JavaScript where, when an event occurs on an element, such as a click, that event first triggers on the target element and then "bubbles" up through its ancestor elements all the way up to the root of the document (usually <code>&lt;html&gt;</code>). This triggers the same event on each ancestor along the way. Here's an example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"alert('form')"</span>&gt;</span>
  FORM
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"alert('div')"</span>&gt;</span>
    DIV
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"alert('p')"</span>&gt;</span>P<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<p>If you click on the <code>&lt;p&gt;</code> element, the click event will first trigger on the <code>&lt;p&gt;</code> element, then on the <code>&lt;div&gt;</code>, and finally on the <code>&lt;form&gt;</code>. This is because the event bubbles up through each parent element in the DOM hierarchy.</p>
<p><strong><code>event.target</code></strong> vs. <code>this</code>:</p>
<ul>
<li><code>event.target</code> refers to the element that initiated the event. It remains the same throughout the bubbling process. In the above example, if you click on the <code>&lt;p&gt;</code> element, <code>event.target</code> will be the <code>&lt;p&gt;</code> element.</li>
<li><code>this</code> (or <code>event.currentTarget</code>) refers to the current element that the event handler is attached to. In the above example, if the event handler is attached to the <code>&lt;form&gt;</code>, <code>this</code> will be the <code>&lt;form&gt;</code> element.</li>
</ul>
<h4 id="heading-how-to-stop-event-bubbling">How to stop event bubbling:</h4>
<p>Sometimes, you might want to stop the event from bubbling up further. You can do this using the <code>event.stopPropagation()</code> method. This method stops the event from propagating to parent elements.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"alert('the bubbling doesn't reach here')"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"event.stopPropagation()"</span>&gt;</span>Click here<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>In this example, clicking the button won't trigger the <code>alert</code> on the body element because <code>event.stopPropagation()</code> is called in the button's click event handler.</p>
<p><code>event.stopImmediatePropagation()</code> is similar to <code>event.stopPropagation()</code>, but also prevents other handlers on the current element from executing.</p>
<h3 id="heading-event-delegation">Event Delegation:</h3>
<p>Event delegation is a technique that allows you to handle events more efficiently by attaching a single event listener to a parent element instead of attaching multiple event listeners to individual child elements. This is particularly useful when you have a large number of similar elements that need the same event handling logic.</p>
<pre><code class="lang-javascript">parentElement.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>{
    <span class="hljs-keyword">if</span> (event.target.classList.contains(<span class="hljs-string">'childElement'</span>)) {
        <span class="hljs-comment">// Action to be performed when a child element is clicked</span>
    }
});
</code></pre>
<pre><code class="lang-javascript">&lt;!-- Example: Event delegation --&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"myList"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Item 1<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Item 2<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Item 3<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span>

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
    <span class="hljs-comment">// Adding a click event listener to the parent ul element</span>
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"myList"</span>).addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>{
        <span class="hljs-comment">// Checking if the clicked element is an li</span>
        <span class="hljs-keyword">if</span> (event.target.tagName === <span class="hljs-string">"LI"</span>) {
            <span class="hljs-comment">// Code to execute when an li is clicked</span>
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Item clicked:"</span>, event.target.textContent);
        }
    });
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>
</code></pre>
<p>This approach reduces the number of event listeners and improves performance.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The DOM, or Document Object Model, is an interface that represents the structure of HTML documents. It serves as the bridge between JavaScript code and the browser, allowing manipulation of HTML elements, styles, attributes, and event handling. </p>
<p>The DOM API provides methods and properties to interact with the DOM tree. Examples include <code>querySelector</code>, <code>addEventListener</code>, <code>createElement</code>, <code>innerHTML</code>, <code>textContent</code>, etc.</p>
<p>Through DOM manipulation, developers can dynamically change various aspects of a web page, including text content, HTML attributes, and the structure of the document itself (for example, inserting, updating, or deleting HTML elements).</p>
<p>JavaScript frameworks and libraries like React often utilize DOM manipulation capabilities to efficiently manage and update user interfaces. This lets developers create complex web applications with interactive and responsive user experiences.</p>
<p>To learn more about the DOM, here are a few resources you can check out:</p>
<p>First of all, I wrote a follow-up article, which you can find here:<br><a class="post-section-overview" href="#https://www.freecodecamp.org/news/form-validation-in-javascript/">Client-Side Form Handling with JavaScript</a>.</p>
<p>You can also read more in the following articles:</p>
<ul>
<li><a target="_blank" href="https://www.samyakinfo.tech/blog/document-and-resource-loading">DOM Events Lifecycle and Efficient script Loading</a></li>
<li>The <a target="_blank" href="https://www.freecodecamp.org/news/the-javascript-dom-manipulation-handbook/">JavaScript DOM manipulation handbook</a></li>
<li>The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model">MDN</a> web docs</li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/dom-manipulation-best-practices/">JavaScript DOM manipulation best practices</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learn-javascript-for-dom-manipulation-in-spanish-course-for-beginners/">JS DOM manipulation in Spanish - full course</a></li>
</ul>
<p></p> ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python Debugging Handbook – How to Debug Your Python Code ]]>
                </title>
                <description>
                    <![CDATA[ Programming is an art, and bugs are an inevitable part of the creative process. Every developer encounters errors in their code – there's really no exception to it. Because of this, understanding how to effectively debug is a crucial skill that can s... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-debugging-handbook/</link>
                <guid isPermaLink="false">66c72192e15bf8cd4413e9e5</guid>
                
                    <category>
                        <![CDATA[ debugging ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Samyak Jain ]]>
                </dc:creator>
                <pubDate>Wed, 24 Jan 2024 12:24:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/The-Python-Debugging-Handbook-Cover--1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Programming is an art, and bugs are an inevitable part of the creative process. Every developer encounters errors in their code – there's really no exception to it.</p>
<p>Because of this, understanding how to effectively debug is a crucial skill that can save you time and frustration. </p>
<p>In this tutorial, we will delve into the fundamentals of debugging Python code. We'll explore common error messages, leverage the community, and utilize print statements to identify and resolve issues. The primary goal is to identify and fix errors in your code, and the key to successful debugging lies in a systematic approach.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><strong><a class="post-section-overview" href="#heading-common-code-error-messages">Common Code Error Messages</a></strong></p>
</li>
<li><p><a class="post-section-overview" href="#heading-1-syntaxerror-invalid-syntax">SyntaxError: invalid syntax</a></p>
</li>
<li><a class="post-section-overview" href="#heading-2-indentationerror-unexpected-indent">IndentationError: unexpected indent</a></li>
<li><a class="post-section-overview" href="#heading-3-nameerror-name-variable-is-not-defined">NameError: name 'variable' is not defined</a></li>
<li><a class="post-section-overview" href="#heading-4-attributeerror-module-object-has-no-attribute-attributename">AttributeError: 'module' object has no attribute 'attribute_name'</a></li>
<li><a class="post-section-overview" href="#heading-5-filenotfounderror-errno-2-no-such-file-or-directory-filename">FileNotFoundError: [Errno 2] No such file or directory: 'filename'</a></li>
<li><a class="post-section-overview" href="#heading-6-indexerror-list-index-out-of-range">IndexError: list index out of range</a></li>
<li><a class="post-section-overview" href="#heading-7-importerror-no-module-named-modulename">ImportError: No module named 'module_name'</a></li>
<li><a class="post-section-overview" href="#heading-8-typeerror">TypeError</a></li>
<li><p><a class="post-section-overview" href="#heading-9-valueerror">ValueError</a></p>
</li>
<li><p><strong>  <a class="post-section-overview" href="#heading-how-to-debug-python-code">How to Debug Python Code</a></strong></p>
</li>
<li><p><a class="post-section-overview" href="#heading-foundational-debugging-techniques"><strong>Foundational Debugging</strong> <strong>Techniques</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-print-statements">Print Statements</a></p>
</li>
<li><a class="post-section-overview" href="#heading-logging">Logging</a></li>
<li><a class="post-section-overview" href="#heading-exception-handling">Exception Handling</a></li>
<li><p><a class="post-section-overview" href="#heading-assertions">Assertions</a></p>
</li>
<li><p><strong>**   [</strong>Advanced Debugging Techniques**](#heading-advanced-debugging-techniques)</p>
</li>
<li><p><a class="post-section-overview" href="#heading-unit-testing">Unit Testing</a></p>
</li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-interactive-debugger-pdb">Interactive Debugger (PDB)</a></li>
<li><p><a class="post-section-overview" href="#heading-remote-debugging">Remote Debugging</a></p>
</li>
<li><p><strong>**  [</strong>Performance Debugging**](#performance-debugging--1)</p>
</li>
<li><p><a class="post-section-overview" href="#heading-code-linters-and-analyzers">Code Linters and Analyzers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-profiling">Profiling</a></p>
</li>
<li><p><strong>  <a class="post-section-overview" href="#heading-ide-features-for-debugging">IDE Features for Debugging</a></strong></p>
</li>
<li><p><strong>   <a class="post-section-overview" href="#heading-some-additional-tips-for-efficient-debugging">Some Additional Tips for Efficient Debugging</a></strong></p>
</li>
<li><p><strong>   <a class="post-section-overview" href="#heading-how-to-search-for-solutions-to-bugs-and-errors">How to Search for Solutions to Bugs and Errors</a></strong></p>
</li>
<li><p><a class="post-section-overview" href="#heading-1-effective-search-strategies">Effective Search Strategies</a></p>
</li>
<li><a class="post-section-overview" href="#heading-2-leveraging-web-resources">Leveraging Web Resources</a></li>
</ol>
<h1 id="heading-common-code-error-messages">Common Code Error Messages</h1>
<p>Before moving on to debugging, let's first examine some common error messages and their meanings:</p>
<p><em>If you're already familiar with common code error messages, feel free to skip this section and move straight to the <a class="post-section-overview" href="#heading-how-to-debug-python-code">Debugging Techniques</a>.</em></p>
<h2 id="heading-1-syntaxerror-invalid-syntax">1. SyntaxError: invalid syntax</h2>
<p>This error occurs when the Python interpreter encounters code that doesn't follow the correct syntax rules. It could be a missing parenthesis, a misplaced colon, or some other syntax-related issue.</p>
<p>To fix these types of errors, check for missing syntax elements and ensure proper pairing of quotes, parentheses, and brackets.</p>
<h2 id="heading-2-indentationerror-unexpected-indent">2. IndentationError: unexpected indent</h2>
<p>Python relies on indentation to define code blocks. This error occurs when indentation is inconsistent or incorrect.</p>
<p>To avoid these errors, ensure proper and consistent indentation using spaces or tabs as required by the programming language.</p>
<h2 id="heading-3-nameerror-name-variable-is-not-defined">3. NameError: name 'variable' is not defined</h2>
<p>These types of errors can result from attempting to use a variable or function that hasn't been defined.</p>
<p>Make sure to check for typos in variable or function names, and make sure they are defined before use.</p>
<h2 id="heading-4-attributeerror-module-object-has-no-attribute-attributename">4. AttributeError: 'module' object has no attribute 'attribute_name'</h2>
<p>You may get this type of error when trying to access an attribute or method that doesn't exist for a module or object.</p>
<p>To fix this, review the code and confirm that the attribute or method being called is correct and available.</p>
<h2 id="heading-5-filenotfounderror-errno-2-no-such-file-or-directory-filename">5. FileNotFoundError: [Errno 2] No such file or directory: 'filename'</h2>
<p>You'll get this error when attempting to access a file that doesn't exist.</p>
<p>You should check the file path and make sure the file exists at the specified location.</p>
<h2 id="heading-6-indexerror-list-index-out-of-range">6. IndexError: list index out of range</h2>
<p>This type of error happens when you're trying to access an index in a sequence (like a list or a string) that doesn't exist. The same error can happen for strings and tuples for the same reason.</p>
<p>To fix it, make sure that the index being used is within the valid range of the sequence.</p>
<h2 id="heading-7-importerror-no-module-named-modulename">7. ImportError: No module named 'module_name'</h2>
<p>You'll get this error if you attempt to import a module that isn't installed or accessible.</p>
<p>To avoid this, install the required module using a package manager (pip) or check the module name for typos.</p>
<h2 id="heading-8-typeerror">8. TypeError:</h2>
<p>This is a common exception in Python that occurs when an operation or function is applied to an object of an inappropriate type. Here are some common types of <code>TypeError</code>:</p>
<ol>
<li><code>TypeError: unsupported operand type(s) for +: 'type1' and 'type2'</code><strong>:</strong>  This error occurs when trying to perform an operation on two objects with incompatible types. For example, attempting to add a string and an integer or multiply a list by a string. </li>
<li><code>TypeError: function_name() takes X positional arguments but Y were given</code><strong>:</strong> This error occurs when calling a function with an incorrect number of arguments. It indicates that the function expects a specific number of arguments, but a different number is provided.</li>
<li><code>TypeError: 'int' object is not callable</code>:  This error occurs when you try to call an object as if it were a function, but it's not callable. For example, attempting to call an integer.</li>
</ol>
<h2 id="heading-9-valueerror">9. ValueError:</h2>
<p>This type of error occurs when a function receives an argument of the correct type but with an inappropriate value.</p>
<ol>
<li><code>ValueError: invalid literal for int() with base X: 'non-numeric'</code>:  This occurs when attempting to convert a string to an integer using <code>int()</code>, but the string is not a valid representation of an integer in the specified base (X). For example, trying to convert a non-numeric string or a string with an invalid format (for example, containing letters) to an integer.</li>
<li><code>ValueError: could not convert string to float: 'non-numeric'</code>:  This happens when trying to convert a string to a floating-point number using <code>float()</code>, but the string is not a valid representation of a number. Similar to the first case, it often involves non-numeric characters or an incorrect format.</li>
<li><code>ValueError: invalid literal for int() with base 10: 'non-numeric'</code>:  Similar to the first case, this error occurs when trying to convert a string to an integer using <code>int()</code>, but the string is not a valid numeric representation in base 10. It is a more general form of the first type, where the base is explicitly set to 10.</li>
<li><code>ValueError: unhashable type: 'mutable_type'</code>:  This error occurs when trying to use a mutable type (for example, list, dictionary) as a key in a dictionary or as an element in a set. Dictionaries and sets require keys and elements to be of a hashable (immutable) type. To resolve this, convert the mutable type to an immutable one or consider a different data structure that supports mutable elements.</li>
</ol>
<p>Understanding these common errors provides a foundation for effective debugging.</p>
<h1 id="heading-how-to-debug-python-code">How to Debug Python Code</h1>
<p>Now that you understand some common error types, let's explore various techniques and tools that can help you debug your Python code efficiently.</p>
<h2 id="heading-foundational-debugging-techniques">Foundational Debugging Techniques:</h2>
<h3 id="heading-print-statements">Print Statements</h3>
<p>When you're writing code, especially in complex programs, it's essential to understand how your code is executing and the values of variables at different points in the program. Print statements allow you to insert messages in your code that get printed to the console or terminal when the program runs. </p>
<p>By strategically placing print statements at different parts of your code, you can create a log of sorts that shows the order in which different sections of your code are being executed. This can help you understand the control flow and pinpoint where the program might be deviating from your expectations.</p>
<p>Here's an example:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">my_function</span>(<span class="hljs-params">x, y</span>):</span>
    print(<span class="hljs-string">"Entering my_function"</span>)
    print(<span class="hljs-string">f'x: <span class="hljs-subst">{x}</span>, y: <span class="hljs-subst">{y}</span>'</span>)
    result = x + y
    print(<span class="hljs-string">f'Result: <span class="hljs-subst">{result}</span>'</span>)
    print(<span class="hljs-string">"Exiting my_function"</span>)
    <span class="hljs-keyword">return</span> result
</code></pre>
<p>While <code>print</code> statements are often the quickest and most straightforward way to get a glimpse into a program's execution flow, especially during initial development., they can be cumbersome to manage and may not be appropriate for production code and therefore comes Logging, which provides a structured way to record information.</p>
<h3 id="heading-logging">Logging</h3>
<p>Logging is like writing notes while your program runs. Instead of just printing things to the screen, you write them to a log. It helps you keep track of what your program is doing, especially when things go wrong.</p>
<p>You can configure logging to control the level of detail in log messages and specify where the logs should go. This could be the console, a file, or other destinations.</p>
<h4 id="heading-logging-levels">Logging Levels:</h4>
<ul>
<li><strong>DEBUG:</strong> Detailed information, useful for developers during debugging.</li>
<li><strong>INFO:</strong> General information about what's happening in the program.</li>
<li><strong>WARNING:</strong> Indicates something unexpected happened, but the program can still continue.</li>
<li><strong>ERROR:</strong> Something went wrong, and the program can't proceed as planned.</li>
<li><strong>CRITICAL:</strong> A very serious error, possibly causing the program to crash.</li>
</ul>
<p>Here's an example of logging:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> logging

logging.basicConfig(level=logging.Info)

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">example_function</span>(<span class="hljs-params">x, y</span>):</span>
    logging.debug(<span class="hljs-string">f"Input values: x=<span class="hljs-subst">{x}</span>, y=<span class="hljs-subst">{y}</span>"</span>)
    result = x + y
    logging.debug(<span class="hljs-string">f"Result: <span class="hljs-subst">{result}</span>"</span>)
    <span class="hljs-keyword">return</span> result

result = example_function(<span class="hljs-number">3</span>, <span class="hljs-number">7</span>)

<span class="hljs-comment"># Logging an error message</span>
<span class="hljs-keyword">if</span> result &gt; <span class="hljs-number">10</span>:
    logging.error(<span class="hljs-string">"Result exceeds the expected maximum."</span>)
</code></pre>
<ul>
<li><strong><code>level=logging.INFO</code></strong> sets the root logger's level to <code>INFO</code>. This means that log messages with severity <code>INFO</code> and above will be captured, while messages with a lower severity (such as <code>DEBUG</code>) will be ignored. It writes logs to a file named <code>example.log</code></li>
<li>Inside the <code>example_function</code>, <code>logging.debug()</code> is used to log information about input values and the result. These messages will only be displayed if the logging level is set to <code>DEBUG</code> or lower.</li>
<li>An error message is logged using <code>logging.error()</code> if the result exceeds the expected maximum (in this case, 10).</li>
<li>Logging can be configured to write messages to both the console and a file named <code>example.log</code>. The <code>format</code> parameter can be used to customize the appearance of log messages, including the timestamp, log level, and the actual log message.</li>
</ul>
<pre><code class="lang-python"><span class="hljs-comment"># Optional</span>
logging.basicConfig(
    filename=<span class="hljs-string">'example.log'</span>,
    format=<span class="hljs-string">'%(asctime)s - %(levelname)s - %(message)s'</span>,
    level=logging.DEBUG
)

<span class="hljs-comment"># this format includes the timestamp, module name, and log level in each log message.</span>
</code></pre>
<p><strong>Note</strong> : In larger applications, it's common to use loggers instead of the root logger directly. This approach allows for more granular control over logging in different parts of the application. You can read more about logging and loggers here.</p>
<p>To learn more about logging and loggers in Python, check out this blog: <a target="_blank" href="https://www.samyakinfo.tech/blog/logging-in-python">https://www.samyakinfo.tech/blog/logging-in-python</a></p>
<h3 id="heading-exception-handling">Exception Handling</h3>
<p>Wrap suspicious code blocks with try-except statements to catch and handle exceptions. This prevents your program from crashing abruptly, allowing you to gracefully handle errors and log relevant information.</p>
<p>The <code>try-except</code> statement is a way to handle exceptions in Python. Here's a basic structure:</p>
<pre><code class="lang-python"><span class="hljs-keyword">try</span>:
    result = x / y
<span class="hljs-keyword">except</span> ExceptionType <span class="hljs-keyword">as</span> e:
    print(<span class="hljs-string">f"An exception of type <span class="hljs-subst">{type(e).__name__}</span> occurred: <span class="hljs-subst">{e}</span>"</span>)
    <span class="hljs-comment"># Additional handling logic, if needed</span>
</code></pre>
<ul>
<li><strong><code>try</code> Block:</strong> Contains the code that might raise an exception.</li>
<li><strong><code>except</code> Block:</strong> Contains the code that is executed if an exception of the specified type occurs in the <code>try</code> block.</li>
<li><strong>Exception Type:</strong> Specifies the type of exception to catch. You can catch specific exceptions or a more general <code>Exception</code> type to catch any exception.</li>
<li><strong><code>as e:</code>:</strong> Assigns the exception object to the variable <code>e</code>, allowing you to access information about the exception.</li>
</ul>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">safe_divide</span>(<span class="hljs-params">x, y</span>):</span>
    <span class="hljs-keyword">try</span>:
        result = x / y
        print(<span class="hljs-string">f"Result: <span class="hljs-subst">{result}</span>"</span>)
    <span class="hljs-keyword">except</span> ZeroDivisionError <span class="hljs-keyword">as</span> e:
        print(<span class="hljs-string">f"Error: <span class="hljs-subst">{type(e).__name__}</span> - <span class="hljs-subst">{e}</span>"</span>)
        <span class="hljs-comment"># Handle the division by zero case</span>
    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
        print(<span class="hljs-string">f"An unexpected error occurred: <span class="hljs-subst">{type(e).__name__}</span> - <span class="hljs-subst">{e}</span>"</span>)
        <span class="hljs-comment"># Handle other types of exceptions</span>
    <span class="hljs-keyword">finally</span>:
        print(<span class="hljs-string">"This block always executes, whether an exception occurred or not."</span>)

<span class="hljs-comment"># Eg.</span>
safe_divide(<span class="hljs-number">10</span>, <span class="hljs-number">2</span>)
safe_divide(<span class="hljs-number">5</span>, <span class="hljs-number">0</span>)
</code></pre>
<p>In this example, the <code>safe_divide</code> function attempts to perform a division operation. If a <code>ZeroDivisionError</code> occurs (division by zero), it's caught in the first <code>except</code> block. If any other type of exception occurs, it's caught in the second <code>except</code> block. The <code>finally</code> block always executes, regardless of whether an exception occurred.</p>
<h3 id="heading-assertions">Assertions</h3>
<p>An assertion is a statement that you add to your code to check if a certain condition holds true. If the condition is false, it indicates a bug or an unexpected situation in your program.</p>
<p>In Python, you use the <code>assert</code> keyword to create an assertion. The syntax is:</p>
<pre><code class="lang-python"><span class="hljs-keyword">assert</span> condition, <span class="hljs-string">"Optional error message"</span>

<span class="hljs-comment"># Example of an assertion with an optional error message</span>
x = <span class="hljs-number">10</span>
y = <span class="hljs-number">0</span>
<span class="hljs-keyword">assert</span> y != <span class="hljs-number">0</span>, <span class="hljs-string">"Divisor (y) should not be zero"</span>

<span class="hljs-comment"># Handling AssertionError</span>
<span class="hljs-keyword">try</span>:
    <span class="hljs-keyword">assert</span> x &gt; <span class="hljs-number">0</span>, <span class="hljs-string">"x should be greater than zero"</span>
<span class="hljs-keyword">except</span> AssertionError <span class="hljs-keyword">as</span> e:
    print(<span class="hljs-string">f"Assertion failed: <span class="hljs-subst">{e}</span>"</span>)
</code></pre>
<p>In this example, the <code>assert y != 0</code> checks whether the divisor (<code>y</code>) is not zero. If it is zero, the assertion fails, and the program raises an <code>AssertionError</code> with the specified error message.</p>
<h4 id="heading-considerations-when-using-assertions">Considerations When Using Assertions:</h4>
<ul>
<li>Assertions are typically used during development and debugging. In a production environment, you may choose to disable assertions  for performance reasons. To disable it, use the <code>-O</code> (eg. <code>python -O script.py</code> ) command-line option or the <code>PYTHONOPTIMIZE</code> environment variable. The <code>-O</code>(optimize) flag turns off assert statements.</li>
<li>Assertions are not meant for input validation from users or external systems. They are more for catching logical errors in your code.</li>
<li>Assertions should be simple conditions that are easy to check and understand. Avoid complex expressions or side effects.</li>
</ul>
<h2 id="heading-advanced-debugging-techniques">Advanced Debugging Techniques:</h2>
<h3 id="heading-unit-testing">Unit Testing</h3>
<p>Unit testing is a software testing methodology where individual components or functions of a program are tested in isolation to ensure that they function correctly. In Python, units typically refer to functions, methods, or classes.</p>
<ol>
<li>Unit tests help catch bugs early in the development process, preventing them from escalating into more complex problems.</li>
<li>Unit tests focus on specific functions or methods in isolation. This allows for pinpointing the source of errors when they occur.</li>
<li>As code evolves, unit tests act as a safety net, ensuring that new changes do not inadvertently break existing functionality.</li>
</ol>
<h3 id="heading-how-to-use-unittest">How to use <code>unittest</code></h3>
<p><code>unittest</code> is the built-in testing framework in Python, inspired by Java's JUnit. It provides a test discovery mechanism and various assertion methods for verifying expected behavior</p>
<p>Let's start with a simple example. Suppose we have a function that adds two numbers:</p>
<pre><code class="lang-python"><span class="hljs-comment"># my_module.py</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add_numbers</span>(<span class="hljs-params">a, b</span>):</span>
    <span class="hljs-keyword">return</span> a + b
</code></pre>
<p>Now, we can create a corresponding test file:</p>
<pre><code class="lang-python"><span class="hljs-comment"># test_my_module.py</span>
<span class="hljs-keyword">import</span> unittest
<span class="hljs-keyword">from</span> my_module <span class="hljs-keyword">import</span> add_numbers

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TestAddNumbers</span>(<span class="hljs-params">unittest.TestCase</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_add_numbers</span>(<span class="hljs-params">self</span>):</span>
        result = add_numbers(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
        self.assertEqual(result, <span class="hljs-number">5</span>)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    unittest.main()
</code></pre>
<p>To run the tests, execute the following command in the terminal:</p>
<pre><code>python -m unittest test_my_module.py
</code></pre><h3 id="heading-how-to-use-pytest">How to use <code>pytest</code></h3>
<p><code>pytest</code> is a third-party testing framework that offers a more concise syntax and additional features like powerful fixtures, and extensive plugin support.</p>
<p>Using the same example as before, a <code>pytest</code> test might look like this:</p>
<pre><code class="lang-python"><span class="hljs-comment"># test_my_module.py</span>

<span class="hljs-keyword">from</span> my_module <span class="hljs-keyword">import</span> add_numbers

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_add_numbers</span>():</span>
    result = add_numbers(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
    <span class="hljs-keyword">assert</span> result == <span class="hljs-number">5</span>
</code></pre>
<p>To run the tests, simply execute:</p>
<pre><code>pytest test_my_module.py
</code></pre><h3 id="heading-how-to-use-the-interactive-debugger-pdb">How to Use the Interactive Debugger (PDB)</h3>
<p>Python comes with a built-in debugger called PDB (Python Debugger). It allows you to pause the execution of your Python code, inspect variables, and step through your code line by line to find and fix issues. </p>
<p>While print statements and logging are helpful for basic debugging, PDB takes debugging to the next level by allowing you to intervene and analyze your code in real-time. </p>
<p>In your Python script, you start by importing the <code>pdb</code> module. This module provides the functionality for debugging Python code. <code>import pdb</code></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pdb

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">example_function</span>(<span class="hljs-params">x, y</span>):</span>
    pdb.set_trace()
    result = x + y
    <span class="hljs-keyword">return</span> result
</code></pre>
<h4 id="heading-setting-breakpoints">Setting breakpoints</h4>
<p>To start debugging at a specific point in your code, you insert the <code>pdb.set_trace()</code> statement. This line acts as a breakpoint, indicating where the debugger should pause the execution of the program.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">some_function</span>():</span>
    pdb.set_trace()  <span class="hljs-comment"># This line sets a breakpoint</span>
    print(<span class="hljs-string">"Hello, World!"</span>)
</code></pre>
<p>When the program reaches this line during execution, it will pause, and the debugger will be activated.</p>
<h4 id="heading-starting-the-debugger">Starting the Debugger:</h4>
<p>There are two ways to start the debugger:</p>
<p><strong>a.</strong> <strong>Using the <code>break</code> Command:</strong></p>
<p>In Python 3.7 and later versions, <code>pdb</code> introduced the <code>pdb.breakpoint()</code> function as a more convenient and standardized way to set a breakpoint and to address some potential issues with the <code>pdb.set_trace()</code> method.</p>
<p>You can set breakpoints directly in your code using the <code>break</code> command. For example:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pdb

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">some_function</span>():</span>
    <span class="hljs-comment"># Setting a breakpoint at line 4</span>
    pdb.breakpoint()
    print(<span class="hljs-string">"Hello, World!"</span>)

some_function()
</code></pre>
<p><strong>b.</strong> <strong>Running the Script with <code>-m pdb</code> Option:</strong></p>
<p>Alternatively, you can run your Python script with the <code>-m pdb</code> option, which automatically starts the debugger. For example:</p>
<pre><code>python -m pdb your_script.py
</code></pre><h4 id="heading-entering-debugger-mode">Entering Debugger Mode:</h4>
<p>When your code encounters the breakpoint (either set using <code>pdb.set_trace()</code> or <code>pdb.breakpoint()</code>), it enters the interactive debugger mode. This is indicated by the <code>(Pdb)</code> prompt.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-18-212824-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>A snapshot of Interactive debugger mode in terminal</em></p>
<h4 id="heading-basic-commands">Basic Commands:</h4>
<p>Now, you can interact with the debugger and use various commands to inspect variables, step through the code, and identify and fix issues.</p>
<p>Some common commands in the pdb debugger include:</p>
<ul>
<li><code>n</code> (next): Continue execution until the next line in the current function is reached. If the current line contains a function call, it will not step into the called function.</li>
<li><code>c</code> (continue): Continue execution until the next breakpoint is encountered.</li>
<li><code>s</code> (step): Execute the current line of code and stop at the first possible occasion (either in a function that is called or at the next line in the current function).</li>
<li><code>q</code> (quit): Exit the debugger and terminate the program.</li>
<li><strong><code>break</code> (or <code>b</code>):</strong> <code>break [file:]line_number</code> or <code>break [function_name]</code>                  Sets a breakpoint at the specified line number or function. When the program execution reaches the breakpoint, it will pause, allowing you to inspect variables and step through the code.</li>
</ul>
<p>By strategically placing breakpoints and using these commands, you can effectively debug your Python code and identify the source of issues in a systematic manner.</p>
<table>
  <tbody>
    <tr>
      <td>
        <strong>Command</strong>
      </td>
      <td>
        <strong>Functionality</strong>
      </td>
    </tr>
    <tr>
    <td>
    list (or l)
    </td>
    <td>
    <strong>list or list [first[, last]]:</strong> Display the source code around the current line. Optionally, you can specify a range of lines to display.
    </td>
  </tr>

  <tr>
  <td>
  print (or p)
  </td>
  <td>
  <b>print expression:</b> Evaluate and print the value of the specified expression. This is useful for inspecting variables.
  </td>
</tr>

<tr>
<td>
break (or b)
</td>
<td>
<b>[file:]line_number or break [function_name]:</b> Sets a breakpoint at the specified line number or function. When the program execution reaches the breakpoint, it will pause, allowing you to inspect variables and step through the code.
</td>
</tr>
    <tr>
      <td>
        help
      </td>
      <td>
        Displays list of commands or provide information about a specific command or topic(eg. help breakpoints)
      </td>
    </tr>
    <tr>
      <td>
        where
      </td>
      <td>
      Display a stack traceback of the function calls leading up to the current point in the code. Each line of the traceback typically includes the function name, the file name, and the line number where the function was called.
      </td>
    </tr>
  </tbody>
</table>


<h4 id="heading-debugger-extensions">Debugger Extensions</h4>
<p>Consider using third-party debugging tools and extensions, such as <code>pdbpp</code>, <code>pudb</code> and <code>ipdb</code>, which enhance the functionality of the built-in PDB debugger. </p>
<p><code>pdbpp</code> provides additional features such as syntax highlighting, tab-completion, and better navigation capabilities.</p>
<p><code>ipdb</code> is an IPython-based debugger, integrating the powerful features of IPython into the debugging experience. It offers an interactive and user-friendly interface for debugging Python code. It Supports IPython magic commands, making it easier to perform complex debugging tasks.</p>
<p><code>pudb</code> is a full-screen, console-based visual debugger that provides syntax highlighting and an interactive and visually appealing debugging experience. It includes a visual interface with a code browser, making it easy to navigate through your code. </p>
<p>To use any of them, replace <code>pdb</code> with the corresponding debugger you want to use. For eg.  <code>import pdb; pdb.set_trace()</code> with <code>import pdbpp; pdbpp.set_trace()</code> in your code.</p>
<h3 id="heading-remote-debugging">Remote Debugging</h3>
<p>Remote debugging refers to the process of debugging code that is running on a system or server separate from the development environment. This is commonly used when the application is deployed on a remote server, in the cloud, or on a different device.</p>
<p>You connect your local Integrated Development Environment (IDE) to the remote environment where the code is running.</p>
<p>You can do this in two ways:</p>
<ul>
<li><strong>IDE with Remote Debugging Support:</strong> Popular integrated development environments (IDEs) like PyCharm, Visual Studio Code, and others provide built-in support for remote debugging.</li>
<li><strong>pdb or pydevd Library:</strong> Python's built-in <code>pdb</code> module can be used for basic debugging. Alternatively, you can use <code>pydevd</code>, a powerful remote debugger.</li>
</ul>
<p>Remote breakpoints, stepping through code, variable inspection, and other debugging features are employed, similar to local debugging.</p>
<h2 id="heading-ide-features-for-debugging">IDE Features for Debugging</h2>
<p>Most Integrated Development Environments (IDEs) for Python, such as PyCharm, Visual Studio Code, and Jupyter Notebooks, come with powerful debugging features. These include visual breakpoints, variable inspection, and step-by-step execution. Utilize these features to streamline your debugging process.</p>
<h3 id="heading-visual-breakpoints">Visual Breakpoints:</h3>
<p>Breakpoints are markers that pause the execution of your Python program at a specific line of code, allowing you to inspect variables, evaluate expressions, and understand the flow of your program at that point. </p>
<ul>
<li><strong>PyCharm:</strong> Simply click on the left margin next to the line number where you want to set the breakpoint.</li>
<li><strong>Visual Studio Code:</strong> Click on the left margin, or use the shortcut <code>F9</code>.</li>
<li><strong>IDLE:</strong> You can add the line <code>import pdb; pdb.set_trace()</code> at the desired location.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/image-101.png" alt="Image" width="600" height="400" loading="lazy">
<em>A snapshot of Breakpoint(red dot) in PyCharm</em></p>
<p>Once a breakpoint is set, run your program in debug mode to stop execution at that specific point.</p>
<h3 id="heading-stepping-through-code">Stepping Through Code:</h3>
<p>After hitting a breakpoint, you can step through your code line by line to understand its behavior. Three common options for this are:</p>
<ul>
<li><strong>Step Into (F7):</strong> Moves to the next line of code and enters function calls if applicable.</li>
<li><strong>Step Over (F8):</strong> Executes the current line of code and stops at the next line, skipping function calls.</li>
<li><strong>Step Out (Shift + F8):</strong> Completes the execution of the current function and stops at the calling function.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/image-119.png" alt="Image" width="600" height="400" loading="lazy">
<em>Stepping through code options</em></p>
<p>Debuggers in IDEs allow you to execute your code step by step. This includes stepping into functions, stepping over lines, and stepping out of functions. This fine-grained control helps you trace the flow of your program and identify the exact location of an issue.</p>
<p>Jupyter Notebooks support this feature with the help of magic commands such as <code>%debug</code> which allows you to interactively debug a cell.</p>
<h3 id="heading-call-stack-exploration">Call Stack Exploration:</h3>
<p>IDEs typically provide a call stack that shows the hierarchy of function calls leading to the current point in the code. This is valuable for understanding the flow of program execution and can be especially useful when dealing with complex applications.</p>
<p>PyCharm, for instance, displays the call stack in the debugger tool window.</p>
<h3 id="heading-variable-inspection">Variable Inspection:</h3>
<p>Inspecting variables is crucial for understanding how data changes during program execution. IDEs provide a Variables panel where you can view the current state of variables, making it easier to identify bugs. Simply hover over a variable or check the Variables tab to see its current value.</p>
<ul>
<li><strong>PyCharm:</strong> Utilizes a dedicated "Variables" pane during debugging.</li>
<li><strong>Visual Studio Code:</strong> Provides variable inspection in the "Watch" and "Variables" panes.</li>
<li><strong>IDLE:</strong> Allows you to type variable names in the interactive console during debugging.</li>
</ul>
<p>Inspecting variables is crucial for understanding how data changes during program execution. </p>
<h3 id="heading-conditional-breakpoints">Conditional Breakpoints:</h3>
<p>In addition to standard breakpoints, some IDEs allow you to set breakpoints with conditions. This means the debugger will only pause if a specified condition is met. This can be helpful when you want to investigate a specific scenario or condition in your code.</p>
<ul>
<li><strong>PyCharm:</strong> Right-click on a breakpoint and set conditions.</li>
<li><strong>Visual Studio Code:</strong> Right-click on a breakpoint, select "Edit Breakpoint," and define a condition.</li>
<li><strong>IDLE:</strong> Utilize the <code>pdb</code> library to set conditional breakpoints within your code.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/hitCount--1-.gif" alt="Image" width="600" height="400" loading="lazy">
<em>A snapshot illustrating the process of setting Conditional breakpoint in Python code within PyCharm</em></p>
<h3 id="heading-watch-expressions">Watch Expressions:</h3>
<p>Watch expressions allow you to monitor specific variables or expressions continuously as your program runs. This feature is beneficial when you want to keep an eye on certain values without manually inspecting them at each breakpoint.</p>
<ul>
<li><strong>PyCharm:</strong> Add expressions to the "Watches" pane to monitor them throughout debugging.</li>
<li><strong>Visual Studio Code:</strong> Use the "Watch" pane to add expressions for continuous monitoring.</li>
<li><strong>IDLE:</strong> While at a breakpoint, type expressions in the interactive console to observe their values.</li>
</ul>
<p>By utilizing watch expressions, you can track the evolution of specific variables or expressions and identify patterns or unexpected changes during runtime.</p>
<p>There are more tools that IDE provides for debugging purposes like:</p>
<ul>
<li>"Python Profiler" in VSCode and the built-in profiler in PyCharm as <strong>Profiling Tools.</strong> </li>
<li>"Code With Me" in PyCharm and Extensions like "Live Share" in VSCode for <strong>Collaborative Debugging.</strong></li>
</ul>
<h2 id="heading-performance-debugging">Performance Debugging:</h2>
<h3 id="heading-code-linters-and-analyzers">Code Linters and Analyzers</h3>
<p>Code linters and static analyzers are tools that help identify potential issues in your code by analyzing the source code without executing it. They can catch common programming errors, enforce coding standards, and provide valuable suggestions for improvement. </p>
<p>Here, we'll talk about a couple of these tools – PyLint and mypy – so you can see how to install them and how they work.</p>
<h4 id="heading-how-to-install-pylint">How to install PyLint:</h4>
<pre><code>pip install pylint
</code></pre><p>Run <code>pylint</code> on your Python script or module using this command:</p>
<pre><code>pylint your_script.py
</code></pre><p>When you run PyLint, it generates a detailed report with information about potential issues, coding convention violations, and other insights. The output includes a score for your code, along with messages indicating areas for improvement.</p>
<p>PyLint can be customized to fit your project's specific needs. You can create a configuration file (usually named <code>.pylintrc</code>) to define your preferences. This file can be placed in the root of your project. eg:</p>
<pre><code>[MASTER]
enable = all

[MESSAGES CONTROL]
disable = missing-docstring
</code></pre><p>In this example, we enable all checks except for the missing docstring check. You can tailor the configuration to match your coding style and project requirements.</p>
<h4 id="heading-how-to-install-mypy">How to install mypy:</h4>
<pre><code>pip install mypy
</code></pre><p>Run <code>mypy</code> on your Python script or module with this command:</p>
<pre><code>mypy your_script.py
</code></pre><p>Mypy will check your code for type-related issues and provide feedback on potential type mismatches and violations of type annotations.</p>
<p>Mypy is particularly useful when you use type annotations in your Python code. It checks that the types you specify match the actual usage of variables, functions, and other elements in your code.</p>
<p>Let's discuss some other code formatters as well.</p>
<h3 id="heading-flake8">flake8</h3>
<p>flake8 combines three main tools:</p>
<ol>
<li><strong>PyFlakes:</strong> This tool performs static code analysis to find errors in your Python code without executing it.</li>
<li><strong>pycodestyle:</strong> Formerly known as pep8, this tool checks your code against the style guide outlined in PEP 8, providing feedback on coding style violations.</li>
<li><strong>McCabe:</strong> This complexity checker identifies complex code blocks that may be harder to understand or maintain.</li>
</ol>
<h4 id="heading-how-to-install-flake8">How to install flake8:</h4>
<pre><code>pip install flake8
</code></pre><p>Similar to PyLint, you can run flake8 on your Python code by executing the following command in your terminal:</p>
<pre><code>flake8 your_file.py 
#Replace your_file.py <span class="hljs-keyword">with</span> the actual name <span class="hljs-keyword">of</span> your Python file.
</code></pre><p>Similar to PyLint, flake8 can be configured to suit your project's requirements. You can create a configuration file (usually named <code>.flake8</code>) in your project's root directory. eg.</p>
<pre><code>[flake8]
max-line-length = <span class="hljs-number">88</span>
extend-ignore = E203, W503
</code></pre><p>In this example, we set the maximum line length to 88 characters and extend the list of ignored errors.</p>
<h3 id="heading-black">Black</h3>
<p>Black is an opinionated code formatter that automates formatting decisions for consistent and readable code.</p>
<p>Black has a set of formatting rules, and it applies them consistently. This eliminates debates over code style within development teams.</p>
<p>You can install Black using this command:</p>
<pre><code>pip install black
</code></pre><p>And here's how you use it:</p>
<pre><code>black your_file.py
</code></pre><p>Black complements traditional linters like PyLint and flake8. You can use these tools in combination to ensure both code quality and consistent formatting.</p>
<p>Many popular editors like Visual Studio Code, Atom, and Sublime Text have extensions or plugins that allow you to use these Code Linters and Analyzers results directly within the editor as you write code.</p>
<h3 id="heading-profiling">Profiling</h3>
<p>Profiling involves analyzing the performance of your code to identify bottlenecks and areas that can be optimized. Python provides built-in tools and external libraries for profiling, helping developers gain insights into their code's execution time and resource usage.</p>
<ul>
<li><strong>Identify Performance Issues:</strong> Profiling allows you to pinpoint sections of your code that consume the most time and resources, aiding in optimization efforts.</li>
<li><strong>Optimize Code:</strong> Once bottlenecks are identified, developers can focus on optimizing specific functions or code blocks to enhance overall performance.</li>
<li><strong>Memory Usage Analysis:</strong> Profiling tools can also help in analyzing memory consumption, aiding in the detection of memory leaks and inefficient memory usage.</li>
</ul>
<p>Python comes with built-in modules for basic profiling. The two main modules are <code>cProfile</code> and <code>profile</code>.</p>
<h4 id="heading-1-cprofile"><strong>1</strong>. cProfile:<em>**</em></h4>
<p><code>cProfile</code> is a built-in module that provides a deterministic profiling of Python programs. It records the time each function takes to execute, making it easier to identify performance bottlenecks.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> cProfile

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">example_function</span>():</span>
    <span class="hljs-comment"># Your code here</span>

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    cProfile.run(<span class="hljs-string">'example_function()'</span>)
</code></pre>
<p>This will output a detailed report of function calls, their execution time, and the percentage of total time spent in each function.</p>
<h4 id="heading-2-profile"><strong>2</strong>. profile:<em>**</em></h4>
<p>The <code>profile</code> module is similar to <code>cProfile</code> but is implemented in pure Python. It provides a more detailed analysis of function calls and can be used when a more fine-grained profiling is needed.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> profile

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">example_function</span>():</span>
    <span class="hljs-comment"># Your code here</span>

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    profile.run(<span class="hljs-string">'example_function()'</span>)
</code></pre>
<p>Both <code>cProfile</code> and <code>profile</code> produce similar outputs, but the former is generally preferred for its lower overhead.</p>
<h3 id="heading-how-to-visualize-profiling-results">How to Visualize Profiling Results:</h3>
<p>While the built-in modules provide textual reports, visualizing the results can make it easier to understand and analyze. One popular tool for this is <code>snakeviz</code>.</p>
<h4 id="heading-installing-snakeviz"><strong>Installing snakeviz:</strong></h4>
<pre><code>pip install snakeviz
</code></pre><h4 id="heading-using-snakeviz"><strong>Using snakeviz:</strong></h4>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> cProfile
<span class="hljs-keyword">import</span> snakeviz

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">example_function</span>():</span>
    <span class="hljs-comment"># Your code here</span>

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    cProfile.run(<span class="hljs-string">'example_function()'</span>, <span class="hljs-string">'profile_results'</span>)
    snakeviz.view(<span class="hljs-string">'profile_results'</span>)
</code></pre>
<p>This will open a browser window displaying an interactive visualization of the profiling results.</p>
<h3 id="heading-advanced-profiling-techniques">Advanced Profiling Techniques:</h3>
<p>While the built-in profiling tools offer valuable insights, more advanced techniques and external libraries can provide additional information.</p>
<h4 id="heading-line-profiling"><strong>Line Profiling:</strong></h4>
<p>Line profiling allows you to see how much time is spent on each line of code within a function. The <code>line_profiler</code> module is commonly used for this purpose.</p>
<h4 id="heading-installing-lineprofiler">Installing line_profiler:</h4>
<pre><code>pip install line_profiler
</code></pre><h4 id="heading-using-lineprofiler">Using line_profiler:</h4>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> line_profiler <span class="hljs-keyword">import</span> LineProfiler

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">example_function</span>():</span>
    <span class="hljs-comment"># Your code here</span>

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    profiler = LineProfiler()
    profiler.add_function(example_function)

    profiler.run(<span class="hljs-string">'example_function()'</span>)

    <span class="hljs-comment"># Display the results</span>
    profiler.print_stats()
</code></pre>
<p>This will show a detailed report with the time spent on each line within the <code>example_function</code>.</p>
<h4 id="heading-memory-profiling">Memory Profiling:</h4>
<p>Understanding memory usage is crucial for optimizing code. The <code>memory_profiler</code> module helps in profiling memory consumption.</p>
<h4 id="heading-installing-memoryprofiler">Installing memory_profiler:</h4>
<pre><code>pip install memory-profiler
</code></pre><h4 id="heading-using-memoryprofiler">Using memory_profiler:</h4>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> memory_profiler <span class="hljs-keyword">import</span> profile

<span class="hljs-meta">@profile</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">example_function</span>():</span>
    <span class="hljs-comment"># Your code here</span>

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    example_function()
</code></pre>
<p>When executed, this will display a line-by-line analysis of memory usage during the execution of the <code>example_function</code></p>
<p>Understanding memory usage is crucial for optimizing code. The <code>memory_profiler</code> module helps in profiling memory consumption.</p>
<p>While these techniques cover a broad range of debugging scenarios, it's important to note that the most effective debugging often involves a combination of these methods. Additionally, understanding the specific context and the type of problem you're dealing with will guide you in choosing the most appropriate technique.</p>
<h1 id="heading-some-additional-tips-for-efficient-debugging">Some Additional Tips for Efficient Debugging:</h1>
<ul>
<li><strong>Version Control and Git Bisect:</strong> Leverage features provided by your version control system to track changes and revert to working versions if needed.. If the bug was introduced recently and you have version control (e.g., Git) in place, using git bisect can help you identify the exact commit that introduced the issue.</li>
<li><strong>Documentation and Code Comments</strong>: Writing  well-documented code and comments can help in understanding the purpose of specific functions or code blocks, making debugging more straightforward for both you and others who might work on the code. </li>
<li><strong>Break Down Complex Problems</strong>: Divide large code blocks into smaller, testable functions for easier debugging and maintenance.</li>
<li><strong>Take Breaks</strong>: Stepping away and returning with a fresh perspective can often reveal solutions that weren't apparent earlier.</li>
<li><strong>Rubber Duck Debugging</strong>: It's like having a therapy session for your code, except the therapist is a rubber duck. Imagine you're stuck on a tricky coding issue. Instead of asking a person for help, you talk to a rubber duck. Yes, an actual rubber duck! You explain your code to the duck, line by line, as if it understands everything. Even though the duck is quite rude and doesn't reply, something magical happens. By talking through your problem out loud, you start to see the solution yourself.</li>
</ul>
<h1 id="heading-how-to-search-for-solutions-to-bugs-and-errors">How to Search for Solutions to Bugs and Errors</h1>
<h2 id="heading-1-effective-search-strategies">1. Effective Search Strategies:</h2>
<ul>
<li><strong>Understand the Error Message:</strong> Start by understanding the error message or bug description. Identify key terms and error codes that can be used in your search.</li>
<li><strong>Include context details</strong>:<em>**</em> for example, operating system, version number of the software, libraries, or frameworks you are working with. Bugs and solutions can vary between different versions.</li>
<li><strong>Quotation Marks:</strong> Use quotation marks to search for an exact phrase. This is useful when searching for specific error messages or code snippets.</li>
<li><strong>Use Descriptive Keywords:</strong> Use specific and descriptive keywords related to the error. Include programming languages, frameworks, and relevant technologies in your search. Whenever possible, include code snippets or examples in your search query. This can narrow down results to those including practical implementations.</li>
</ul>
<h2 id="heading-2-leveraging-web-resources">2. Leveraging Web Resources:</h2>
<ul>
<li><strong>GitHub Repositories:</strong> Search GitHub repositories for similar issues. Many projects have issue trackers where users discuss problems and solutions.</li>
<li><strong>Documentation and Manuals:</strong> Check official documentation and manuals for the technologies you are using. Sometimes, the answer might be found in the official documentation.</li>
<li><strong>Site-specific Searches:</strong> Use the "site:" operator to search within a specific website or domain. This can be useful when looking for solutions on particular forums, documentation, or blogs.</li>
<li>Some useful forums/sites are: Stack Overflow, GitHub discussions, Reddit, and other developer communities. These platforms often have discussions about common bugs and their solutions.</li>
</ul>
<p>These are the ways how you can find the solution for your problem. Even if you don’t find an exact match to your problem, similar issues might provide insights into potential solutions. </p>
<p>If you can't find a solution at all, consider posting your problem on relevant forums or communities. Others may have faced similar issues and can offer assistance. </p>
<p>Bug resolution may require some patience. Be persistent and try different search queries, especially if the issue is complex. </p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>In this debugging handbook, we've explored common error messages, learned effective search strategies, and discovered the practical utility of print statements. </p>
<p>Debugging is an integral part of the software development process. It's an art of patience, persistence, and problem-solving. By employing a combination of print statements, logging, built-in debugging tools, and third-party utilities, you can effectively identify and resolve issues in your Python code. </p>
<p>Developing good debugging habits and leveraging the available tools will not only save you time but also enhance the overall quality and reliability of your programs. </p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
