<?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[ Damilola Oladele - 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[ Damilola Oladele - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 02 Jun 2026 11:12:13 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/activusd/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Write Unit Tests in Python – with Example Test Code ]]>
                </title>
                <description>
                    <![CDATA[ Unit testing is a software testing technique in which individual components or units of a software application are tested independently from the rest of the application. In software development, it's beneficial to break your application into small, i... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/unit-testing-in-python/</link>
                <guid isPermaLink="false">66d45e0cf855545810e93423</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ unit testing ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Damilola Oladele ]]>
                </dc:creator>
                <pubDate>Mon, 10 Jun 2024 16:33:04 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/06/WhatsApp-Image-2024-06-10-at-10.46.58-AM.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Unit testing is a software testing technique in which individual components or units of a software application are tested independently from the rest of the application.</p>
<p>In software development, it's beneficial to break your application into small, isolated units. This approach allows you to write independent tests to check all parts of your application, ensuring that they behave as expected. Also, if a test fails, you can easily isolate and troubleshoot the area of the code that has the bug without tampering with the rest of your application.</p>
<p>Python provides built-in support for unit testing through the <a target="_blank" href="https://docs.python.org/3/library/unittest.html">unittest</a> testing framework. There are also other third-party testing frameworks that you can use for your unit testing, such as <a target="_blank" href="https://docs.pytest.org/en/7.1.x/contents.html">pytest</a>.</p>
<p>This article focuses on how to use the <code>unittest</code> framework to write tests for your Python applications and why developers often prefer it.</p>
<p>To get the best out of this article, you should have a basic understanding of the Python programming language.</p>
<h2 id="heading-why-do-developers-prefer-to-use-unittest">Why Do Developers Prefer to Use unittest?</h2>
<p>While there are many frameworks for unit testing in the Python ecosystem, many developers still prefer the built-in <code>unittest</code> due to its compelling advantages.</p>
<p>First, the <code>unittest</code> module is part of Python's standard library. This ensures immediate availability and compatibility across various environments without extra dependencies. The seamless integration with various environments makes it convenient for developers to use <code>unittest</code> without installing additional packages.</p>
<p>Second, as a long-standing framework within the Python ecosystem, <code>unittest</code> benefits from familiarity and longevity. Many developers are already used to its API and structure, making it a reliable choice for testing.</p>
<p>Third, most integrated development environments (IDEs) such as PyCharm offer built-in support for <code>unittest</code>. This improves developer productivity and streamlines the testing process, allowing for easier test management and execution.</p>
<p>Fourth, the framework has comprehensive and well-maintained documentation. This provides detailed guidance and examples, aiding developers in effectively using <code>unittest</code> for their testing needs.</p>
<p>Finally, many existing Python projects use <code>unittest</code> for testing, ensuring compatibility with legacy codebases. This widespread adoption allows developers to maintain and extend older projects without needing to introduce and adapt to a new testing framework.</p>
<h2 id="heading-how-to-write-unit-tests-with-unittest">How to Write Unit Tests with unittest</h2>
<p>Unit testing with <code>unittest</code> involves creating test cases to verify the functionality of individual units of your code. Each test case is defined by subclassing <code>unittest.TestCase</code>. This allows you to inherit the several methods provided by the <a target="_blank" href="https://docs.python.org/3/library/unittest.html#test-cases">TestCase</a> class.</p>
<p>Some of the methods provided by the <code>TestCase</code> class are assert methods. These assert methods allow you to check whether the actual result of a function or operation matches the expected result, or whether certain conditions are met. If an assertion fails, the test is marked as failed, and you will receive an error message.</p>
<p>See <a target="_blank" href="https://docs.python.org/3/library/unittest.html#classes-and-functions">Classes and functions</a> for detailed information about the different methods provided by the <code>TestCase</code> class.</p>
<p>Now, let's use two of the assert methods to write tests for a simple calculator program. First, create a new folder (directory), named <code>unit-testing</code>. Then, create a file named <code>calculator.py</code> within your <code>unit-testing</code> folder. Now, copy the following code into your <code>calculator.py</code> file:</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">x, y</span>):</span>
    <span class="hljs-string">"""add numbers"""</span>
    <span class="hljs-keyword">return</span> x + y

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

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">divide</span>(<span class="hljs-params">x, y</span>):</span>
    <span class="hljs-string">"""divide numbers"""</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-string">"""multiply numbers"""</span>
    <span class="hljs-keyword">return</span> x * y
</code></pre>
<p>Notice that instead of having your calculator program within a single function, we broke it into four independent functions (units). This is to ensure that each part of the program is independently tested. So if any of the units gives an error during testing, you can easily identify that unit and troubleshoot it without tampering with the other parts of your program.</p>
<p>As earlier mentioned, testing with <code>unittest</code> involves creating a subclass of the <code>unittest.TestCase</code> class and then defining methods within the subclass to test individual units of your program.</p>
<p>To show how this works, let's write a test for the <code>add</code> function in your calculator program. In your <code>unit-testing</code> folder, create a new file named <code>test_calculator.py</code> and then copy the following code into it:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> unittest
<span class="hljs-keyword">import</span> calculator

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TestCalculator</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</span>(<span class="hljs-params">self</span>):</span>
        self.assertEqual(calculator.add(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>), <span class="hljs-number">3</span>)
        self.assertEqual(calculator.add(<span class="hljs-number">-1</span>, <span class="hljs-number">1</span>), <span class="hljs-number">0</span>)
        self.assertEqual(calculator.add(<span class="hljs-number">-1</span>, <span class="hljs-number">-1</span>), <span class="hljs-number">-2</span>)
        self.assertEqual(calculator.add(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>), <span class="hljs-number">0</span>)
</code></pre>
<p>In lines one and two of your code, you imported the <code>unittest</code> and your <code>calculator</code> modules. You then created a <code>TestCalculator</code> class, which inherits from the <code>TestCase</code> class.</p>
<p>In line five of your code, you defined a <code>test_add</code> method within your class. The method just like every instance methods in Python takes <code>self</code> as its first argument. Since <code>self</code> is a reference of the <code>TestCalculator</code> class, it can access the <code>assertEqual</code> method provided by the <code>TestCase</code> class, which <code>TestCalculator</code> inherits from.</p>
<p>The <code>assertEqual</code> method checks if two values are equal. It has the following syntax:</p>
<pre><code class="lang-python">self.assertEqual(first, second, msg=<span class="hljs-literal">None</span>)
</code></pre>
<p>In the preceding syntax, <code>first</code> represents the value you want to test against the <code>second</code> value. <code>msg</code> is optional and it represents a custom message that you will receive if the assertion fails. If you don't provide a value for <code>msg</code>, you will receive a default message.</p>
<p>Now, let's use the explanation of the syntax to explain the use of <code>assertEqual</code> in your <code>test_add</code> method. In your first assertion, <code>self.assertEqual(add(1, 2), 3)</code> checks if the result of <code>add(1, 2)</code> is equal to 3. If the function returns 3, the test passes. Otherwise, it fails and outputs a message indicating the mismatch. This explanation is the same for the rest of your assertions.</p>
<p>Also, notice that you tested just representative values in your <code>test_add</code> method. This ensures that your test covers a wide range of possible inputs without redundant code. Here is a breakdown of the representative values in your <code>test_add</code> method:</p>
<ul>
<li><p>The addition of two positive numbers (<code>self.assertEqual(calculator.add(1, 2), 3)</code>).</p>
</li>
<li><p>The addition of a negative number and a positive number (<code>self.assertEqual(calculator.add(-1, 1), 0)</code>).</p>
</li>
<li><p>The addition of two negative numbers (<code>self.assertEqual(calculator.add(-1, -1), -2)</code>).</p>
</li>
<li><p>The addition of two zeros (<code>self.assertEqual(calculator.add(0, 0), 0)</code>).</p>
</li>
</ul>
<p>Now, to run your test, navigate to the <code>unit-testing</code> directory in your terminal and run the following command:</p>
<pre><code class="lang-bash">python -m unittest test_calculator.py
</code></pre>
<p>Running the preceding command will give you the following message in your terminal:</p>
<pre><code class="lang-bash">.
----------------------------------------------------------------------
Ran 1 <span class="hljs-built_in">test</span> <span class="hljs-keyword">in</span> 0.000s

OK
</code></pre>
<p>The output indicates that you ran a single test and it was successful.</p>
<p>To ensure that your test is working as expected, you go back to your <code>calculator.py</code> file and change the addition (<code>+</code>) operator in your <code>add</code> function to subtraction (<code>-</code>), like this:</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">x, y</span>):</span>
    <span class="hljs-string">"""add numbers"""</span>
    <span class="hljs-keyword">return</span> x - y
</code></pre>
<p>Once you've made the changes, running your test again will raise an <code>AssertionError</code> showing that your test failed:</p>
<pre><code class="lang-bash">Traceback (most recent call last):
  File <span class="hljs-string">".../test_calculator.py"</span>, line 6, <span class="hljs-keyword">in</span> test_add
    self.assertEqual(calculator.add(1, 2), 3)
AssertionError: -1 != 3

----------------------------------------------------------------------
Ran 1 <span class="hljs-built_in">test</span> <span class="hljs-keyword">in</span> 0.000s
</code></pre>
<p>You may be wondering why you have to include the <code>unittest</code> module in your command instead of running <code>python test_calculator.py</code>. That's because you are yet to make your <code>test_calculator.py</code> file a standalone script. So running <code>python test_calculator.py</code> won't give you any output.</p>
<p>To make your <code>test_calculator.py</code> executable as a standalone script, you need to add the following to the bottom of your <code>test_calculator.py</code> file:</p>
<pre><code class="lang-python"><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    unittest.main()
</code></pre>
<p>Also, the <code>unittest</code> module requires that you start the name of your test methods with the word <code>test</code>, otherwise, your test won't run as expected.</p>
<p>To try this, change the name of your <code>test_add</code> method to <code>add_test</code> like this:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TestCalculator</span>(<span class="hljs-params">unittest.TestCase</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add_test</span>(<span class="hljs-params">self</span>):</span>
        self.assertEqual(calculator.add(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>), <span class="hljs-number">3</span>)
        self.assertEqual(calculator.add(<span class="hljs-number">-1</span>, <span class="hljs-number">1</span>), <span class="hljs-number">0</span>)
        self.assertEqual(calculator.add(<span class="hljs-number">-1</span>, <span class="hljs-number">-1</span>), <span class="hljs-number">-2</span>)
        self.assertEqual(calculator.add(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>), <span class="hljs-number">0</span>)
</code></pre>
<p>Now, if you run the command <code>python test_calculator.py</code>, you will get a message similar to this:</p>
<pre><code class="lang-bash">----------------------------------------------------------------------
Ran 0 tests <span class="hljs-keyword">in</span> 0.000s

OK
</code></pre>
<p>Notice that the preceding output shows that zero tests ran. Now, change your method's name back to <code>test_add</code>. Also, change the operator in the <code>add</code> function of your <code>calculator.py</code> back to addition (<code>+</code>). Now, rerun the test with the command <code>python test_calculator.py</code> and compare your output to the preceding output.</p>
<p>It's a common practice for developers to handle invalid input by raising exceptions. So, it's important to write tests that check for these exceptions.</p>
<p>For example, Python will raise a <code>ZeroDivisionError</code> if you try to divide any number by zero. You can use the <code>unittest</code> module to test for such errors.</p>
<p>Now, modify your <code>test_calculator.py</code> file to include a test method for your <code>divide</code> function:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> unittest
<span class="hljs-keyword">import</span> calculator

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TestMathOperations</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</span>(<span class="hljs-params">self</span>):</span>
        self.assertEqual(calculator.add(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>), <span class="hljs-number">3</span>)
        self.assertEqual(calculator.add(<span class="hljs-number">-1</span>, <span class="hljs-number">1</span>), <span class="hljs-number">0</span>)
        self.assertEqual(calculator.add(<span class="hljs-number">-1</span>, <span class="hljs-number">-1</span>), <span class="hljs-number">-2</span>)
        self.assertEqual(calculator.add(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>), <span class="hljs-number">0</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_divide</span>(<span class="hljs-params">self</span>):</span>
        self.assertEqual(calculator.divide(<span class="hljs-number">10</span>, <span class="hljs-number">2</span>), <span class="hljs-number">5</span>)
        self.assertEqual(calculator.divide(<span class="hljs-number">9</span>, <span class="hljs-number">3</span>), <span class="hljs-number">3</span>)
        self.assertEqual(calculator.divide(<span class="hljs-number">-6</span>, <span class="hljs-number">2</span>), <span class="hljs-number">-3</span>)
        self.assertEqual(calculator.divide(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>), <span class="hljs-number">0</span>)
        <span class="hljs-keyword">with</span> self.assertRaises(ZeroDivisionError):
            calculator.divide(<span class="hljs-number">10</span>, <span class="hljs-number">0</span>)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    unittest.main()
</code></pre>
<p>In the preceding code, your new <code>test_divide</code> method tests representative values just like your <code>test_add</code> method. But there is new code at the end that uses <code>assertRaises</code>. <code>assertRaises</code> is another assert method provided by <code>unittest</code> to check if your code raises an exception. Here, you used the method to check for <code>ZeroDivisionError</code>.</p>
<p>So, if you run the tests now, you will get a message showing two dots (<code>..</code>) and indicating that you ran two successful tests:</p>
<pre><code class="lang-bash">..
----------------------------------------------------------------------
Ran 2 tests <span class="hljs-keyword">in</span> 0.000s

OK
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This article has taught you the basics of unit testing in Python using the <code>unittest</code> testing framework.</p>
<p>You've learned the importance of independently testing individual units of your application and the reasons <code>unittest</code> is still a popular choice among Python developers. Also, you've learned how to write basic test cases for the <code>add</code> and <code>divide</code> functions in your simple calculator program.</p>
<p>With this knowledge, you can now confidently create tests that ensure your code behaves as expected, making it more robust and maintainable. I encourage you to apply these lessons by writing tests for the remaining <code>subtract</code> and <code>multiply</code> functions in your calculator program.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Object-Oriented Programming in Python – Explained With Examples ]]>
                </title>
                <description>
                    <![CDATA[ Object-oriented programming (OOP) is a style of programming that heavily relies on objects. These objects can have attributes and methods. While attributes store data, methods define behavior. Like many other programming languages, Python supports bo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-oop-in-python/</link>
                <guid isPermaLink="false">66d45e0647a8245f78752a16</guid>
                
                    <category>
                        <![CDATA[ Object Oriented Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Damilola Oladele ]]>
                </dc:creator>
                <pubDate>Wed, 24 Apr 2024 14:39:28 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/04/WhatsApp-Image-2024-04-24-at-8.25.07-AM.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Object-oriented programming (OOP) is a style of programming that heavily relies on objects. These objects can have attributes and methods. While attributes store data, methods define behavior.</p>
<p>Like many other programming languages, Python supports both OOP and functional programming. However, OOP becomes valuable when writing large-sized and complex programs.</p>
<p>In this article, you will learn the benefits of OOP in Python, how to define a class, class and instance attributes, and instance methods. You will also learn the concept of encapsulation and how to implement inheritance between classes in Python.</p>
<p>To fully understand this article, you should have the following prerequisites:</p>
<ul>
<li><p>Basic knowledge of the Python programming language.</p>
</li>
<li><p>Familiarity with the concepts of functions and objects in programming.</p>
</li>
<li><p>Experience working with a code editor or integrated development environment (IDE).</p>
</li>
<li><p>Basic understanding of how to use a command-line terminal or console.</p>
</li>
</ul>
<p>Now let's dive in.</p>
<h2 id="heading-why-use-object-oriented-programming">Why Use Object-Oriented Programming?</h2>
<p>Object-oriented programming (OOP) offers several benefits when organizing and managing code. By grouping related data and functions into logical classes, OOP promotes code structure and simplifies maintenance, especially as programs grow in size and complexity. The <a target="_blank" href="https://en.wikipedia.org/wiki/Modular_programming">modular approach</a> makes it easier to understand, modify, and reuse code, thereby reducing development time.</p>
<p>Another benefit of OOP is its ability to provide a clear and relatable programming style, which can be more helpful for developers. The use of objects and the relationships between them mirror real-world concepts. This makes it easier to reason about code and design complex systems.</p>
<p>Finally, OOP's concepts such as encapsulation and inheritance, contribute to code robustness by promoting data protection and code reusability.</p>
<h2 id="heading-what-is-a-class-in-python">What is a Class in Python?</h2>
<p>OOP in Python heavily relies on the concept of <code>class</code>. You can think of a class as a blueprint that is used to create objects. To illustrate this, imagine that you have a blueprint for a speaker. You can use this blueprint to build multiple speakers. Each speaker that is created using the blueprint is an instance of the blueprint. Also, each created speaker has its attributes such as color, model, and name. They will also have their methods showing a certain kind of behavior such as volume up and volume down.</p>
<h2 id="heading-how-to-define-a-class-in-python">How to Define a Class in Python</h2>
<p>To define a class, you have to use the <code>class</code> keyword, provided by Python, then followed by the name of the class and a colon:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ClassName</span>:</span>
    <span class="hljs-keyword">pass</span>
</code></pre>
<p>Now using our earlier illustration, let’s create a class named <code>Speaker</code>. In your code editor, create a file named <code>classes.py</code> and copy the following lines of code into it:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Speaker</span>:</span>
    <span class="hljs-keyword">pass</span>

speaker_one = Speaker()
print(speaker_one)
</code></pre>
<p>In the preceding code, you defined a class named <code>Speaker</code> without any attributes or methods. You used the keyword <code>pass</code> in the class body. In Python, the <code>pass</code> keyword does nothing and is usually used as a placeholder.</p>
<p>In line four of the code, you created an instance of the <code>Speaker</code> class and assigned it to the variable <code>speaker_one</code>. This process is also known as instantiating an object from a class. You then printed <code>speaker_one</code> in line five.</p>
<p>Now run the code by running the command <code>python classes.py</code> in your terminal. You will get an output similar to this in your terminal:</p>
<pre><code class="lang-bash">&lt;__main__.Speaker object at 0x10087f8e0&gt;
</code></pre>
<p>The output shows that <code>speaker_one</code> is an object. <code>0x10087f8e0</code> in the output shows the memory address where Python stores the object on your computer.</p>
<p>The memory address in your terminal output will be different.</p>
<p>You can create several more instances from the <code>Speaker</code> class and they will all be different from one another. To verify this, let’s use the equality comparison (<strong>\==</strong>) operator. In your <code>classes.py</code> file, delete <code>print(speaker_one)</code> and add the following to the bottom of your code:</p>
<pre><code class="lang-python">speaker_two = Speaker()

<span class="hljs-keyword">if</span> speaker_one == speaker_two:
    print(<span class="hljs-string">"speaker one is the same as speaker two"</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"speaker one is different from speaker two"</span>)
</code></pre>
<p>Now run <code>python classes.py</code> in your terminal. You will get the following output:</p>
<pre><code class="lang-bash">speaker one is different from speaker two
</code></pre>
<h2 id="heading-class-and-instance-attributes">Class and Instance Attributes</h2>
<p>In this section, you'll add attributes to your <code>Speaker</code> class. You can see attributes as data stored within an object. While class attributes are common to all instances created from your class, instance attributes are unique to each instance.</p>
<p>Now modify your <code>classes.py</code> file by replacing your code with the following:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Speaker</span>:</span>
    brand = <span class="hljs-string">"Beatpill"</span> <span class="hljs-comment"># class attribute</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, color, model</span>):</span>
        self.color = color <span class="hljs-comment"># instance attribute</span>
        self.model = model <span class="hljs-comment"># instance attribute</span>
</code></pre>
<p>You should already be familiar with line one of your new code. In line two, you defined a class attribute, named <code>brand</code>, and assigned it the value <code>Beatpill</code>. Class attributes are variables that belong to the class itself, rather than to individual instances of the class. The effect of class attributes is that all instances you create from your class will inherit and share that class attribute and its value. In this case, every instance you create from your <code>Speaker</code> class will share the same <code>brand</code> value.</p>
<p>Line four of your code defines an <code>__init__</code> method, which takes in three parameters—<code>self</code>, <code>color</code>, and <code>model</code>. This method will be called anytime you create a new instance from your <code>Speaker</code> class. The <code>self</code> parameter is a reference to the <code>Speaker</code> class and it's a convention in Python to always have it as the first parameter in a <code>__init__</code> method. Line five and six set instance attributes, <code>color</code>, and <code>model</code> to your <code>Speaker</code> class.</p>
<p>So, every time you create a new instance from your class, you have to provide arguments for your <code>color</code> and <code>model</code> attributes. Not doing this will result in an error.</p>
<p>Now add the following to the bottom of your code:</p>
<pre><code class="lang-python">speaker_one = Speaker(<span class="hljs-string">"black"</span>, <span class="hljs-string">"85XB5"</span>)
speaker_two = Speaker(<span class="hljs-string">"red"</span>, <span class="hljs-string">"Y8F33"</span>)

print(<span class="hljs-string">f"speaker one is <span class="hljs-subst">{speaker_one.color}</span> while speaker two is <span class="hljs-subst">{speaker_two.color}</span>"</span>)
</code></pre>
<p>By adding the preceding code, you created two instances of the <code>Speaker</code> class—<code>speaker_one</code> and <code>speaker_two</code>. The arguments in each instance represent the values of their <code>color</code> and <code>model</code> attributes. You then printed a message that displays the color attribute of each object. Now, if you run the command <code>python classes.py</code> in your terminal, you will get the output:</p>
<pre><code class="lang-bash">speaker one is black <span class="hljs-keyword">while</span> speaker two is red
</code></pre>
<p>To see that both instances share the same <code>brand</code> class attribute, modify your <code>print()</code> function like this:</p>
<pre><code class="lang-python">print(
    <span class="hljs-string">f"speaker one is <span class="hljs-subst">{speaker_one.color}</span> while speaker two is <span class="hljs-subst">{speaker_two.color}</span>"</span>,
    speaker_one.brand,
    speaker_two.brand,
    sep=<span class="hljs-string">"\n"</span>,
)
</code></pre>
<p>Now run <code>python classes.py</code> and you will get the following output:</p>
<pre><code class="lang-bash">speaker one is black and speaker two is red
Beatpill
Beatpill
</code></pre>
<h2 id="heading-instance-methods">Instance Methods</h2>
<p>In addition to class and instance attributes, classes can also have methods, known as instance methods. Instance methods are functions defined within a class that operate on instances of the class. They use the class and instance attributes to provide behavior and functionality to the objects.</p>
<p>To add instance methods, modify your code file as follows:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Speaker</span>:</span>
    brand = <span class="hljs-string">"Beatpill"</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, color, model</span>):</span>
        self.color = color
        self.model = model

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">power_on</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">f"Powering on <span class="hljs-subst">{self.color}</span> <span class="hljs-subst">{self.model}</span> speaker."</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">power_off</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">f"Powering off <span class="hljs-subst">{self.color}</span> <span class="hljs-subst">{self.model}</span> speaker."</span>)


speaker_one = Speaker(<span class="hljs-string">"black"</span>, <span class="hljs-string">"85XB5"</span>)
speaker_two = Speaker(<span class="hljs-string">"red"</span>, <span class="hljs-string">"Y8F33"</span>)
</code></pre>
<p>In the example above, we've added two instance methods—<code>power_on()</code> and <code>power_off()</code>. These methods, just like the <code>__init__</code> method, take <code>self</code> as the first argument.</p>
<p>The <code>power_on()</code> method prints a message indicating that the speaker of the given color and model is being powered on. Similarly, the <code>power_off()</code> method prints a message about powering off the speaker.</p>
<p>To call these methods, add the following to the bottom of your file:</p>
<pre><code class="lang-python">speaker_one.power_on()
speaker_two.power_off()
</code></pre>
<p>Now run <code>python classes.py</code> in your terminal and you will get the following output:</p>
<pre><code class="lang-bash">Powering on black 85XB5 speaker.
Powering off red Y8F33 speaker.
</code></pre>
<h2 id="heading-encapsulation-in-python">Encapsulation in Python</h2>
<p>Encapsulation is one of the core concepts of OOP. It refers to the bundling of data (attributes) and methods within a class. Encapsulation provides data protection and control over how the code interacts with an object's internal state.</p>
<p>You can achieve encapsulation in Python by defining private attributes and methods within a class. By convention, private attributes and methods are prefixed with a single underscore (_). While Python does not have strict private modifiers like some other languages, the underscore prefix serves as a warning to other developers not to access or modify the attributes and methods directly from outside the class.</p>
<p>Here's an example of encapsulation in Python:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Speaker</span>:</span>
    brand = <span class="hljs-string">"Beatpill"</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, color, model</span>):</span>
        self._color = color  <span class="hljs-comment"># Private attribute</span>
        self._model = model  <span class="hljs-comment"># Private attribute</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">power_on</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">f"Powering on <span class="hljs-subst">{self._color}</span> <span class="hljs-subst">{self._model}</span> speaker."</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">power_off</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">f"Powering off <span class="hljs-subst">{self._color}</span> <span class="hljs-subst">{self._model}</span> speaker."</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_color</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> self._color

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">set_color</span>(<span class="hljs-params">self, new_color</span>):</span>
        self._color = new_color


speaker_one = Speaker(<span class="hljs-string">"black"</span>, <span class="hljs-string">"85XB5"</span>)
speaker_one.power_on()

<span class="hljs-comment"># Accessing a private attribute directly (not recommended)</span>
print(speaker_one._color)

<span class="hljs-comment"># Accessing a private attribute using the getter method (recommended)</span>
print(speaker_one.get_color())

<span class="hljs-comment"># Modifying a private attribute using the setter method (recommended)</span>
speaker_one.set_color(<span class="hljs-string">"white"</span>)
print(speaker_one.get_color())
</code></pre>
<p>In the preceding example, the <code>color</code> and <code>model</code> attributes are private attributes of the <code>Speaker</code> class. Although it is possible to access and modify these attributes directly from outside the class by using, for example, <code>print(speaker_one._color)</code>, this practice is discouraged. Doing so violates encapsulation and can lead to unintended behavior or data corruption.</p>
<p>Instead, the class provides getter <code>get_color()</code> and setter <code>set_color()</code> methods to access and modify the private attributes in a controlled manner. These methods act as an interface for interacting with the object's internal state, ensuring data integrity and enabling additional validation.</p>
<p>Encapsulation promotes code modularity, maintainability, and data protection by separating the internal state from the public interface (methods). It allows you to change the internal state without affecting the code that uses the class, as long as the public interface remains the same.</p>
<h2 id="heading-inheritance-in-python">Inheritance in Python</h2>
<p>Inheritance is another core concept of OOP. It allows classes to inherit attributes and methods from other classes. The new class inherits attributes and methods from the existing class, known as the parent or base class. The new class is called the child or derived class.</p>
<p>Inheritance promotes code reuse by allowing the child class to inherit and extend the functionality of the parent class. This helps in creating hierarchical relationships between classes and organizing code in a more structured and logical manner.</p>
<p>In Python, inheritance is implemented using the following syntax:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DerivedClass</span>(<span class="hljs-params">BaseClass</span>):</span>
    <span class="hljs-comment"># Derived class methods and attributes</span>
</code></pre>
<p>To see how inheritance works, modify your code as follows:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Speaker</span>:</span>
    brand = <span class="hljs-string">"Beatpill"</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, color, model</span>):</span>
        self._color = color
        self._model = model

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">power_on</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">f"Powering on <span class="hljs-subst">{self._color}</span> <span class="hljs-subst">{self._model}</span> speaker."</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">power_off</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">f"Powering off <span class="hljs-subst">{self._color}</span> <span class="hljs-subst">{self._model}</span> speaker."</span>)

<span class="hljs-comment"># Add a SmartSpeaker class and make it inherit from the Speaker class</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SmartSpeaker</span>(<span class="hljs-params">Speaker</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, color, model, voice_assistant</span>):</span>
        super().__init__(color, model)
        self._voice_assistant = voice_assistant

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">say_hello</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">f"Hello, I am <span class="hljs-subst">{self._voice_assistant}</span>"</span>)


<span class="hljs-comment"># Create an instance of the SmartSpeaker class</span>
smart_speaker = SmartSpeaker(<span class="hljs-string">"black"</span>, <span class="hljs-string">"XYZ123"</span>, <span class="hljs-string">"Alexa"</span>)
smart_speaker.power_on()  <span class="hljs-comment"># Inherited from Speaker</span>
smart_speaker.say_hello()
</code></pre>
<p>In the preceding code, the <code>SmartSpeaker</code> class is derived from the <code>Speaker</code> class. The <code>SmartSpeaker</code> class inherits the attributes and methods of the <code>Speaker</code> class.</p>
<p>The <code>__init__</code> method of the <code>SmartSpeaker</code> class calls the <code>__init__</code> method of the <code>Speaker</code> class using <code>super().__init__(color, model)</code>. This ensures that the inherited <code>_color</code> and <code>_model</code> attributes are properly initialized. Also, the <code>SmartSpeaker</code> class has its own attribute <code>_voice_assistant</code>, and a new method <code>say_hello</code>.</p>
<p>Now run <code>python classes.py</code> in your terminal and you will get the following output:</p>
<pre><code class="lang-bash">Powering on black XYZ123 speaker.
Hello, I am Alexa
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Throughout this article, we highlighted the benefits of Object-Oriented Programming (OOP) and demonstrated how to define classes, create and use instance attributes and methods. We provided practical examples to illustrate the implementation of classes in Python, as well as key OOP concepts such as encapsulation and inheritance.</p>
<p>Applying the lessons covered in this article will help you improve your Python programming experience and increase the efficiency and maintainability of your code.</p>
<h2 id="heading-references-and-further-reading">References and Further Reading</h2>
<ul>
<li><p>https://en.wikipedia.org/wiki/Object-oriented_programming</p>
</li>
<li><p>https://realpython.com/python3-object-oriented-programming/</p>
</li>
<li><p>https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object-oriented_programming</p>
</li>
<li><p>https://docs.python.org/3/tutorial/classes.html</p>
</li>
<li><p>https://realpython.com/python-classes/</p>
</li>
<li><p>https://realpython.com/python-double-underscore/</p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Define Relationships Between Django Models ]]>
                </title>
                <description>
                    <![CDATA[ Django is a free and open-source web framework written in Python. It helps with rapid web development and provides out-of-the-box web security. Websites must be able to store and retrieve data from databases. Django makes provisions for this. By defa... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/django-model-relationships/</link>
                <guid isPermaLink="false">66d45e0051f567b42d9f8450</guid>
                
                    <category>
                        <![CDATA[ database ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Django ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Damilola Oladele ]]>
                </dc:creator>
                <pubDate>Mon, 20 Mar 2023 16:05:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/Blog-Banner-560x315-px-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p><a target="_blank" href="https://www.djangoproject.com/">Django</a> is a free and open-source web framework written in Python. It helps with rapid web development and provides out-of-the-box web security.</p>
<p>Websites must be able to store and retrieve data from databases. Django makes provisions for this. By default, Django operates a Relational Database Management System.</p>
<blockquote>
<p>A relational database is a type of database that stores and provides access to data points that are related to one another. Relational databases are based on the relational model, an intuitive, straightforward way of representing data in tables. In a relational database, each row in the table is a record with a unique ID called the key. <a target="_blank" href="https://www.oracle.com/ng/database/what-is-a-relational-database/#:~:text=The%20software%20used%20to%20store,storage%2C%20access%2C%20and%20performance.">(Source: Oracle Cloud)</a></p>
</blockquote>
<p>A major advantage of a Relational Database Management System is being able to define the types of relationships between the different data held in the different tables of your database.</p>
<p>This tutorial shows you how you can define the relationships between your Django <a target="_blank" href="https://docs.djangoproject.com/en/3.2/topics/db/models/">models</a>. To get the most out of this tutorial, you should have a basic understanding of the Django web framework, especially Django file structure and <a target="_blank" href="https://docs.djangoproject.com/en/3.2/topics/db/models/">models</a>.</p>
<h2 id="heading-different-types-of-model-relationships-in-django"><strong>Different Types of Model Relationships in Django</strong></h2>
<p>Each <a target="_blank" href="https://docs.djangoproject.com/en/3.2/topics/db/models/">model</a> in a <a target="_blank" href="https://www.djangoproject.com/">Django</a> application represents a database table. This means that you can define the kind of relationship you want between the different models in your Django application.</p>
<p>Django supports three main types of relationships between its models. They're as follows:</p>
<h3 id="heading-one-to-one-relationship"><strong>One-to-One Relationship</strong></h3>
<p>A <strong>one-to-one</strong> relationship means that a record in one table relates to a single record in another table.</p>
<p>An instance of this is if you have a Django model that defines users. This model can then have a one-to-one relationship with another Django model, which defines users' profiles. In this scenario, a user can have only one profile and a profile can be associated with only one user.</p>
<p>The following diagram illustrates a <strong>one-to-one</strong> relationship:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/Untitled-drawing--5--2.png" alt="diagram indicating one-to-one relationship" width="600" height="400" loading="lazy"></p>
<p><em>A diagram showing a one-to-one relationship between a User model and a Profile model.</em></p>
<p>Django provides you with <code>OneToOneField</code><strong>,</strong> which helps define a one-to-one relationship between two different models.</p>
<p>The following code shows you how you can define a <strong>one-to-one</strong> relationship in Django. Go to your <code>&lt;app&gt;/models.py</code> and write the following code:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span>(<span class="hljs-params">models.Model</span>):</span>
    name = models.CharField(max_length=<span class="hljs-number">50</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__str__</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> str(self.name)

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Profile</span>(<span class="hljs-params">models.Model</span>):</span>
    user = models.OneToOneField(
        User,
        on_delete=models.PROTECT,
        primary_key=<span class="hljs-literal">True</span>,
    )
    language = models.CharField(max_length=<span class="hljs-number">50</span>)
    email = models.EmailField(max_length=<span class="hljs-number">70</span>,blank=<span class="hljs-literal">True</span>,unique=<span class="hljs-literal">True</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__str__</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> str(self.email)
</code></pre>
<p>Let's see what's going on in the above code:</p>
<ol>
<li><p>Line one imports the sub-module <code>models</code> from the <code>django.db</code> module.</p>
</li>
<li><p>Line three defines a Django model named <code>User</code>.</p>
</li>
<li><p>Line four defines a <code>name</code> property within the <code>User</code> model, and the keyword <code>CharField</code> is how you define text with a limited number of characters.</p>
</li>
<li><p>Line six and seven is a special method within the <code>User</code> model and returns a string representation of the <code>User</code> model that includes the <code>name</code> property.</p>
</li>
<li><p>Line nine defines a Django model named <code>Profile</code>.</p>
</li>
<li><p>Line ten defines a <strong>one-to-one</strong> relationship between the <code>Profile</code> model and the <code>User</code> model using the <code>OneToOneField</code> keyword.</p>
</li>
<li><p>Lines eleven and twelve define the properties <code>language</code> and <code>email</code> within the <code>Profile</code> model.</p>
</li>
<li><p>Line twelve and thirteen is a special method within the <code>Profile</code> model and returns a string representation of the <code>Profile</code> model that includes the <code>email</code> property.</p>
</li>
</ol>
<h3 id="heading-many-to-one-relationship"><strong>Many-to-one Relationship</strong></h3>
<p>In a <strong>many-to-one</strong> relationship, a record in one table relates to multiple records in another table. Some resources refer to a <strong>many-to-one</strong> relationship as a <em>one-to-many</em> relationship. These two mean the same thing.</p>
<p>An example of a one to many relationship is the relationship between an author and their published books. While an author can have more than one book to their name, it's less common to find a book with more than one author. You can see this kind of relationship as a parent-child relationship.</p>
<p>The following diagram illustrates a <strong>one-to-many</strong> relationship:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/Untitled-drawing-1.png" alt="diagram indicating one-to-many relationship" width="600" height="400" loading="lazy"></p>
<p><em>A diagram showing a one-to-many relationship between an Author model and a Book model.</em></p>
<p>Django provides you with <code>ForeignKey</code>, which helps define a <strong>many-to-one</strong> relationship between two different models.</p>
<p>The following code shows you how you can define a <strong>many-to-one</strong> relationship in Django. Go to your <code>&lt;app&gt;/models.py</code> and write the following code:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Author</span>(<span class="hljs-params">models.Model</span>):</span> 
    name = models.CharField(max_length=<span class="hljs-number">50</span>, blank=<span class="hljs-literal">False</span>, unique=<span class="hljs-literal">True</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__str__</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> str(self.name)

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span>(<span class="hljs-params">models.Model</span>):</span>
    author = models.ForeignKey(
        Author,
        on_delete=models.PROTECT,
        blank=<span class="hljs-literal">False</span>
    )

    title = models.CharField(max_length=<span class="hljs-number">100</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__str__</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> self.title
</code></pre>
<p>This code is similar to the code in the first example. However, in line ten here, the <code>ForeignKey</code> keyword is what you use to define a many-to-one relationship between two Django models. In this case, the current model will have a <strong>many-to-one</strong> relationship with the <code>Author</code> model.</p>
<h3 id="heading-many-to-many-relationship"><strong>Many-to-Many Relationship</strong></h3>
<p>In a <strong>many-to-many</strong> relationship, multiple records in one table relate to many records in another table. For instance, you may have a collection model in your application, in which one collection has many books within it. In the same vein, a book may belong to several collections.</p>
<p>The following diagram illustrates a <strong>many-to-many</strong> relationship:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/Untitled-drawing--3-.png" alt="diagram indicating many-to-many relationship" width="600" height="400" loading="lazy"></p>
<p><em>A diagram showing a many-to-many relationship between a Collection model and a Book model.</em></p>
<p>Django provides you with a <a target="_blank" href="https://docs.djangoproject.com/en/4.1/ref/models/fields/#django.db.models.ManyToManyField"><code>ManyToManyField</code></a> which helps define a <strong>many-to-many</strong> relationship between two different models.</p>
<p>The following code shows you how you can define a many-to-many relationship in Django. Go to your <code>&lt;app&gt;/models.py</code> and enter the write the following code:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Collection</span>(<span class="hljs-params">models.Model</span>):</span>
  name = models.CharField(max_length=<span class="hljs-number">50</span>)

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__str__</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> str(self.name)

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span>(<span class="hljs-params">models.Model</span>):</span>
  collection = models.ManyToManyField(Collection)

  title = models.CharField(max_length=<span class="hljs-number">100</span>)

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__str__</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> str(self.title)
</code></pre>
<p>In this code sample, the <code>ManyToManyField</code> keyword in line 10 is what you use to define a <strong>many-to-many</strong> relationship between the <code>Collection</code> and <code>Book</code> models.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Although this tutorial explains the basics of Django model relationships to help you get a basic understanding, real-life projects can get more complicated.</p>
<p>The complexity of your Django model relationships depends on your application's complexity. So before you build your applications, it's important to plan out your database relationships. Doing this saves you lots of time and effort compared to finding problems and backtracking later.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Create a CSV File Using Python ]]>
                </title>
                <description>
                    <![CDATA[ CSV is an acronym for comma-separated values. It's a file format that you can use to store tabular data, such as in a spreadsheet. You can also use it to store data from a tabular database. You can refer to each row in a CSV file as a data record. ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-create-a-csv-file-in-python/</link>
                <guid isPermaLink="false">66d45e02a3a4f04fb2dd2e39</guid>
                
                    <category>
                        <![CDATA[ csv ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Damilola Oladele ]]>
                </dc:creator>
                <pubDate>Wed, 01 Mar 2023 00:43:48 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/csv-article-cover-image-2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p><strong>CSV</strong> is an acronym for comma-separated values. It's a file format that you can use to store tabular data, such as in a spreadsheet. You can also use it to store data from a tabular database.</p>
<p>You can refer to each row in a CSV file as a data record. Each data record consists of one or more fields, separated by commas.</p>
<p>This article shows you how to use the Python built-in module called <strong>csv</strong> to create CSV files. In order to fully comprehend this tutorial, you should have a good understanding of the fundamentals of the Python programming language.</p>
<p>The csv module has two classes that you can use in writing data to CSV. These classes are:</p>
<ul>
<li><p>the <code>csv.writer</code> class</p>
</li>
<li><p>the <code>csv.DictWriter</code> class</p>
</li>
</ul>
<h2 id="heading-how-to-create-a-csv-file-using-the-csvwriter-class">How to Create a CSV File Using the <code>csv.writer</code> Class</h2>
<p>You can use the <code>csv.writer</code> class to write data into a CSV file. The class returns a writer object, which you can then use to convert data into delimited strings.</p>
<p>To ensure that the newline characters inside the quoted fields interpret correctly, open a CSV file object with <strong>newline=''</strong>.</p>
<p>The syntax for the <strong>csv.writer</strong> class is as follows:</p>
<pre><code class="lang-python">csv.writer(csvfile, dialect=’excel’, **fmtparams)
</code></pre>
<p>Now, let me walk you through the meaning of the different parameters used in the syntax.</p>
<ol>
<li><p>The <code>csvfile</code> parameter represents the csvfile object with the <code>write()</code> method.</p>
</li>
<li><p>The optional <code>dialect</code> parameter represents the name of the dialect you can use in writing the CSV file.</p>
</li>
<li><p>The optional <code>fmtparams</code> parameter represents the formatting parameters that you can use to overwrite the parameters specified in the dialect.</p>
</li>
</ol>
<p>The <strong>csv.writer</strong> class has two methods that you can use to write data to CSV files. The methods are as follows:</p>
<h3 id="heading-the-writerow-method">The <code>writerow()</code> Method</h3>
<p>The <code>writerow()</code> method takes in iterable data as its parameter and then writes the data to your CSV file in a single row. One popular usage of the <strong>writerow()</strong> method is using it to write the field row of your CSV file.</p>
<p>Now let me show you how you can use the <strong>writerow()</strong> method to write a single row into your CSV file.</p>
<p>In your code editor, create a file with the name <a target="_blank" href="http://profiles1.py"><em>profiles1.py</em></a>. Then write the following code in the file:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> csv

<span class="hljs-keyword">with</span> open(<span class="hljs-string">'profiles1.csv'</span>, <span class="hljs-string">'w'</span>, newline=<span class="hljs-string">''</span>) <span class="hljs-keyword">as</span> file:
    writer = csv.writer(file)
    field = [<span class="hljs-string">"name"</span>, <span class="hljs-string">"age"</span>, <span class="hljs-string">"country"</span>]

    writer.writerow(field)
    writer.writerow([<span class="hljs-string">"Oladele Damilola"</span>, <span class="hljs-string">"40"</span>, <span class="hljs-string">"Nigeria"</span>])
    writer.writerow([<span class="hljs-string">"Alina Hricko"</span>, <span class="hljs-string">"23"</span>, <span class="hljs-string">"Ukraine"</span>])
    writer.writerow([<span class="hljs-string">"Isabel Walter"</span>, <span class="hljs-string">"50"</span>, <span class="hljs-string">"United Kingdom"</span>])
</code></pre>
<p>The explanation for the code in <code>profiles1.py</code> is as follows:</p>
<ol>
<li><p>Line one imports the Python <em>csv</em> module.</p>
</li>
<li><p>Line two is a blank line that separates the imported module from the rest of the code.</p>
</li>
<li><p>Line three of the code opens the CSV file in writing (w mode) with the help of the <code>open()</code> function.</p>
</li>
<li><p>Line four creates a CSV writer object by calling the writer() function and stores it in the <code>writer</code> variable.</p>
</li>
<li><p>Line five creates a variable named <code>fields</code>, which stores a list that consists of strings, each representing the title of a column in the CSV file.</p>
</li>
<li><p>Line six and below writes the field data and other data to CSV file by calling the <strong>writerow()</strong> method of the CSV writer object.</p>
</li>
</ol>
<p>Once you are done, go to your command line terminal and navigate to the directory that has the Python file <em>profiles1.py</em>. Run the following command:</p>
<pre><code class="lang-sh">python profiles1.py
</code></pre>
<p>You should get a CSV file named <em>profiles1.csv</em> in your working directory with the following text in it:</p>
<pre><code class="lang-bash">name,age,country
Oladele Damilola,40,Nigeria
Alina Hricko,23,Ukraine
Isabel Walter,50,United Kingdom
</code></pre>
<h3 id="heading-the-writerows-method">The <code>writerows()</code> Method</h3>
<p>The <strong>writerows()</strong> method has similar usage to the writerow() method. The only difference is that while the writerow() method writes a single row to a CSV file, you can use the <strong>writerows()</strong> method to write multiple rows to a CSV file.</p>
<p>To see how the <strong>writerows()</strong> method works, create a file named <em>profiles2.py</em> in your working directory. Then write the following code in the file you created:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> csv

<span class="hljs-keyword">with</span> open(<span class="hljs-string">'profiles2.csv'</span>, <span class="hljs-string">'w'</span>, newline=<span class="hljs-string">''</span>) <span class="hljs-keyword">as</span> file:
    writer = csv.writer(file)
    row_list = [
        [<span class="hljs-string">"name"</span>, <span class="hljs-string">"age"</span>, <span class="hljs-string">"country"</span>], 
        [<span class="hljs-string">"Oladele Damilola"</span>, <span class="hljs-string">"40"</span>, <span class="hljs-string">"Nigeria"</span>], 
        [<span class="hljs-string">"Alina Hricko"</span>, <span class="hljs-string">"23"</span> <span class="hljs-string">"Ukraine"</span>], 
        [<span class="hljs-string">"Isabel Walter"</span>, <span class="hljs-string">"50"</span> <span class="hljs-string">"United Kingdom"</span>],
    ]

    writer.writerows(row_list)
</code></pre>
<p>After writing the code in your profiles2.py file, go to your command line terminal and run the following command:</p>
<pre><code class="lang-sh">python profiles2.py
</code></pre>
<p>Now you should have a CSV file named <em>profiles2.csv</em> in your working directory. The file should have the data in the <code>row_list</code> variable.</p>
<h2 id="heading-how-to-create-a-csv-file-using-the-csvdictwriter-class">How to Create a CSV File Using the <code>csv.DictWriter</code> Class</h2>
<p>You can use the <code>csv.DictWriter</code> class to write a CSV file from a dictionary. This is unlike the csv.writer Class, which writes to a CSV file from a list.</p>
<p>The syntax for the <strong>csv.DictWriter</strong> is as follows:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">csv</span>.<span class="hljs-title">DictWriter</span>(<span class="hljs-params">csvfile, fieldnames, restval=<span class="hljs-string">''</span>, extrasaction=<span class="hljs-string">'raise'</span>, dialect=<span class="hljs-string">'excel'</span>, *args, **kwds</span>)</span>
</code></pre>
<p>Now let me explain the meaning of the different parameters in the syntax:</p>
<ol>
<li><p>The <code>csvfile</code> represents the file object with the <code>write()</code> method</p>
</li>
<li><p>The <code>fieldnames</code> parameter is a sequence of keys that identify the order in which Python passes the values in the dictionary.</p>
</li>
<li><p>The <code>restval</code> parameter is optional and it specifies the value to be written if the dictionary is missing a key in fieldnames.</p>
</li>
<li><p>The <code>extrasaction</code> parameter is optional and it specifies the action to take if a key is not found in fieldnames. Setting this parameter to <code>raise</code>, raises a <em>ValueError</em>.</p>
</li>
<li><p>The <code>dialect</code> parameter is optional and it represents the name of the dialect you want to use.</p>
</li>
</ol>
<p>The <strong>csv.DictWriter</strong> class has two methods that you can use to write data to CSV files. The methods are as follows:</p>
<h3 id="heading-the-writeheader-method">The <code>writeheader()</code> Method</h3>
<p>Use the <strong>writeheader()</strong> method to write the first row of your csv file using the pre-specified <code>fieldnames</code>.</p>
<p>To see how the the <strong>writeheader()</strong> method works, create a new file named <em>profiles3.py</em> in your working directory. Then write the following code in the <em>profles3.py</em> file using your code editor:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> csv 

mydict =[{<span class="hljs-string">'name'</span>: <span class="hljs-string">'Kelvin Gates'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-string">'19'</span>, <span class="hljs-string">'country'</span>: <span class="hljs-string">'USA'</span>}, 
         {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Blessing Iroko'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-string">'25'</span>, <span class="hljs-string">'country'</span>: <span class="hljs-string">'Nigeria'</span>}, 
         {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Idong Essien'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-string">'42'</span>, <span class="hljs-string">'country'</span>: <span class="hljs-string">'Ghana'</span>}]

fields = [<span class="hljs-string">'name'</span>, <span class="hljs-string">'age'</span>, <span class="hljs-string">'country'</span>] 

<span class="hljs-keyword">with</span> open(<span class="hljs-string">'profiles3.csv'</span>, <span class="hljs-string">'w'</span>, newline=<span class="hljs-string">''</span>) <span class="hljs-keyword">as</span> file: 
    writer = csv.DictWriter(file, fieldnames = fields)

    writer.writeheader()
</code></pre>
<p>The explanation of the code in <em>profiles3.py</em> is as follows:</p>
<ol>
<li><p>Line one imports the Python <em>csv</em> module.</p>
</li>
<li><p>Line two is a blank space that separates the Python csv module from the rest of the code.</p>
</li>
<li><p>Line three stores a list that contains three different dictionaries in a variable named <code>mydict</code>. The dictionaries have the data of different profiles in them.</p>
</li>
<li><p>Line seven stores strings, which represent the title of each column of the CSV file that you want to create in a variable named <code>fields</code>.</p>
</li>
<li><p>Line nine opens the <em>profiles3.csv</em> file in writing mode using <code>open()</code> function.</p>
</li>
<li><p>The <code>csv.DictWriter()</code> function in line ten creates the CSV dictionary writer object.</p>
</li>
<li><p>Line twelve passes the list of dictionaries to the <code>writer.writeheader()</code> function to write the pre-defined field names.</p>
</li>
</ol>
<p>Once you are done writing the code, go to your command line terminal and navigate to the directory that has the python file <em>profiles3.py</em>. Run the following command:</p>
<pre><code class="lang-sh">python profiles3.py
</code></pre>
<p>Now, you should get a CSV file a named <em>profiles3.csv</em> in your working directory that has the following text in it:</p>
<pre><code class="lang-bash">name,age,country
</code></pre>
<h3 id="heading-the-writerows-method-1">The <code>writerows()</code> Method</h3>
<p>The <strong>writerows()</strong> method has a similar usage as the writeheader() method. You can use the method to write all the rows. The method writes only the values and not the keys.</p>
<p>To use the <strong>writerows()</strong> method, add this line of code to your code in <em>profiles3.py</em>:</p>
<pre><code class="lang-python">writer.writerows(mydict)
</code></pre>
<p>Now delete the <em>profiles3.csv</em> in your working directory and re-run the following command in your command line terminal:</p>
<pre><code class="lang-sh">python profiles3.py
</code></pre>
<p>You should now have a new CSV file named <em>profiles3.csv</em> in your working directory that has the following text in it:</p>
<pre><code class="lang-bash">name,age,country
Kelvin Gates,19,USA
Blessing Iroko,25,Nigeria
Idong Essien,42,Ghana
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Although CSV got its name from a <strong>comma</strong>, the comma is just a delimiter that separates the data.</p>
<p>You should know that a comma is a popular delimiter you will get in most CSV files. However, the delimiter could also be something else. For instance, you can use a semi-colon to separate the data instead of a comma.</p>
<p>If you like this tutorial, kindly <a target="_blank" href="https://twitter.com/activus_d">follow me on Twitter</a> and give me a shout out.</p>
<h3 id="heading-references-and-further-reading">References and Further Reading</h3>
<ul>
<li><a target="_blank" href="https://docs.python.org/3/library/csv.html?highlight=csv">https://docs.python.org/3/library/csv.html?highlight=csv</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is the Jamstack? Tutorial for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ You may have heard the term Jamstack and have been wondering what it means. Well, the Jamstack is nothing more than a modern way of building web applications. Jamstack takes advantage of existing technologies – which we'll discuss in a minute. The re... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/jamstack-for-beginners/</link>
                <guid isPermaLink="false">66d45e0847a8245f78752a1e</guid>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JAMstack ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ markup ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Applications ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Damilola Oladele ]]>
                </dc:creator>
                <pubDate>Thu, 10 Nov 2022 18:30:49 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/11/Damilola-Oladele-2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>You may have heard the term Jamstack and have been wondering what it means. Well, the Jamstack is nothing more than a modern way of building web applications.</p>
<p>Jamstack takes advantage of existing technologies – which we'll discuss in a minute. The result is better performance, improved security, and easier scalability for web applications.</p>
<p>In this article, you'll learn what Jamstack means and the benefits of using this approach in your projects.</p>
<h2 id="heading-what-is-the-jamstack">What is the Jamstack?</h2>
<p>Jamstack is a web development architecture. Matt Biilmann, the CEO of Netlify, popularized it with his presentation at Smashing Conference 2016.</p>
<p>Jamstack is an acronym for Javascript, APIs, and Markup, and is a technology stack you use to build your apps.</p>
<p>This is like the MERN stack (MongoDB, ExpressJS, ReactJS and NodeJS) and the MEAN stack (MongoDB, ExpressJS, Angular and NodeJS) – just with different tools.</p>
<p>Now let's discuss the various components of a Jamstack web application:</p>
<h3 id="heading-javascript">Javascript</h3>
<p>Javascript is the core programming language of the web. It has been around for decades and you can use it both on the client side and the backend with NodeJS.</p>
<p>Javascript is the programming language you use for handling the client side of your Jamstack applications.</p>
<h3 id="heading-apis">APIs</h3>
<p>API is an acronym for <strong>Application Programming Interface</strong>. It's an interface which helps two or more computer programs communicate with each other.</p>
<p>In Jamstack apps, you use APIs to communicate with your backend.</p>
<h3 id="heading-markup">Markup</h3>
<p>Markup refers to standard text-encoding systems consisting of a set of symbols inserted into a text document. Examples of markup languages are <strong>HTML</strong>, <strong>XML</strong>, and templating languages such as <strong>JSX</strong>.</p>
<p>In the Jamstack, markup refers to the content of a Jamstack application. Note that we use markup here in its broader sense. It doesn't refer to text content only but also to the assets of the web application, such as images.</p>
<h2 id="heading-important-features-of-jamstack-apps">Important Features of Jamstack Apps</h2>
<p>To consider an application a Jamstack app, it should meet the following conditions:</p>
<h3 id="heading-distributed-architecture">Distributed Architecture</h3>
<p>This refers to the decoupling of the client side from the backend. The client side handles the presentation of the user interface, and the backend handles business logic and data.</p>
<p>Communication between the frontend and backend happens via a dedicated API. This means that a change or upgrade in one will not affect the other. This results in easier maintenance of the entire web application.</p>
<h3 id="heading-static-sites">Static Sites</h3>
<p>It is important for Jamstack applications to serve static web pages and not dynamic ones.</p>
<p>Traditional web applications are dynamic sites. This means that when you request a page, the backend will have to reach a database to retrieve the data. The data is then used to generate HTML files, and then sent back to the client.</p>
<p>The disadvantage of dynamic sites is how long it takes to complete these steps.</p>
<p>For static sites, the pages are already pre-rendered at build time. So every time you request a page, you get the pre-rendered page.</p>
<p>This eliminates the time that dynamic sites spend in obtaining data, generating HTML files, and sending it back to the client. You can serve your static sites from a <a target="_blank" href="https://www.cloudflare.com/learning/cdn/what-is-a-cdn/">content delivery network (CDN).</a> This will lead to improved speed and reduced costs.</p>
<p>Examples of static site generators that you can use for your Jamstack web applications include:</p>
<ul>
<li><p>NextJS</p>
</li>
<li><p>Gatsby</p>
</li>
<li><p>Hugo</p>
</li>
<li><p>Jekyll</p>
</li>
<li><p>Nuxt</p>
</li>
</ul>
<h2 id="heading-why-should-you-use-the-jamstack-for-your-web-applications">Why Should You Use the Jamstack for your Web Applications?</h2>
<p>Let's now discuss some of the reasons the Jamstack web architecture has become so popular in recent times and why you should consider adopting it:</p>
<h3 id="heading-jamstack-apps-are-scalable">Jamstack Apps Are Scalable</h3>
<p>You can serve most Jamstack applications from a CDN. This allows for the speedy transfer of assets needed for loading web pages.</p>
<p>As a result of the distributed nature of CDNs, your web application will also be able to handle more traffic at a reduced cost.</p>
<h3 id="heading-jamstack-apps-are-easy-to-maintain">Jamstack Apps Are Easy to Maintain</h3>
<p>Jamstack applications are easier to maintain since their client side is decoupled from their backends.</p>
<p>This means that you can maintain one part without requiring major modifications to the other.</p>
<h3 id="heading-jamstack-apps-load-faster">Jamstack Apps Load Faster</h3>
<p>As stated earlier, serving your site from a CDN increases the speed with which it loads.</p>
<p>Also, in Jamstack applications, web pages are prebuilt, saving time that would normally be spent retrieving and generating HTML files every time you make a request.</p>
<h3 id="heading-jamstack-apps-are-cheaper">Jamstack Apps Are Cheaper</h3>
<p>Since Jamstack applications are easier to maintain and deploy, they are cheaper compared to their traditional counterparts.</p>
<h3 id="heading-jamstack-apps-are-more-secure">Jamstack Apps Are More Secure</h3>
<p>Since you do not have to constantly maintain a server in Jamstack applications and the pages are constructed on read-only files (that is, the pages are static), you can worry less about the security of your applications.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Despite the fact that more and more projects are being built using the Jamstack architecture, we're still in the relatively early stages of its adoption.</p>
<p>I believe that more large and small businesses will adopt it in the near future in place of costly monolithic architectures.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Objects in JavaScript – A Beginner's Guide ]]>
                </title>
                <description>
                    <![CDATA[ If you declare multiple variables to hold different values, this can make your program messy and clunky. For instance, if you need to store three characteristics each for 10 individuals, having 30 variables individually declared can make your program... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/objects-in-javascript-for-beginners/</link>
                <guid isPermaLink="false">66d45e0a47a8245f78752a24</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Damilola Oladele ]]>
                </dc:creator>
                <pubDate>Wed, 20 Jul 2022 17:50:17 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/07/shelf4.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you declare multiple variables to hold different values, this can make your program messy and clunky.</p>
<p>For instance, if you need to store three characteristics each for 10 individuals, having 30 variables individually declared can make your program appear less organized.</p>
<p>So you need a way to group values with similar characteristics together to make your code more readable. And in JavaScript, objects work well for this purpose.</p>
<p>Unlike other data types, objects are capable of storing complex values. Because of this, JavaScript relies heavily on them. So it's important that you become familiar with what an object is, how to create one, and how you can use it before going in-depth into learning JavaScript.</p>
<p>This article will introduce you to the basics of objects, object syntax, the different methods of creating objects, how to copy objects and how to iterate over an object.</p>
<p>In order to get the most out of this article, you need to have at least a basic understanding of JavaScript, particularly variables, functions, and data types.</p>
<h2 id="heading-what-are-objects-in-javascript">What Are Objects in JavaScript?</h2>
<p>An object is a data type that can take in collections of key-value pairs.</p>
<p>A major difference between an object and other data types such as strings and numbers in JavaScript is that an objects can store different types of data as its values. On the other hand, primitive data types such as numbers and strings can store only numbers and strings, respectively, as their values.</p>
<p>The key, also known as the property name, is usually a string. If any other data type is used as a property name other than strings, it would be converted into a string.</p>
<p>You can visualize an object as a multi-purpose shelf containing space for your gadgets and ornaments as well as a storage space for books, and files.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/shelf1-2.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>A shelf with several items in it</em></p>
<p>The most recognizable feature of an object is the brackets which contain the key-value pair.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> emptyObject = {};
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> emptyObject); <span class="hljs-comment">//'object'</span>
</code></pre>
<p>The contents of an object can consist of variables, functions, or both. Variables found in objects are properties, while functions are methods. Methods allow the objects to use the properties within them to perform some kind of action.</p>
<p>For example, in the sample code below, <strong>object1.user</strong>, <strong>object1.nationality</strong> and <strong>object1.profession</strong> are all properties of <strong>object1</strong> while <strong>object1.myBio()</strong> is a method:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> object1 = {
    <span class="hljs-attr">user</span>: <span class="hljs-string">"alex"</span>,
    <span class="hljs-attr">nationality</span>: <span class="hljs-string">"Nigeria"</span>,
    <span class="hljs-attr">profession</span>: <span class="hljs-string">"Software Enginneer"</span>,
    myBio() {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`My name is <span class="hljs-subst">${<span class="hljs-built_in">this</span>.user}</span>. I'm a               <span class="hljs-subst">${<span class="hljs-built_in">this</span>.profession}</span> from <span class="hljs-subst">${<span class="hljs-built_in">this</span>.nationality}</span>`</span>)
    }
}
<span class="hljs-built_in">console</span>.log(object1.user); <span class="hljs-comment">//Alex </span>
<span class="hljs-built_in">console</span>.log(object1.nationality); <span class="hljs-comment">//Nigeria </span>
<span class="hljs-built_in">console</span>.log(object1.profession); <span class="hljs-comment">//Software Engineer </span>
<span class="hljs-built_in">console</span>.log(object1.myBio()); <span class="hljs-comment">//My name is alex. I'm a Software Engineer from Nigeria</span>
</code></pre>
<p>The keys in the sample code above are <strong>user</strong>, <strong>nationality</strong> and <strong>profession</strong> while their values are the string values that come after the colons. Also, notice the use of the <strong>this</strong> keyword. The <strong>this</strong> keyword simply refers to the object itself.</p>
<p>As mentioned earlier in this article, the value of a property can be any data type. In the following sample code, the values are both arrays and objects:</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">const</span> object2 = { 
        <span class="hljs-attr">users</span>: [<span class="hljs-string">"Alex"</span>, <span class="hljs-string">"James"</span>, <span class="hljs-string">"Mohammed"</span>], 
        <span class="hljs-attr">professions</span>: { 
            <span class="hljs-attr">alex</span>: <span class="hljs-string">"software engineer"</span>, 
            <span class="hljs-attr">james</span>: <span class="hljs-string">"lawyer"</span>, 
            <span class="hljs-attr">mohammed</span>: <span class="hljs-string">"technical writer"</span> 
        } 
    }; 
    <span class="hljs-built_in">console</span>.log(object2.users); <span class="hljs-comment">//['Alex', 'James', 'Mohammed'] </span>
    <span class="hljs-built_in">console</span>.log(object2.professions); <span class="hljs-comment">//{alex: 'software engineer', james: 'lawyer', mohammed: 'technical writer'}</span>
</code></pre>
<h2 id="heading-how-to-access-objects-and-create-new-object-properties-or-methods-in-javascript">How to Access Objects and Create New Object Properties or Methods in JavaScript</h2>
<p>There are two ways to access objects: dot notation and bracket notation. In the previous sample code, we used dot notation to access the properties and methods in <strong>object1</strong> and <strong>object2</strong>.</p>
<p>Also, to create new properties and methods after the declaration of an object, you can use either dot notation or bracket notation. You just have to state the new property and give it a value.</p>
<p>For instance, we can add new properties to <strong>object2</strong> like this:</p>
<pre><code class="lang-javascript">object2.ages = [<span class="hljs-number">30</span>, <span class="hljs-number">32</span>, <span class="hljs-number">40</span>];
object2[<span class="hljs-string">"summary"</span>] = <span class="hljs-string">`Object2 has <span class="hljs-subst">${object2.users.length}</span> users`</span>;
<span class="hljs-built_in">console</span>.log(object2);
<span class="hljs-comment">/*
{
    "users": [
        "Alex",
        "James",
        "Mohammed"
    ],
    "professions": {
        "alex": "software engineer",
        "james": "lawyer",
        "mohammed": "technical writer"
    },
    "ages": [
        30,
        32,
        40
    ],
    "summary": "Object2 has 3 users"
}
*/</span>
</code></pre>
<p>Similarly, you can use either notation to change the value of an object:</p>
<pre><code class="lang-javascript">object2.users = [<span class="hljs-string">"jane"</span>, <span class="hljs-string">"Williams"</span>, <span class="hljs-string">"John"</span>];
object2[<span class="hljs-string">"age"</span>] = [<span class="hljs-number">20</span>, <span class="hljs-number">25</span>, <span class="hljs-number">29</span>]
<span class="hljs-built_in">console</span>.log(object2.users); <span class="hljs-comment">//['jane', 'Williams', 'John']</span>
<span class="hljs-built_in">console</span>.log(object2.ages) <span class="hljs-comment">//[20, 25, 29</span>
</code></pre>
<p>Although dot notation is the most commonly used to access an object's properties and methods, it has some limitations. Let's look at them now.</p>
<h3 id="heading-you-cant-use-values-as-property-names-with-dot-notation">You Can't Use Values as Property Names with Dot Notation</h3>
<p>If you want to use the value of a variable as a property name in your object, you have to use bracket notation and not dot notation. Whether the variable value is defined at runtime or not is irrelevant.</p>
<p>Runtime is a phase of a computer program in which the program is run or executed on a computer system.</p>
<p>For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> object3 = {};
<span class="hljs-keyword">const</span> gadget = prompt(<span class="hljs-string">"enter a gadget type"</span>); 
object3[gadget] = [<span class="hljs-string">"jbl"</span>, <span class="hljs-string">"sony"</span>]; 
<span class="hljs-built_in">console</span>.log(object3) <span class="hljs-comment">//(respose entered in prompt): ["jbl","sony"] notice that the property name is the value you enter in the reply to the prompt message</span>
</code></pre>
<p>If you define the variable value in your code, and you use dot notation to set that value as a property name of your object, dot notation will create a new property with the variable name instead of with the variable value.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> computer = <span class="hljs-string">"brands"</span>
object3.computer = [<span class="hljs-string">"hp"</span>, <span class="hljs-string">"dell"</span>, <span class="hljs-string">"apple"</span>]
<span class="hljs-built_in">console</span>.log(object3.brands); <span class="hljs-comment">//undefined</span>
<span class="hljs-built_in">console</span>.log(object3.computer)<span class="hljs-comment">//['hp', 'dell', 'apple']</span>

object3[computer] = [<span class="hljs-string">"hp"</span>, <span class="hljs-string">"dell"</span>, <span class="hljs-string">"apple"</span>]
<span class="hljs-built_in">console</span>.log(object3.brands) <span class="hljs-comment">//['hp', 'dell', 'apple']</span>
</code></pre>
<p>Notice the omission of quotes within the square brackets. This is because the brackets took in a variable.</p>
<h3 id="heading-you-cant-use-multi-word-properties-with-dot-notation">You Can't Use Multi-Word Properties with Dot Notation</h3>
<p>Where the property name is a multi-word string then dot notation is insufficient. For instance:</p>
<pre><code class="lang-javascript">object3.users height = [<span class="hljs-number">5.6</span>, <span class="hljs-number">5.4</span>, <span class="hljs-number">6.0</span>];
Console.log(object3.users height); <span class="hljs-comment">//SyntaxError</span>
</code></pre>
<p>A syntax error occurs because JavaScript reads the command as <code>object3.users</code>, but the string height is not recognized so it returns a syntax error.</p>
<p>When using dot notation to access objects, the usual rules of declaring a variable apply. This means that if you want to use dot notation to access an object or create a property, the property name must not start with a number, must not include any spaces, and can only include the special characters <em>$</em> and _<em>.</em></p>
<p>To avoid this kind of error, you have to use bracket notation. For instance, you can correct the above sample code like this:</p>
<pre><code class="lang-javascript">object3[<span class="hljs-string">"users height"</span>] = [<span class="hljs-number">5.6</span>, <span class="hljs-number">5.4</span>, <span class="hljs-number">6.0</span>];  
<span class="hljs-built_in">console</span>.log(object3[<span class="hljs-string">"users height"</span>]); <span class="hljs-comment">//[5.6, 5.4, 6]</span>
</code></pre>
<h2 id="heading-how-to-create-objects-with-the-object-constructor-in-javascript">How to Create Objects with the Object Constructor in JavaScript</h2>
<p>There are two methods by which you can create an object: an object literal and the object constructor. The objects used so far as samples in this article are object literals. Object literals work well if you want to create a single object.</p>
<p>But if you want to create more than one object, it is always better to use the object constructor. This allows you to avoid unnecessary repetition in your code and also makes it easier to change the properties of your object.</p>
<p>Basically, constructors are functions whose names are usually capitalized. The capitalization of a constructor name does not have any effect on the object. It is only a means of identification.</p>
<p>You can use a constructor to create a new object by calling the constructor with the <strong>new</strong> keyword. The <strong>new</strong> keyword will create an instance of an object and bind the <strong>this</strong> keyword to the new object.</p>
<p>As earlier mentioned in this article, the <strong>this</strong> keyword is a reference to the object itself.</p>
<p>An example of an object constructor is:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Profile</span>(<span class="hljs-params">name, age, nationality</span>) </span>{ 
    <span class="hljs-built_in">this</span>.name = name; 
    <span class="hljs-built_in">this</span>.age = age; 
    <span class="hljs-built_in">this</span>.nationality = nationality; 
    <span class="hljs-built_in">this</span>.bio = <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">`My name is <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>. I'm <span class="hljs-subst">${<span class="hljs-built_in">this</span>.age}</span> years old. I'm from <span class="hljs-subst">${<span class="hljs-built_in">this</span>.nationality}</span>`</span>) 
    } 
};

<span class="hljs-keyword">const</span> oladele = <span class="hljs-keyword">new</span> Profile(<span class="hljs-string">"Oladele"</span>, <span class="hljs-number">50</span>, <span class="hljs-string">"Nigeria"</span> );
<span class="hljs-built_in">console</span>.log(oladele.bio()); <span class="hljs-comment">//My name is Oladele. I'm 50 years old. I'm from Nigeria</span>
</code></pre>
<h2 id="heading-how-to-create-object-copies-in-javascript">How to Create Object Copies in JavaScript</h2>
<p>Unlike primitive data types such as strings and numbers, assigning an existing object to another variable will not produce a copy of the original but rather a reference in memory.</p>
<p>What this means is that both the original object and subsequent objects created by assigning the original object as a value are referencing the same item in memory.</p>
<p>This means that a change in the value of any of the objects will also cause a change in the others. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> x = <span class="hljs-number">10</span>;
<span class="hljs-keyword">let</span> y = x;
x = <span class="hljs-number">20</span>;
<span class="hljs-built_in">console</span>.log(x); <span class="hljs-comment">//20</span>
<span class="hljs-built_in">console</span>.log(y); <span class="hljs-comment">//10</span>

<span class="hljs-keyword">let</span> object4 = { 
    <span class="hljs-attr">name</span>: <span class="hljs-string">"Alex"</span>, 
    <span class="hljs-attr">age</span>: <span class="hljs-number">40</span> 
}; 
<span class="hljs-keyword">let</span> object5 = object4; 
<span class="hljs-built_in">console</span>.log(object5); <span class="hljs-comment">//{name: 'Alex', age: 40} </span>
object4.name = <span class="hljs-string">"Jane"</span>; 
<span class="hljs-built_in">console</span>.log(object5); <span class="hljs-comment">//{name: 'Jane', age: 40}</span>
<span class="hljs-built_in">console</span>.log(object4 === object5); <span class="hljs-comment">//true</span>
</code></pre>
<p>To create a copy of an object, you can use the spread operator.</p>
<h3 id="heading-what-is-the-spread-operator">What is the Spread Operator?</h3>
<p>The spread operator is represented by three dots <code>...</code> . You can use the spread operator to copy the values of any iterable including objects.</p>
<p>An iterable is an object which can be looped over or iterated over with the help of a for...loop. Examples of iterables include objects, arrays, sets, strings, and so on.</p>
<p>To use the spread operator, you will have to prefix it to the object you want to copy from. For instance:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> object6 = {...object5}; 
object5.name = <span class="hljs-string">"Willaims"</span>; 
<span class="hljs-built_in">console</span>.log(object5); <span class="hljs-comment">//{name: 'Willaims', age: 40}</span>
<span class="hljs-built_in">console</span>.log(object6); <span class="hljs-comment">//{name: 'Jane', age: 40}</span>
<span class="hljs-built_in">console</span>.log(object5 === object6); <span class="hljs-comment">//false</span>
</code></pre>
<p>As you can see, unlike in the previous code sample, where a change in the <strong>object4</strong> caused a change in <strong>object5</strong>, the change in <strong>object6</strong> did not result in a change in <strong>object5</strong>.</p>
<h3 id="heading-how-to-use-the-objectassign-method">How to Use the Object.assign() Method</h3>
<p>The <strong>Object.assign()</strong> method copies all enumerable properties of one object into another and then returns the modified object.</p>
<p>The method takes in two parameters. The first parameter is the target object which takes in the properties copied. The second parameter is the source object which has the properties you want to copy. For instance :</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> object7  = <span class="hljs-built_in">Object</span>.assign({}, object6); 
<span class="hljs-built_in">console</span>.log(object7); <span class="hljs-comment">//{name: 'Jane', age: 40}</span>
<span class="hljs-built_in">console</span>.log(object7); <span class="hljs-comment">//{name: 'Jane', age: 40}</span>

<span class="hljs-built_in">console</span>.log(object6 === object7); <span class="hljs-comment">//false</span>
object6.age = <span class="hljs-number">60</span>
<span class="hljs-built_in">console</span>.log(object6); <span class="hljs-comment">//{name: 'Jane', age: 60}</span>
<span class="hljs-built_in">console</span>.log(object7); <span class="hljs-comment">//{name: 'Jane', age: 40</span>
</code></pre>
<p>You can see from the above sample code that a change in the value of the <strong>age</strong> property of <strong>object6</strong> did not cause a change in the vale of the <strong>age</strong> property of <strong>object7</strong>.</p>
<p>Note that both the spread operator and the <strong>Object.assign()</strong> method can only make a shallow copy of an object.</p>
<p>This means that if you have deeply nested objects or arrays in your source object, only the references to such objects are copied into the target object. So a change in the value of any of the deeply nested objects would cause a change in the value of the deeply nested object of the other. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> objectX = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Mary'</span>, 
    <span class="hljs-attr">age</span>: <span class="hljs-number">40</span>,
    <span class="hljs-attr">gadgets</span>: { 
        <span class="hljs-attr">brand</span>: [<span class="hljs-string">"apple"</span>, <span class="hljs-string">"sony"</span>]
    }
};

<span class="hljs-keyword">let</span> objectY = {...objectX};
objectY.name = <span class="hljs-string">"Bianca"</span>;
objectY.gadgets.brand[<span class="hljs-number">0</span>] = <span class="hljs-string">"hp"</span>;
<span class="hljs-built_in">console</span>.log(objectX);
<span class="hljs-comment">/*
{
    "name": "Mary",
    "age": 40,
    "gadgets": {
        "brand": [
            "hp",
            "sony"
        ]
    }
}
*/</span> 

<span class="hljs-built_in">console</span>.log(objectY);
<span class="hljs-comment">/*
{
    "name": "Bianca",
    "age": 40,
    "gadgets": {
        "brand": [
            "hp",
            "sony"
        ]
    }
}
*/</span>
</code></pre>
<p>The above sample code performed the following actions:</p>
<ol>
<li><p>Created an object named <strong>objectX</strong>.</p>
</li>
<li><p>Gave three properties to <strong>objectX</strong>: name, age and gadgets.</p>
</li>
<li><p>Gave the <strong>gadgets</strong> property of <strong>objectX</strong> an object as its value.</p>
</li>
<li><p>Gave the object value of the <strong>gadget</strong> property a <strong>brand</strong> property.</p>
</li>
<li><p>Gave the <strong>brand</strong> property an array as its value.</p>
</li>
<li><p>Copied the properties in <strong>objectX</strong> into <strong>objectY</strong> with the use of the spread operator.</p>
</li>
<li><p>Changed the value of the <strong>name</strong> property of <strong>objectY</strong> to <strong>Mary</strong>.</p>
</li>
<li><p>Changed the the first item in the array value of the <strong>brand</strong> property from <strong>apple</strong> to <strong>hp</strong>.</p>
</li>
</ol>
<p>In the sample code, the array value is a deeply nested object. Notice that a change in the value of the <strong>name</strong> property of <strong>objectY</strong> did not cause a change in the value of the <strong>name</strong> property of <strong>objectX</strong>. But a change in the deeply nested object of <strong>objectY</strong> caused a similar change in the deeply nested object of <strong>objectX</strong> .</p>
<h2 id="heading-how-to-iterate-over-objects-in-javascript">How to Iterate Over Objects in JavaScript</h2>
<p>Use a <strong>for...in</strong> loop to iterate over an object and to select its properties. The <strong>for..in</strong> loop syntax is as follows:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> key <span class="hljs-keyword">in</span> object) {
    <span class="hljs-comment">//perform action(s) for each key</span>
}
</code></pre>
<p>The <strong>key</strong> keyword in the syntax above is a parameter for the properties. So you can replace it with any word of your choice. Replace the object keyword with the name of the object you want to iterate over. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> objectZ = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"Ade"</span>,
    <span class="hljs-attr">Pronuon</span>: <span class="hljs-string">"he"</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">60</span>
};
<span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> property <span class="hljs-keyword">in</span> objectZ) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${property}</span>: <span class="hljs-subst">${objectZ[property]}</span>`</span>)
}
<span class="hljs-comment">/* 
name: Ade
Pronuon: he
age: 60
*/</span>
</code></pre>
<p>Notice the use of bracket notation in the loop to get the values of the property. Using dot notation instead of bracket notation would return undefined.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In JavaScript, objects are probably the most important data type. Programming concepts like Object-Oriented programming work on the principle of leveraging the flexibility of objects to store complex values and their distinct capability of interacting with properties and methods within the object.</p>
<p>This article lays a solid foundation for understanding such advanced concepts by explaining the basics of objects.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Stay Motivated While Learning to Code ]]>
                </title>
                <description>
                    <![CDATA[ Learning to code can be like preparing for a long battle. Ultimately, winning is not always determined by your initial strength, but by how well prepared you are and how long you can hold out. With programming, the greatest challenge is often not the... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-stay-motivated-while-learning-to-code/</link>
                <guid isPermaLink="false">66d45e04d1ffc3d3eb89ddb5</guid>
                
                    <category>
                        <![CDATA[ Habit Building ]]>
                    </category>
                
                    <category>
                        <![CDATA[ learning to code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ motivation ]]>
                    </category>
                
                    <category>
                        <![CDATA[ self-improvement  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Damilola Oladele ]]>
                </dc:creator>
                <pubDate>Thu, 30 Jun 2022 17:54:56 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/06/cover-i-age-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Learning to code can be like preparing for a long battle. Ultimately, winning is not always determined by your initial strength, but by how well prepared you are and how long you can hold out.</p>
<p>With programming, the greatest challenge is often not the complexity of the language, but rather staying consistent and motivated through the learning process.</p>
<p>In order to stay consistent with your learning, you will need a lot of motivation and energy. The consistency with which you learn would help you to understand the complex concepts of any programming language and make the most of your time.</p>
<p>Having come from an absolutely non-technical background, I had to learn this late. After I took the first step into the transition, I struggled with everything relating to learning, particularly motivation.</p>
<p>This article will share the steps I have gathered over time to overcome my struggles with staying consistent and motivated.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Testudo_formation-1.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-start-slowly-but-maintain-a-habit">Start Slowly but Maintain a Habit</h2>
<p>In the early stage of learning, you might only have a few free hours that you can dedicate to learning.</p>
<p>This is because most people are just opening themselves up to doing something they have never done before. Also, they might have tasks such as a full-time job which take a better part of their daily life. Therefore, adjusting and making time for learning might not be easy.</p>
<p>At this stage, you don't need to be concerned about the amount of time you have available to learn in one sitting. The most important thing is making time for a daily study session, regardless of its length, and persisting with it in spite whatever crops up in the way.</p>
<h2 id="heading-always-schedule-your-tasks">Always Schedule Your Tasks</h2>
<p>If you don't schedule your daily tasks, it's much easier to procrastinate and forget about them. It's easy to become engrossed in just one or few tasks and lose sight of the fact that there are other things you need to do. Often, this happens when you don't follow a set task list.</p>
<p>To prevent procrastination and forgetfulness, make sure you plan out your days by scheduling tasks. You can use the following tips as a guide in scheduling your tasks:</p>
<ol>
<li><p>Think of all the tasks you would like to accomplish.</p>
</li>
<li><p>Estimate how long it will take to accomplish each task.</p>
</li>
<li><p>Identify your peak hours of productivity.</p>
</li>
<li><p>Arrange the tasks in order of priority.</p>
</li>
<li><p>Make sure to bundle similar tasks together to improve your productivity.</p>
</li>
<li><p>To stay organized, schedule these tasks on your phone or computer and use reminder and task applications.</p>
</li>
<li><p>Schedule complex or difficult tasks during your peak productivity hours.</p>
</li>
<li><p>Make time for unexpected events in your schedule and plan for them ahead of time.</p>
</li>
</ol>
<p>Note that it is a good idea to schedule your tasks at the beginning of every week.</p>
<p>To learn more about how you can schedule your day for better productivity, consider reading <a target="_blank" href="https://www.calendar.com/blog/how-to-schedule-your-day-for-optimal-productivity/">this article by John Rampton, the co-founder and CEO of Calendar.</a></p>
<h2 id="heading-join-a-community-of-learners">Join a Community of Learners</h2>
<p>For most people, learning alone can be boring and tedious, and in no time, it can hurt your motivation. This is why having a community of like-minded people is always better.</p>
<p>This type of community will provide you numerous benefits, including, but not limited to:</p>
<ul>
<li><p>access to group study</p>
</li>
<li><p>access to different resources to help with your study</p>
</li>
<li><p>information on current technological trends</p>
</li>
<li><p>getting feedback on personal projects</p>
</li>
<li><p>an avenue to share your progress and measure your growth</p>
</li>
</ul>
<p>Find out if this type of community exists in your area. Alternatively, if you are unable to find one, you can join a remote learning community instead.</p>
<p>The following are some of the remote communities I have personally found useful and consider to be of great value:</p>
<ul>
<li><p><strong>100Devs:</strong> The 100devs community is a nonprofit organization founded and maintained by Leon Noel, a teacher and Managing Director of Engineering at ResilientCoders. The 100Devs community provides free lessons in full-stack web development to individuals. You can join the 100Devs community <a target="_blank" href="https://t.co/N1svwNfVRd">here</a>.</p>
</li>
<li><p><strong>100DaysofCode:</strong> 100DaysofCode is an online challenge where people dedicate 100 days to learning a programming language of their choice. In order to participate in 100DaysofCode, you must devote at least an hour a day to learning. And after that, you post a completed task on Twitter with the hashtag #100DaysofCode.</p>
</li>
<li><p><strong>Kevin Powell Community:</strong> The Kevin Powell Community of active learners is a community on discord created and maintained by Kevin Powell. Kevin is a teacher and software developer with years of experience. You can join the Kevin Powell Community on <a target="_blank" href="https://discord.gg/9NmT5HxN">discord</a>.</p>
</li>
<li><p><strong>Commit Your Code:</strong> The Commit Your Code community is created and maintained by Danny Thompson. The community has a lot of active learners as well as experienced developers who are more than willing to help you with your projects and mentorship. You can join the Commit Your Code community on <a target="_blank" href="https://discord.gg/3JvHFCCp">discord</a>.</p>
</li>
</ul>
<p>And of course the freeCodeCamp community has a <a target="_blank" href="https://forum.freecodecamp.org/">supportive and friendly forum</a> where you can ask questions and meet other developers.</p>
<p>After joining one or more of these communities, it is important to be on your best behaviour. Keep in mind to also be kind, provide value, and follow their rules.</p>
<h2 id="heading-find-a-study-partner">Find a Study Partner</h2>
<p>Being consistent and motivated may be hard even after scheduling your tasks and joining a study community. If this is the case, you might need a study partner.</p>
<p>You can benefit from having a study partner in the following ways:</p>
<ul>
<li><p>Makes sure you have accountability.</p>
</li>
<li><p>You can set up joint study sessions.</p>
</li>
<li><p>You can collaborate on joint projects.</p>
</li>
<li><p>You might find mentorship.</p>
</li>
<li><p>You can go through coding challenges together.</p>
</li>
</ul>
<h2 id="heading-use-an-efficient-study-technique">Use an Efficient Study Technique</h2>
<p>Programming languages are generally complex. Unless you have an effective study technique, it will be difficult to understand the concepts and apply them in practical contexts. This can make you frustrated and lessen your motivation to learn.</p>
<p>If you're learning new concepts or a new programming language, here are some study techniques you might have tried:</p>
<ul>
<li><p>repetitive reading, otherwise known as re-reading</p>
</li>
<li><p>highlighting</p>
</li>
<li><p>summarizing or making notes</p>
</li>
<li><p>cramming</p>
</li>
</ul>
<p>But there's lots of evidence from prominent scientists and psychologists that has proven that these techniques are less effective when compared to other study techniques you can use.</p>
<p>To make the best use of your time and ensure you remember what you have studied for a longer time, try the following study techniques:</p>
<h3 id="heading-active-recall">Active Recall</h3>
<p>Active recall is a study technique that involves retrieving already stored information from your brain.</p>
<blockquote>
<p>The mind is a vast storehouse or space; memories are objects stored in that space; and retrieving a memory is akin to searching for and finding an object in a physical space (Roediger, 1980).</p>
</blockquote>
<p>Using this technique involves reading a topic once and then converting concepts and ideas in the topic you have read into questions and then testing yourself on them.</p>
<h3 id="heading-spaced-repetition">Spaced Repetition</h3>
<p>This study technique, as its name suggests, involves spacing revisions of what you have learned by way of active recalling. This is in contrast to cramming, which involves memorizing all the concepts in a particular topic in a single sitting.</p>
<p>Essentially, spaced repetition helps you minimize the effect of The Forgetting Curve. It is a mode of learning by which you allow yourself to forget what you have learned. Then you try to retrieve those concepts from your brain by making active recalls at specific intervals over a period of time.</p>
<blockquote>
<p>The forgetting curve hypothesizes the decline of memory retention in time. This curve shows how information is lost over time when there is no attempt to retain it. (<a target="_blank" href="https://en.wikipedia.org/wiki/Forgetting_curve">Source</a>)</p>
</blockquote>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/The-Forgetting-Curve-and-Spaced-Repetition.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Using the above study techniques will help you make sure that you are not spending too much time understanding and remembering any topic or concepts.</p>
<p>In addition, you will have more time to complete other tasks on your list, as well as the opportunity to learn new skills that will be helpful in your professional development.</p>
<p>One popular tool you can use to help with active recall and spaced repetition is Anki. Learn how to use Anki <a target="_blank" href="https://leananki.com/how-to-use-anki-tutorial/#:~:text=You%20just%20open%20the%20app,spacebar%20to%20show%20the%20answer.&amp;text=Using%20Anki%20default%20settings%2C%20Anki,you%20to%20recall%20the%20card.">here</a>.</p>
<p>To learn more about the use of these efficient study techniques, watch the video below:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/ukLnPbIffxE" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<h3 id="heading-pomodoro-timer">Pomodoro timer</h3>
<p>The Pomodoro study technique is ideal for people who struggle to concentrate on studying for a lengthy period of time.</p>
<p>One way to use this technique is to break your workday into 30 or 20 minute chunks separated by five minute breaks. These intervals are called Pomodoros.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/pomodoro.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-set-short-term-goals-and-stay-focused-on-achieving-one-goal-at-a-time">Set Short Term Goals and Stay Focused on Achieving One Goal at a Time</h2>
<blockquote>
<p>Success doesn't happen overnight.</p>
</blockquote>
<p>Trying to achieve too many objectives at the same time can be overwhelming. So it's always better to break your objective into shorter chunks of goals and focus on accomplishing one of the chunks or goals at a time.</p>
<p>For instance, let's say your goal is to be able to build a webpage with any of the popular JavaScript framework as a beginner. To do that, you'll need to learn various scripting and programming languages, tools, and skills. Here's what you should know to build a webpage:</p>
<ol>
<li><p>Understand the <a target="_blank" href="https://www.freecodecamp.org/news/learn-html-beginners-course/">basics of HTML</a>.</p>
</li>
<li><p>Understand the <a target="_blank" href="https://www.freecodecamp.org/news/learn-css-in-this-free-6-hour-video-course/">basics of CSS</a>.</p>
</li>
<li><p>Understand the use of <a target="_blank" href="https://www.freecodecamp.org/news/semantic-html-alternatives-to-using-divs/">semantic elements in HTML</a>.</p>
</li>
<li><p>Understand the use of <a target="_blank" href="https://www.freecodecamp.org/news/css-flexbox-and-grid-tutorial/">CSS Flexbox and Grid for layouts</a>.</p>
</li>
<li><p>Try building a simple static website with what you have learned so far.</p>
</li>
<li><p>Start learning the <a target="_blank" href="https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/">basics of JavaScript</a>.</p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/javascript-projects-for-beginners/">Focus on building projects</a> with your knowledge of HTML, CSS and the basics of JavaScript you have learned so far.</p>
</li>
<li><p>Start learning advanced JavaScript concepts such as <a target="_blank" href="https://www.freecodecamp.org/news/how-javascript-implements-oop/">Objective Oriented Programming</a>, and <a target="_blank" href="https://www.freecodecamp.org/news/synchronous-vs-asynchronous-in-javascript/">Asynchronous Programming</a>.</p>
</li>
<li><p>Solidify you knowledge on the advanced concepts by building projects with them.</p>
</li>
<li><p>Learn the JavaScript framework of your choice. <a target="_blank" href="https://www.freecodecamp.org/news/learn-react-basics/">React</a>, <a target="_blank" href="https://www.freecodecamp.org/news/vue-js-full-course/">Vue</a>, and <a target="_blank" href="https://www.freecodecamp.org/news/learn-angular-full-course/">Angular</a> are all popular choices.</p>
</li>
<li><p>Finally you can build your favourite project using the framework you have learned.</p>
</li>
</ol>
<p>You might think that going through the steps above in the order they are stated would take you a few months. But it may take you much longer than that – and that's ok.</p>
<p>Also, don't try to skip any of these steps. Simply taking a crash web dev course likely won't be enough, and can set you up for disappointment and cause you to struggle much more than you would if you'd taken your time learning the concepts thoroughly.</p>
<p>On the other hand, making sure that you carefully go through each of the steps, one at a time, will help you to build the skills necessary to achieve your main goal. It will also prevent you from losing motivation, which is the likely result of having unrealistic expectations.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/a-step-at-a-time.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-dont-be-afraid-to-ask-for-help">Don't be Afraid to Ask for Help</h2>
<p>One of the reasons why people give up early when learning programming is because they encounter some sort of bug in their program that seems difficult to solve.</p>
<p>But you should know that no one knows it all when it comes to programming. Even software developers with decades of experience still encounter bugs they find very hard to solve on their own.</p>
<p>This is a major reason why collaboration is so important – even more so than developing your personal skills.</p>
<p>Whenever you find yourself in this situation, do not linger on the problem for too long. Use the internet to your advantage when searching for answers. In this regard, your best friend is Google. You can get the answer to almost everything related to programming on Google if you take your time and search deeply.</p>
<p>If you are unable to get the answer you need from searching on Google, then the next step to take is to go to the study community you belong to get help from others. They will typically be more than willing to help you, whatever the problem may be.</p>
<p>Take note of the following when seeking help from your community:</p>
<ul>
<li><p>Make sure to ask direct questions.</p>
</li>
<li><p>Make sure your questions are clear enough to understand.</p>
</li>
<li><p>Provide a copy of your code by putting them in a public remote repository such as <a target="_blank" href="https://github.com/">GitHub</a> or C<a target="_blank" href="https://codepen.io/">odepen</a> and provide the link to the repository.</p>
</li>
</ul>
<h2 id="heading-maintain-a-healthy-lifestyle">Maintain a Healthy Lifestyle</h2>
<p>I can't overemphasize the benefits of maintaining a healthy lifestyle. It will help your maintain energy and keep you fit for the next challenge.</p>
<p>There are several ways to maintain a healthy lifestyle, some of which are:</p>
<ul>
<li><p>Get regular exercise to help your cognitive abilities and general fitness.</p>
</li>
<li><p>Don't sit for lengthy periods of time.</p>
</li>
<li><p>Exercise your fingers regularly while you're studying.</p>
</li>
<li><p>Keep your eyes off your screen at regular intervals while you study.</p>
</li>
<li><p>Make time for your hobbies as a reward for your efforts.</p>
</li>
<li><p>Ensure you always sleep well and get a proper amount of rest.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Programming is a marathon, not a sprint. If you want to achieve any level of success, you have to take your time and study consistently.</p>
<p>Taking the steps discussed in this article will significantly improve your chances of reaching your goals.</p>
<p>If you enjoy this article, then you should give me a <a target="_blank" href="https://twitter.com/activus_d">shout-out</a>.</p>
<h2 id="heading-further-reading-and-references">Further Reading and References</h2>
<ol>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=ukLnPbIffxE">Retrieval creates learning</a>.</p>
</li>
<li><p><a target="_blank" href="https://en.wikipedia.org/wiki/Forgetting_curve">The forgetting curve.</a></p>
</li>
<li><p><a target="_blank" href="https://apps.ankiweb.net/">Download Anki, a powerful tool for active recall and spaced repetition</a>.</p>
</li>
</ol>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is the DOM? The Document Object Model Explained in Plain English ]]>
                </title>
                <description>
                    <![CDATA[ Modern web pages are dynamic. This means we need a suitable and convenient way to modify and manipulate a web document's structure. This modification in an HTML document, for instance, usually takes the form of creating, adding, or removing elements ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-the-dom-explained-in-plain-english/</link>
                <guid isPermaLink="false">66d45e0e3dce891ac3a967da</guid>
                
                    <category>
                        <![CDATA[ Document Object Model ]]>
                    </category>
                
                    <category>
                        <![CDATA[ DOM ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Damilola Oladele ]]>
                </dc:creator>
                <pubDate>Wed, 22 Jun 2022 17:54:50 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/06/DOM-cover-2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Modern web pages are dynamic. This means we need a suitable and convenient way to modify and manipulate a web document's structure.</p>
<p>This modification in an HTML document, for instance, usually takes the form of creating, adding, or removing elements in the document.</p>
<p>In this article, you'll learn what the <strong>Document Object Model (DOM)</strong> is, a bit about its history, and how you use it to manipulate web documents, especially HTML documents.</p>
<h2 id="heading-what-is-the-document-object-model-dom">What is the Document Object Model (DOM)?</h2>
<p>The DOM is a web interface, developed and released by the <strong>World Wide Web Consortium (</strong><a target="_blank" href="https://www.w3.org/"><strong>W3C</strong></a><strong>)</strong>. This organization was founded to establish standards for the World Wide Web.</p>
<p>The DOM is a web API that is language-neutral. This means that you can implement and adopt it in any programming language.</p>
<p>The DOM represents the structural pieces of a web document as objects that can be accessed and manipulated. In other words, the DOM allows you as a software developer to do the following:</p>
<ul>
<li><p>Create and build web documents.</p>
</li>
<li><p>Navigate the structure of web documents.</p>
</li>
<li><p>Add, modify, or delete elements and content within web documents.</p>
</li>
</ul>
<h2 id="heading-history-of-the-dom">History of the DOM</h2>
<p>The history of the DOM is relative to JavaScript and JScript as the first widely used scripting languages. These languages helped make web pages interactive.</p>
<p>Prior to the development of a standard DOM specification by the W3C, JavaScript and JScript had different ways of enabling access to manipulating HTML documents.</p>
<p>These limited methods and interfaces that let you manipulate HTML documents in this way became the <strong>DOM Level 0</strong>.</p>
<p>In 1998, the W3C completed its draft of the first standard DOM specification, which became the recommended standard for all browsers. This standard DOM specification became <strong>DOM Level 1</strong>. The DOM level 1 provided a comprehensive model for manipulating both HTML and XML documents.</p>
<p>In 2000, the W3C released <strong>DOM Level 2</strong>, which introduced methods such as <code>getElementById()</code>, as well as a standardized event model and support for XML namespaces and CSS.</p>
<p>The <strong>DOM Level 3</strong>, released in 2004, added support for XPath and keyboard event handling. And in late 2015, the latest DOM specification, <strong>DOM Level 4</strong>, became a published standard.</p>
<h2 id="heading-what-is-the-dom-tree">What is the DOM Tree?</h2>
<p>The structural representation created by the DOM is very much like a tree. It has several objects in it known as nodes.</p>
<p>The browser uses the DOM tree representation it builds from an HTML document to determine what to render on a web page. For example, a visual representation of a DOM tree will look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/DOM-tree.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The DOM Tree</em></p>
<p>The HTML document of the above DOM tree looks like this:</p>
<pre><code class="lang-javascript">&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;title&gt;TITLE&lt;/title&gt;
    &lt;link rel="stylesheet" href="style.css"&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div&gt;
        &lt;h1&gt;HELLO WORLD&lt;/h1&gt;
    &lt;/div&gt;
    &lt;a href="link text"&gt;Document Object Model&lt;/a&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h3 id="heading-nodes-vs-elements-in-the-dom">Nodes vs Elements in the DOM</h3>
<p>Often, developers confuse nodes with elements. So we should distinguish between the two early in this article to avoid confusion.</p>
<p><strong>Nodes</strong> are all the components a web page document is made up of. In other words, a web page is collection of nodes.</p>
<p>An <strong>element</strong> is a type of node within a document. For instance, the DOM property <code>nodes.childNodes</code> when used on a parent node will return all the different nodes contained within that specified parent node.</p>
<p>In the example below, the childNodes property is used on the <code>&lt;body&gt;</code> element node of the HTML document given above:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>

<span class="hljs-comment">//select the &lt;body&gt; element node with the DOM method querySelector</span>
<span class="hljs-keyword">const</span> body = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'body'</span>) 
<span class="hljs-comment">//select the children nodes with the &lt;body&gt; element node with the DOM property node.childNodes</span>
<span class="hljs-keyword">const</span> childrenNodes = body.childNodes
<span class="hljs-comment">//console log the children nodes</span>
<span class="hljs-built_in">console</span>.log(childrenNodes)<span class="hljs-comment">//NodeList(5) [text, div, text, a, text]</span>
</code></pre>
<p>Notice that there are five items in the <code>nodeList</code>. This is because we have another type of node, the text nodes, different from the element nodes within the <code>&lt;body&gt;</code> element node.</p>
<p>To investigate this further, go through the following steps in your console:</p>
<ol>
<li><p>Click on the dropdown icon just before "nodeList".</p>
</li>
<li><p>Select the text node by clicking on the dropdown icon before "test".</p>
</li>
<li><p>Check for the textContent option within the list options in the dropdown.</p>
</li>
</ol>
<p>If you follow the above instructions, you will see that the test content of the first text node is "/n ". This is a text node indicating a new line after the <code>&lt;body&gt;</code> element node, the <code>&lt;div&gt;</code> element node, and the <code>&lt;a&gt;</code> element node.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Screenshot--143--1.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-relationships-between-nodes-in-the-dom-tree">Relationships Between Nodes in the DOM Tree</h3>
<p>The nodes in the DOM tree have a hierarchical relationship with each other in the DOM tree. They are defined by their position relative to each other in the DOM tree.</p>
<p>These are the node positions present in the DOM tree illustration above:</p>
<ul>
<li><p><strong>Root node</strong>: The root node is always at the apex of the DOM tree. In an HTML document, the root node is always the <code>&lt;html&gt;</code> element.</p>
</li>
<li><p><strong>Child node</strong>: A child node is a node embedded inside another node. In the illustration given above, the <code>&lt;head&gt;</code> and the <code>&lt;body&gt;</code> elements are the children of the <code>&lt;html&gt;</code> element.</p>
</li>
<li><p><strong>Descendant node</strong>: Any node positioned below another node in the hierarchical order is the descendant of the nodes positioned above it. For example, although the <code>&lt;h1&gt;</code> element is not the direct child of the <code>&lt;body&gt;</code> element, it is a descendant of the <code>&lt;body&gt;</code> and root <code>&lt;html&gt;</code> elements.</p>
</li>
<li><p><strong>Parent node</strong>: Any node which has another node inside it is a parent node. For example, the <code>&lt;body&gt;</code> element is the parent of the <code>&lt;div&gt;</code> and <code>&lt;a&gt;</code> elements in the above example. Note that only element type nodes can be a parent node.</p>
</li>
<li><p><strong>Sibling nodes</strong>: Nodes that are on the same level in hierarchical order in the DOM tree are sibling nodes. For example, <code>&lt;div&gt;</code> and <code>&lt;a&gt;</code> elements in the above example are siblings.</p>
</li>
<li><p><strong>Leaf nodes</strong>: The text inside of elements are leaf nodes. This is because they cannot have children nodes of their own.</p>
</li>
</ul>
<h2 id="heading-htmlcollection-vs-nodelist">HTMLCollection vs nodeList</h2>
<p>To manipulate the DOM tree, you need a way to select individual items or a collection of items in it.</p>
<p>You can use a programming language like JavaScript to select an item or a collection of items in the DOM tree by using a few methods provided by the DOM.</p>
<p>The methods <code>getElementById()</code> and <code>querySelector()</code> can select individual items. The methods <code>getElementsByClassName()</code>, <code>getElementsByTagName()</code>, or <code>querySelectorAll()</code> can select a collection of items.</p>
<p>In the DOM tree, we can either get an HTMLCollection or a NodeList based on the method used to select a collection of items. The <code>getElementsByClassName()</code> and <code>getElementsByTagName()</code> methods return HTMLCollections, while <code>querySelectorAll</code> returns a nodeList.</p>
<p>HTMLCollection and nodeList share some similarities and differences. They're similar in the following ways:</p>
<ul>
<li><p>They are array-like objects.</p>
</li>
<li><p>They are collections of items.</p>
</li>
<li><p>They can be converted into an array by using the <code>Array.from()</code> method.</p>
</li>
<li><p>They both have a zero-based indexing.</p>
</li>
<li><p>They can both be iterated over with a for...loop.</p>
</li>
<li><p>They have a length property.</p>
</li>
<li><p>They do not have array methods available to them.</p>
</li>
</ul>
<p>Below is a sample HTML document and JavaScript code to emphasize these similarities:</p>
<pre><code class="lang-html"><span class="hljs-comment">&lt;!-- html documant --&gt;</span>

<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> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</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">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Document<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">ul</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>item one<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 two<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 three<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 four<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 class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"main.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>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>

<span class="hljs-keyword">const</span> listItemsHtmlCollection = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">"li"</span>)
<span class="hljs-built_in">console</span>.log(listItemsHtmlCollection) <span class="hljs-comment">// HTMLCollection(4) [li, li, li, li]</span>

<span class="hljs-keyword">const</span> listItemsNodeList = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">"li"</span>)
<span class="hljs-built_in">console</span>.log(listItemsNodeList) <span class="hljs-comment">// NodeList(4) [li, li, li, li]</span>
</code></pre>
<p>You can see from the above that while the <code>getElementsByTagName</code> returns an HTMLCollection with items matching the <code>&lt;li&gt;</code> tag specified, the <code>querySelectorAll</code> returns a nodeList.</p>
<p>Now, let's use a for...loop to iterate on both collections:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; listItemsHtmlCollection.length; i++) {
    listItemsHtmlCollection[i].style.color = <span class="hljs-string">'red'</span>
}

<span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; listItemsHtmlCollection.length; i++) {
    listItemsHtmlCollection[i].style.color = <span class="hljs-string">'red'</span>
}
</code></pre>
<p>In both instances the color of the text will be changed to red.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Screenshot--145-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now let's delete the for...loop iteration and use an array method on map to iterate over both collections:</p>
<pre><code class="lang-javascript">listItemsHtmlCollection.map( <span class="hljs-function"><span class="hljs-params">element</span> =&gt;</span> element.style.color = <span class="hljs-string">'red'</span> )
listItemsNodeList.map( <span class="hljs-function"><span class="hljs-params">element</span> =&gt;</span> element.style.color = <span class="hljs-string">'red'</span> )
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Screenshot--146-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>To use the map array method successfully, you have to convert both items to an array with the <code>Array.from()</code> method like this:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Array</span>.from(listItemsHtmlCollection).map( <span class="hljs-function"><span class="hljs-params">element</span> =&gt;</span> element.style.color = <span class="hljs-string">'red'</span> )
<span class="hljs-built_in">Array</span>.from(listItemsNodeList).map( <span class="hljs-function"><span class="hljs-params">element</span> =&gt;</span> element.style.color = <span class="hljs-string">'red'</span> )
</code></pre>
<p>There are two major ways in which HTMLCollection and a nodeList differ from one another. They are:</p>
<ul>
<li><p>A nodeList comes with some inbuilt methods and properties not available in an HTMLCollection. The methods include the <code>forEach()</code> and the <code>entries</code> methods to iterate over a nodeList. The properties include the keys property and the value property.</p>
</li>
<li><p>An HTMLCollection is always live, while a nodeList can either be live or static. A collection of nodes is live if a change in the DOM tree updates the collection automatically. If a change in the DOM tree does not affect the collection, then it is static. DOM changes can be the addition of a new node or the removal of an existing node. DOM methods such as <code>getElementById()</code> and <code>getElementsByClassName()</code> return HTMLCollections, which is always live. The <code>querySelectorAll()</code> method returns a static nodeList.</p>
</li>
</ul>
<h2 id="heading-dom-html-methods">DOM HTML Methods</h2>
<p>The DOM level 1 core, Dom level 2 core, and Dom level 3 core introduced several methods that allow web developers to manipulate the DOM tree. Some of these methods are the following:</p>
<h3 id="heading-the-createelement-dom-method">The <code>createElement()</code> DOM method</h3>
<p>The <code>createElement()</code> method creates an element of the type specified as its argument.</p>
<pre><code class="lang-html">//html document

<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> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</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">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Document<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">"style.css"</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">ul</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>item one<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 two<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 three<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 four<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 class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"main.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>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>

<span class="hljs-comment">//select the parent element</span>
<span class="hljs-keyword">const</span> list = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'ul'</span>)
<span class="hljs-comment">//create a new element</span>
<span class="hljs-keyword">const</span> listItem = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'li'</span>)
<span class="hljs-comment">//make the newly created element a child of the parent</span>
list.appendChild(<span class="hljs-string">'listItem'</span>)
<span class="hljs-built_in">console</span>.log(list)
</code></pre>
<p>Now check the console for the list console logged. You'll see that there are five <code>&lt;li&gt;</code> elements now within the <code>&lt;ul&gt;</code> parent element.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Screenshot--147--1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-the-createtextnode-dom-method">The <code>createTextNode()</code> DOM method</h3>
<p>The <code>createTextNode()</code> method creates a text node with the string specified as its argument. Let's add text to the <code>&lt;li&gt;</code> element we created above.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>

<span class="hljs-keyword">const</span> listText = <span class="hljs-built_in">document</span>.createTextNode(<span class="hljs-string">"item five"</span>)
listItem.appendChild(listText)
</code></pre>
<p>Now save your JavaScript file and reload your webpage.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Screenshot--149-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-the-appendchild-dom-method">The <code>appendChild()</code> DOM method</h3>
<p>The <code>appendChild()</code> method adds a node to the end of the list of children of a parent node.</p>
<p>If the specified child is an existing node in the document, <code>appendChild()</code> moves it from its current position on the DOM tree to the new position. We used the method earlier to make our newly created <code>&lt;li&gt;</code> element a child of the <code>&lt;ul&gt;</code> element.</p>
<h3 id="heading-the-getelementbyid-dom-method">The <code>getElementById()</code> DOM method</h3>
<p>This method selects and returns the element whose ID is specified within it as a argument. If no such element exists, the method returns null. Let's add an <em>id</em> attribute to our <code>&lt;ul&gt;</code> element in the HTML document and give it a red border.</p>
<pre><code class="lang-html">//html document

<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> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</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">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Document<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">"style.css"</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">ul</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"ulList"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>item one<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 two<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 three<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 four<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 class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"main.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>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>

<span class="hljs-keyword">const</span> ulList = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"ulList"</span>) 
ulList.style.border = <span class="hljs-string">'2px solid red'</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Screenshot--150-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-the-getelementsbyclassname-dom-method">The <code>getElementsByClassName()</code> DOM method</h3>
<p>The <code>getElementsByClassName()</code> method selects all elements with the specified class name and returns them as an HTMLCollection in the order they appear on the DOM tree.</p>
<p>You can access individual elements in the HTMLCollection by their index number. Let's add a class attribute to the first two <code>&lt;li&gt;</code> elements in our HTML document and change their text color to red like this:</p>
<pre><code class="lang-html">//html document

<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> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</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">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Document<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">"style.css"</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">ul</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"ulList"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"itemOneAndTwo"</span>&gt;</span>item one<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"itemOneAndTwo"</span>&gt;</span>item two<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 three<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 four<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 class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"main.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>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>

<span class="hljs-comment">//select by elements one and two by their class name</span>
<span class="hljs-keyword">const</span> itemOneAndTwo = <span class="hljs-built_in">document</span>.getElementsByClassName(<span class="hljs-string">"itemOneAndTwo"</span>)
<span class="hljs-comment">//change text color to red with use of index</span>
itemOneAndTwo[<span class="hljs-number">0</span>].style.color = <span class="hljs-string">'red'</span>
itemOneAndTwo[<span class="hljs-number">1</span>].style.color = <span class="hljs-string">'red'</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Screenshot--151-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-the-getelementsbytagname-dom-method">The <code>getElementsByTagName()</code> DOM method</h3>
<p>The <code>getElementsByTagName()</code> method returns an HTMLCollection of all the elements with the tag name specified as its argument, in the order they appear on the DOM tree.</p>
<p>Let's select the <code>&lt;li&gt;</code> elements with the <code>getElementsBytagName()</code> method and change their font style to italic.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>

<span class="hljs-keyword">const</span> liTags = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">"li"</span>) 
<span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; liTags.length; i++) {
    liTags[i].style.fontStyle = <span class="hljs-string">'italic'</span>
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Screenshot--152-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-the-queryselector-dom-method">The <code>querySelector()</code> DOM method</h3>
<p>The <code>querySelector()</code> method accepts any CSS string selector as an argument. It then uses the specified selector to select the first within the document that matches that specified selector.</p>
<p>Let's change select our first two <code>&lt;li&gt;</code> elements with the <code>querySelector()</code> method and change their text color back to black.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>

<span class="hljs-keyword">const</span> querySelectItem = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"itemOneAndTwo"</span>)
querySelectItem.style.color = <span class="hljs-string">'black'</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Screenshot--153-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Notice that only the first list item has had its color changed to black.</p>
<h3 id="heading-the-queryselectorall-dom-method">The <code>querySelectorAll()</code> DOM method</h3>
<p>The <code>querySelectorAll()</code> method, just like the <code>querySelector</code> method, accepts any CSS string selector as its argument. It then uses the specified CSS string selector to select all elements that match that specified selector, put them in a nodeList, and return that nodeList.</p>
<p>Now, let's use it to change all the text in out list items to green.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>

<span class="hljs-keyword">const</span> querySelectAllItems = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">"li"</span>)
<span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; querySelectAllItems.length; i++) {
    querySelectAllItems[i].style.color = <span class="hljs-string">'green'</span>
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Screenshot--154-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-the-setattribute-dom-method">The <code>setAttribute()</code> DOM method</h3>
<p>The <code>setAttribute()</code> method adds a new attribute name to an element. If an attribute with that name is already present in the element, its value will change to that of the value set in the argument.</p>
<p>The method accepts two arguments. The first argument is the name of the attribute you want to create. The second argument is the value to set on the attribute, which is always a string.</p>
<p>Let's use it to give our third item a class attribute and change the text color to black.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>

<span class="hljs-keyword">const</span> itemThree = querySelectAllItems[<span class="hljs-number">2</span>] 
itemThree.setAttribute(<span class="hljs-string">"class"</span>, <span class="hljs-string">"attributeValue"</span>)  
<span class="hljs-keyword">const</span> attributeValue = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.attributeValue'</span>)
attributeValue.style.color = <span class="hljs-string">'black'</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Screenshot--155-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-the-removeattribute-dom-method">The <code>removeAttribute()</code> DOM method</h3>
<p>The <code>removeAttribute()</code> method removes a specified attribute. It takes in the name of the attribute to be removed as its argument. Let's remove the <em>id</em> attribute from the <code>&lt;ul&gt;</code> parent element and use the removed id to removed its red border.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>

<span class="hljs-comment">//remove attribute</span>
ul.removeAttribute(<span class="hljs-string">'id'</span>)
ul.style.border = <span class="hljs-string">'none'</span>
</code></pre>
<p>Now save your JavaScript file and reload your web page. Notice that the borders are still there. If you check the console you will see an error message stating that <em>ul</em> is no longer defined.</p>
<h3 id="heading-the-contains-dom-method">The <code>contains()</code> DOM method</h3>
<p>The <code>contains()</code> method returns true if a node is a descendant of a node and returns false otherwise.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">--HTML</span> <span class="hljs-attr">document--</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">h1</span>&gt;</span>Heading<span class="hljs-tag">&lt;/<span class="hljs-name">h1</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-comment">//javascript content</span>
<span class="hljs-keyword">const</span> body = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'body'</span>)
<span class="hljs-keyword">const</span> h1Element = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'h1'</span>)
<span class="hljs-built_in">console</span>.log( body.contains(h1Element) ) <span class="hljs-comment">// true</span>
</code></pre>
<h3 id="heading-the-item-dom-method">The <code>item()</code> DOM method</h3>
<p>The <code>item()</code> method returns the item specified at the index specified as its argument when used on a collection.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">--HTML</span> <span class="hljs-attr">document--</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>Paragraph<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>Paragraph<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>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>
<span class="hljs-keyword">const</span> pElements = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">"p"</span>) 
<span class="hljs-built_in">console</span>.log(pElements.item(<span class="hljs-number">0</span>)) <span class="hljs-comment">// &lt;p&gt;&lt;/p&gt;</span>
</code></pre>
<h3 id="heading-the-haschildnodes-dom-method">The <code>hasChildNodes()</code> DOM method</h3>
<p>The <code>hasChildNodes</code> method returns true if the element it is called on has child nodes within it and returns false otherwise.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">--HTML</span> <span class="hljs-attr">document--</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>Paragraph<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>Paragraph<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>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>

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

<span class="hljs-built_in">console</span>.log(body.hasChildNodes()) <span class="hljs-comment">// true</span>
</code></pre>
<h2 id="heading-what-are-dom-events">What are DOM Events?</h2>
<p>To make our web page logically interactive by initiating automatic responses or incidents on the web page, we need Events.</p>
<p>DOM events are:</p>
<blockquote>
<p>actions or occurrences that happen in the system you are programming, which the system tells you about so your code can react to them. (Source: <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_objects">MDN</a>)</p>
</blockquote>
<p>A common example of an event is when a user clicks a submit button in a form, which then submits the data input by the user as a response to the click.</p>
<p>Another example is when a user clicks on a menu icon, which then triggers a drop-down navigation or options.</p>
<p>You can use scripting languages such as JavaScript to register event handlers or listeners on elements inside the DOM tree, which runs when the specified event fires.</p>
<p>An event handler is a:</p>
<blockquote>
<p>block of code (usually a JavaScript function that you as a programmer create) that runs when the event fires. When such a block of code is defined to run in response to an event, we say we are <strong>registering an event handler</strong>. (Source: <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_objects">MDN</a>)</p>
</blockquote>
<p>Examples of events used on elements in the DOM tree include:</p>
<ul>
<li><p><strong>click</strong>: A click event is a mousedown or mouseup over an element on a webpage.</p>
</li>
<li><p><strong>keypress</strong>: A keypress event occurs when keys on the keyboard are pressed.</p>
</li>
<li><p><strong>mouseover</strong>: A mouseover event occurs when the pointing device is moved onto an element.</p>
</li>
<li><p><strong>dblclick</strong>: A dblclick occurs when there is a double-click event over an element on a webpage.</p>
</li>
<li><p><strong>submit</strong>: A submit event occurs when a form is submitted.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The DOM is the backbone of modern web dynamism. It represents every piece of a web document as an object and provides programming languages with the necessary methods to manipulate and modify each piece.</p>
<p>If you enjoyed this write-up, you should give me a <a target="_blank" href="https://twitter.com/activus_d"><em>shoutout</em></a>.</p>
<h3 id="heading-references-and-further-reading">References and Further Reading</h3>
<ol>
<li><p><a target="_blank" href="https://dom.spec.whatwg.org/">https://dom.spec.whatwg.org/</a></p>
</li>
<li><p><a target="_blank" href="https://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core.html">https://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core.html</a></p>
</li>
<li><p><a target="_blank" href="https://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html.html">https://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html.html</a></p>
</li>
<li><p><a target="_blank" href="https://www.w3.org/TR/DOM-Level-2-HTML/">https://www.w3.org/TR/DOM-Level-2-HTML/</a></p>
</li>
<li><p><a target="_blank" href="https://www.w3.org/TR/DOM-Level-3-Core/core.html">https://www.w3.org/TR/DOM-Level-3-Core/core.html</a></p>
</li>
</ol>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
