<?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[ beginner - 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[ beginner - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 07 Jul 2026 10:23:47 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/beginner/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Write Your First Quantum Circuit in Python: A Beginner's Step-by-Step Guide ]]>
                </title>
                <description>
                    <![CDATA[ Imagine opening your laptop and writing code that follows the laws of Quantum Physics. Sounds like science fiction, right? That's exactly what I thought the first time I heard about quantum computing. ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-write-your-first-quantum-circuit-in-python-a-beginner-s-step-by-step-guide/</link>
                <guid isPermaLink="false">6a43087a41950d02c662e901</guid>
                
                    <category>
                        <![CDATA[ quantum computing ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Casmir Onyekani ]]>
                </dc:creator>
                <pubDate>Tue, 30 Jun 2026 00:06:18 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/ce5d0476-b953-4865-810b-3f86021152c7.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Imagine opening your laptop and writing code that follows the laws of Quantum Physics. Sounds like science fiction, right?</p>
<p>That's exactly what I thought the first time I heard about quantum computing. I assumed quantum computers were machines hidden inside secret laboratories. I imagined researchers in white coats working with equipment worth millions of dollars.</p>
<p>Then I discovered something surprising: you can write and run your first quantum program using Python on a regular laptop.</p>
<p>No quantum computer required. No physics degree required. No advanced mathematics required.</p>
<p>Just Python.</p>
<p>In this tutorial, you'll learn how to build your first quantum circuit using Python and Qiskit.</p>
<p>By the end, you'll understand what a quantum circuit is, how qubits work, and how to create one of the most famous experiments in quantum computing called a Bell State.</p>
<p>Let's get started.</p>
<h3 id="heading-table-of-contents">Table Of Contents</h3>
<ul>
<li><p><a href="#heading-what-is-quantum-computing">What Is Quantum Computing?</a></p>
<ul>
<li><a href="#heading-why-should-python-developers-care-about-quantum-computing">Why Should Python Developers Care About Quantum Computing?</a></li>
</ul>
</li>
<li><p><a href="#heading-what-is-a-quantum-circuit">What Is a Quantum Circuit?</a></p>
</li>
<li><p><a href="#heading-quantum-gates-explained-like-a-python-developer">Quantum Gates Explained Like a Python Developer</a></p>
<ul>
<li><p><a href="#heading-x-gate-the-quantum-light-switch">X Gate: The Quantum Light Switch</a></p>
</li>
<li><p><a href="#heading-classical-example">Classical Example</a></p>
</li>
<li><p><a href="#heading-quantum-example">Quantum Example</a></p>
</li>
<li><p><a href="#heading-h-gate-the-spinning-coin-trick">H Gate: The Spinning Coin Trick</a></p>
</li>
<li><p><a href="#heading-example">Example</a></p>
</li>
<li><p><a href="#heading-cx-gate-making-two-qubits-work-together">CX Gate: Making Two Qubits Work Together</a></p>
</li>
<li><p><a href="#heading-how-to-set-up-your-python-environment">How to Set Up Your Python Environment</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-building-your-first-quantum-circuit">Building Your First Quantum Circuit</a></p>
<ul>
<li><p><a href="#heading-creating-superposition">Creating Superposition</a></p>
</li>
<li><p><a href="#heading-creating-entanglement-with-the-cnot-gate">Creating Entanglement With the CNOT Gate</a></p>
</li>
<li><p><a href="#heading-measuring-the-qubits">Measuring the Qubits</a></p>
</li>
<li><p><a href="#heading-running-the-circuit-on-a-quantum-simulator">Running the Circuit on a Quantum Simulator</a></p>
</li>
<li><p><a href="#heading-your-complete-bell-state-program">Your Complete Bell State Program</a></p>
</li>
<li><p><a href="#heading-for-windows-users-a-common-qiskit-aer-error">For Windows Users: A Common Qiskit Aer Error</a></p>
</li>
<li><p><a href="#heading-other-common-mistakes-beginners-make">Other Common Mistakes Beginners Make</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-visualizing-results-with-a-histogram">Visualizing Results With a Histogram</a></p>
</li>
<li><p><a href="#heading-understanding-what-just-happened">Understanding What Just Happened</a></p>
</li>
<li><p><a href="#heading-what-is-a-bell-state">What Is a Bell State?</a></p>
<ul>
<li><a href="#heading-why-bell-states-matter">Why Bell States Matter</a></li>
</ul>
</li>
<li><p><a href="#heading-real-world-applications-of-quantum-entanglement">Real World Applications of Quantum Entanglement</a></p>
<ul>
<li><p><a href="#heading-quantum-cryptography">Quantum Cryptography</a></p>
</li>
<li><p><a href="#heading-quantum-networking">Quantum Networking</a></p>
</li>
<li><p><a href="#heading-drug-discovery">Drug Discovery</a></p>
</li>
<li><p><a href="#heading-financial-modeling">Financial Modeling</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-beginner-experiments-to-try">Beginner Experiments to Try</a></p>
<ul>
<li><p><a href="#heading-experiment-1-remove-the-hadamard-gate">Experiment 1: Remove the Hadamard Gate</a></p>
</li>
<li><p><a href="#heading-experiment-2-increase-the-number-of-shots">Experiment 2: Increase the Number of Shots</a></p>
</li>
<li><p><a href="#heading-experiment-3-add-an-x-gate">Experiment 3: Add an X Gate</a></p>
</li>
<li><p><a href="#heading-experiment-4-create-three-qubits">Experiment 4: Create Three Qubits</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-what-should-you-learn-next">What Should You Learn Next?</a></p>
<ul>
<li><p><a href="#heading-build-larger-circuits">Build Larger Circuits</a></p>
</li>
<li><p><a href="#heading-explore-real-quantum-hardware">Explore Real Quantum Hardware</a></p>
</li>
<li><p><a href="#heading-learn-quantum-algorithms">Learn Quantum Algorithms</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-final-thoughts">Final Thoughts</a></p>
</li>
</ul>
<h2 id="heading-what-is-quantum-computing">What Is Quantum Computing?</h2>
<p>Most software developers work on <strong>regular computers</strong>, just like yours - a laptop, smartphone, or gaming console.</p>
<p>Every one of these devices processes information using bits. A bit can only have one value at a time: <code>0 or 1</code> Nothing in between.</p>
<p>Quantum computers use something different. They use <strong>qubits</strong>. A qubit can behave like a <code>0</code> and a <code>1</code> at the same time until it's measured.</p>
<p>Don't worry if that sounds strange. It sounds strange to everyone the first time.</p>
<p>Think about a coin. When a coin is lying flat on a table, it's either heads or tails. That's exactly how a regular computer bit works. But now, imagine spinning that coin. While it's spinning, it's a blur of both heads and tails at the same time. That's exactly how a quantum bit works</p>
<p>This isn't a perfect explanation. But it's a useful one for beginners.</p>
<p>This ability allows quantum computers to solve certain types of problems differently from regular computers.</p>
<h3 id="heading-why-should-python-developers-care-about-quantum-computing">Why Should Python Developers Care About Quantum Computing?</h3>
<p>You might be thinking: "I'm a Python developer. Why should I learn quantum computing?"</p>
<p>Good question.</p>
<p>The truth is that quantum computing is still in its early stages, but so was artificial intelligence a few years ago. Developers who learn early often gain an advantage.</p>
<p>Python has become one of the most popular languages for quantum programming because it is simple and beginner friendly. Many major quantum platforms provide Python libraries. These include:</p>
<ul>
<li><p><a href="https://www.ibm.com/quantum/qiskit">IBM Qiskit</a></p>
</li>
<li><p><a href="https://medium.com/@adnanmasood/quantum-sundays-24-cirq-for-noisy-intermediate-scale-quantum-nisq-circuit-programming-c2c3f951d21d">Google Cirq</a></p>
</li>
<li><p><a href="https://aws.amazon.com/braket/">Amazon Braket</a></p>
</li>
</ul>
<p>Among these options, Qiskit is one of the easiest places to start. That's what you'll use in this tutorial.</p>
<p>If you already know variables, functions, and basic Python syntax, you're ready to begin.</p>
<h2 id="heading-what-is-a-quantum-circuit">What Is a Quantum Circuit?</h2>
<p>If you've built web applications before, you're probably familiar with workflows.</p>
<p>For example:</p>
<pre><code class="language-yaml">User clicks button 
        ↓ 
Data is validated 
        ↓ 
Request is sent 
        ↓ 
Response is returned
</code></pre>
<p>A quantum circuit works in a similar way. Instead of processing user input, it processes qubits.</p>
<p>A quantum circuit is simply a sequence of instructions applied to qubits.</p>
<p>Here's a simplified view:</p>
<pre><code class="language-yaml">Create qubits 
      ↓
Apply quantum gates 
      ↓ 
Measure results 
      ↓ 
Display output
</code></pre>
<p>At its core, a quantum circuit simply involves initializing qubits, performing operations, and measuring the results.</p>
<h2 id="heading-quantum-gates-explained-like-a-python-developer">Quantum Gates Explained Like a Python Developer</h2>
<p>If you've written Python before, you've probably changed values many times.</p>
<p>For example:</p>
<pre><code class="language-python">light = False

light = not light

print(light)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">True
</code></pre>
<p>The <code>not</code> operator changes the value. It takes <code>False</code> and turns it into <code>True</code>.</p>
<p>Quantum computers also need ways to change values. Instead of using operators like <code>not</code>, they use something called <strong>quantum gates</strong>.</p>
<p>Think of quantum gates as special instructions that tell a qubit what to do.</p>
<p>Just like Python has:</p>
<ul>
<li><p><code>not</code></p>
</li>
<li><p><code>+</code></p>
</li>
<li><p><code>-</code></p>
</li>
<li><p><code>*</code></p>
</li>
</ul>
<p>Quantum computing has:</p>
<ul>
<li><p>X Gate</p>
</li>
<li><p>H Gate</p>
</li>
<li><p>CX Gate</p>
</li>
</ul>
<p>Let's understand them one at a time.</p>
<h3 id="heading-x-gate-the-quantum-light-switch">X Gate: The Quantum Light Switch</h3>
<p>Imagine the light switch in your room.</p>
<p>When the switch is OFF: <code>OFF</code>. Press the switch. Now it becomes: <code>ON</code>. Press it again. It becomes <code>OFF</code>.</p>
<p>The switch keeps flipping between the two states, and that's exactly what the X Gate does.</p>
<h3 id="heading-classical-example">Classical Example</h3>
<pre><code class="language-plaintext">0 → 1
1 → 0
</code></pre>
<h3 id="heading-quantum-example">Quantum Example</h3>
<pre><code class="language-plaintext">qc.x(0)
</code></pre>
<p>This means: Apply an X Gate to qubit <code>0</code>.</p>
<p>If qubit <code>0</code> was behaving like a <code>0</code>, it now behaves like a <code>1</code>.</p>
<p>If it was behaving like a <code>1</code>, it becomes a <code>0</code>.</p>
<p>Think of the <code>X Gate</code> as the quantum version of a light switch or a Python <code>not</code> operator.</p>
<h3 id="heading-h-gate-the-spinning-coin-trick">H Gate: The Spinning Coin Trick</h3>
<p>Now things get interesting. Imagine I place a coin on a table. It can only be <code>Heads</code> or <code>Tails</code>, right?</p>
<p>That's how a normal computer works. A bit is either <code>0</code> or <code>1</code></p>
<p>Now imagine I spin that coin. While it's spinning, can you confidently say it's heads at any given moment?</p>
<p>No.</p>
<p>Can you confidently say it's tails?</p>
<p>No.</p>
<p>It hasn't landed yet. It's in a special state where both outcomes are possible.</p>
<p>That's the easiest way to think about what the <a href="https://www.quera.com/glossary/hadamard-gate">H Gate</a> (or Hadamard Gate) does.</p>
<h3 id="heading-example">Example</h3>
<pre><code class="language-plaintext">qc.h(0)
</code></pre>
<p>This tells Qiskit to put qubit <code>0</code> into a superposition.</p>
<p>In beginner language, the qubit is no longer locked to just <code>0</code> or just <code>1</code>. It now has a chance of becoming either when we measure it. Think of it like a spinning coin waiting to land.</p>
<h4 id="heading-before-h-gate">Before H Gate:</h4>
<pre><code class="language-plaintext">0
</code></pre>
<h4 id="heading-after-h-gate">After H Gate:</h4>
<pre><code class="language-plaintext">0 and 1 are both possible
</code></pre>
<p>This idea is one of the reasons quantum computers are so powerful.</p>
<p>Instead of exploring only one possibility at a time, they can work with multiple possibilities.</p>
<h3 id="heading-cx-gate-making-two-qubits-work-together">CX Gate: Making Two Qubits Work Together</h3>
<p>The <strong>CX Gate</strong>, also called the <strong>CNOT (Controlled NOT Gate)</strong>, is different from the X and H gates because it works with two qubits instead of one.</p>
<p>To understand how it works, let's use a simple real-life example.</p>
<p>Imagine you and your friend are playing a game. Before the game starts, you both agree on one rule.</p>
<p>If you raise your hand, your friend must immediately switch what they're doing. If they were standing, they should sit. If they were sitting, they should stand.</p>
<p>But if you keep your hand down, your friend does nothing and stays exactly as they are.</p>
<p>Notice something important: your friend's action depends entirely on what you do. They don't decide on their own.</p>
<p>That's very similar to how the CX Gate works.</p>
<p>Here's how we use it in Qiskit:</p>
<pre><code class="language-plaintext">qc.cx(0, 1)
</code></pre>
<p>This line tells Qiskit: "Use qubit <code>0</code> to control what happens to qubit <code>1</code>."</p>
<p>In this case:</p>
<pre><code class="language-plaintext">Qubit 0 → Control qubit

Qubit 1 → Target qubit
</code></pre>
<p>The control qubit makes the decision, and the target qubit responds.</p>
<h4 id="heading-heres-what-happens-behind-the-scenes">Here's what happens behind the scenes:</h4>
<p>If the control qubit is <code>0</code>, nothing happens. The target qubit stays exactly the same.</p>
<p>If the control qubit is <code>1</code>, the target qubit flips: <code>0</code> becomes <code>1</code>.</p>
<p>Think of the control qubit as a manager giving instructions to an employee. The employee doesn't act randomly. They only change what they're doing when the manager gives the signal.</p>
<p>By itself, the CX Gate is already useful.</p>
<p>But when we combine it with the Hadamard gate, something amazing happens. The two qubits become connected in a special way called entanglement. You'll learn about that later in this tutorial. Now, it's time to practice what you've learned using Python.</p>
<h3 id="heading-how-to-set-up-your-python-environment">How to Set Up Your Python Environment</h3>
<p>Here comes the fun part. Let's prepare your machine. Before you continue, make sure Python is installed on your local computer. For this tutorial, use Python version <code>3.12.8</code> or <code>3.13.8</code>. Those versions work well with all the dependencies you'll be installing.</p>
<pre><code class="language-properties">3.12.8
</code></pre>
<h4 id="heading-step-1-create-a-new-project-folder">Step 1: Create a New Project Folder</h4>
<p>Create a folder called: <code>quantum-python</code> and then open it in VS Code.</p>
<h4 id="heading-step-2-create-a-virtual-environment">Step 2: Create a Virtual Environment</h4>
<p>In your terminal (here I'm using Git Bash), run:</p>
<pre><code class="language-plaintext">python -m venv .venv
</code></pre>
<p>Then activate it. On Windows using Git Bash, run:</p>
<pre><code class="language-shell">source .venv/Scripts/activate
</code></pre>
<p>And on MacOS/Linux:</p>
<pre><code class="language-plaintext">source .venv/bin/activate
</code></pre>
<h4 id="heading-step-3-install-qiskit">Step 3: Install Qiskit</h4>
<p>Run:</p>
<pre><code class="language-shell">pip install qiskit qiskit-aer matplotlib
</code></pre>
<p>This installs:</p>
<ul>
<li><p>Qiskit</p>
</li>
<li><p>Quantum simulator</p>
</li>
<li><p>Chart visualization tools</p>
</li>
</ul>
<h4 id="heading-step-4-verify-installation">Step 4: Verify Installation</h4>
<p>Create a file called:</p>
<pre><code class="language-plaintext">test.py
</code></pre>
<p>Add:</p>
<pre><code class="language-python">import qiskit

print(qiskit.__version__)
</code></pre>
<p>Run:</p>
<pre><code class="language-shell">python test.py
</code></pre>
<p>If you see a version number, you're ready.</p>
<p>Congratulations! You've officially entered the world of quantum programming.</p>
<h2 id="heading-building-your-first-quantum-circuit">Building Your First Quantum Circuit</h2>
<p>Create a new file called <code>bell_state.py</code>. This file will contain your first quantum program.</p>
<p>Now you need to import Qiskit. Add:</p>
<pre><code class="language-python">from qiskit import QuantumCircuit

qc = QuantumCircuit(2, 2)
</code></pre>
<p>This imports the <code>QuantumCircuit</code> class.</p>
<p>What does this mean? QuantumCircuit(2, 2) creates 2 qubits and 2 classical bits.</p>
<p>The classical bits will store the final results after measurement.</p>
<p>Let's print the circuit.</p>
<pre><code class="language-python">print(qc)
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">q_0:
q_1:
c:
</code></pre>
<p>Right now, nothing is happening. The circuit is empty. You're about to change that.</p>
<h3 id="heading-creating-superposition">Creating Superposition</h3>
<p>Let's add our first quantum gate: <code>qc.h(0)</code>.</p>
<p>This applies a Hadamard Gate to qubit <code>0</code>.</p>
<p>Your code becomes:</p>
<pre><code class="language-python">from qiskit import QuantumCircuit

qc = QuantumCircuit(2, 2)

qc.h(0)

print(qc)
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">
      ───
q_0: ┤ H  ├
      ───
q_1: ─────
          
c: 2/═════
</code></pre>
<p>The H gate places qubit <code>0</code> into superposition. This is where quantum behavior begins.</p>
<p>You have officially created your first quantum state.</p>
<h3 id="heading-creating-entanglement-with-the-cnot-gate">Creating Entanglement With the CNOT Gate</h3>
<p>So far, we've only worked with a single qubit. Let's do something much more interesting.</p>
<p>You can make two qubits work together. This phenomenon is called <strong>entanglement</strong>.</p>
<p>If you've spent time on tech Twitter or watched science videos on YouTube, you've probably heard people call entanglement "spooky action at a distance."</p>
<p>Don't worry about the fancy name, just focus on the code.</p>
<p>Add this line beneath your Hadamard gate: <code>qc.cx(0, 1)</code>.</p>
<p>Your program should now look like this:</p>
<pre><code class="language-python">from qiskit import QuantumCircuit

qc = QuantumCircuit(2, 2)

qc.h(0)

qc.cx(0, 1)

print(qc)
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">      ───     
q_0: ┤  H ├─■──
      ───  ─┴─
q_1: ────┤ X  ├
            ───
c: 2/══════════
</code></pre>
<p>But what exactly happened?</p>
<p>The first qubit entered superposition when we applied the H gate. The CNOT gate then linked the second qubit to the first. Now the two qubits behave as a connected system, not two separate pieces of information. Just one shared quantum state.</p>
<p>Think about two perfectly synchronized dice. Every time you roll them, they somehow always show the same number.</p>
<p>Sounds impossible, right? That's because it is impossible in normal classical computing.</p>
<p>But quantum mechanics plays by different rules.</p>
<h3 id="heading-measuring-the-qubits">Measuring the Qubits</h3>
<p>Right now our qubits exist in a quantum state, but computers can't display quantum states directly.</p>
<p>We need to measure them. Measurement converts quantum information into classical information.</p>
<p>Add the following line: <code>qc.measure([0, 1], [0, 1])</code>.</p>
<p>Your code now becomes:</p>
<pre><code class="language-python">from qiskit import QuantumCircuit

qc = QuantumCircuit(2, 2)

qc.h(0)

qc.cx(0, 1)

qc.measure([0, 1], [0, 1])

print(qc)
</code></pre>
<p>What does this line do?</p>
<p>It means:</p>
<ul>
<li><p>Measure qubit <code>0</code></p>
</li>
<li><p>Store result in classical bit <code>0</code></p>
</li>
</ul>
<p>and</p>
<ul>
<li><p>Measure qubit <code>1</code></p>
</li>
<li><p>Store result in classical bit <code>1</code></p>
</li>
</ul>
<p>At this point our circuit is complete. Now we need to execute it.</p>
<h3 id="heading-running-the-circuit-on-a-quantum-simulator">Running the Circuit on a Quantum Simulator</h3>
<p>Here's the cool part. You don't need a quantum computer. Your laptop can simulate one.</p>
<p>Create a new section beneath your circuit.</p>
<pre><code class="language-python">from qiskit_aer import AerSimulator

simulator = AerSimulator()

result = simulator.run(
    qc,
    shots=1024
).result()

counts = result.get_counts()

print(counts)
</code></pre>
<p>Let's break it down.</p>
<h4 id="heading-what-is-aersimulator-that-you-installed">What Is AerSimulator That You Installed?</h4>
<p>AerSimulator is Qiskit's local quantum simulator.</p>
<p>Instead of sending your program to a real quantum machine, it runs everything on your computer.</p>
<p>This is perfect for learning and experimentation, and it's completely free.</p>
<h4 id="heading-what-are-shots">What Are Shots?</h4>
<p>Notice this line: <code>shots=1024</code>.</p>
<p>A shot is a single execution of the quantum circuit. Quantum outcomes are probabilistic, which means that one execution isn't enough.</p>
<p>Running 1,024 shots lets us see the overall pattern.</p>
<p>Think of it like flipping a coin. One flip tells you nothing but a thousand flips reveal the probabilities.</p>
<h3 id="heading-your-complete-bell-state-program">Your Complete Bell State Program</h3>
<p>At this point your file should look like this:</p>
<pre><code class="language-python">from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator

qc = QuantumCircuit(2, 2)

qc.h(0)

qc.cx(0, 1)

qc.measure([0, 1], [0, 1])

simulator = AerSimulator()

result = simulator.run(
    qc,
    shots=1024
).result()

counts = result.get_counts()

print(counts)
</code></pre>
<p>Save the file.</p>
<p>Run: <code>python bell_state.py</code>.</p>
<p>You should see something similar to:</p>
<pre><code class="language-plaintext">{
    '00': 504,
    '11': 520
}
</code></pre>
<p>Your numbers will be slightly different, which is normal. The important thing is that you see: <code>00</code>and <code>11</code>.</p>
<p>You should never see: <code>01</code> or <code>10</code></p>
<p>And that's the clue that tells us entanglement is working.</p>
<h3 id="heading-for-windows-users-a-common-qiskit-aer-error">For Windows Users: A Common Qiskit Aer Error</h3>
<p>If you're using Windows, you might run into this error when importing <code>AerSimulator</code>:</p>
<pre><code class="language-plaintext">ImportError: DLL load failed while importing controller_wrappers:
The specified module could not be found.
</code></pre>
<p>This usually isn't a problem with your code. It happens because Microsoft Visual C++ Redistributable 2015–2022 (x64) isn't installed on your system.</p>
<p>To fix it:</p>
<ol>
<li><p>Download and install the Microsoft Visual C++ Redistributable 2015–2022 (x64) from the official <a href="https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist?view=msvc-170">Microsoft website</a>.</p>
</li>
<li><p>Restart your computer.</p>
</li>
<li><p>Reopen your terminal and run your program again.</p>
</li>
</ol>
<p>Once the runtime is installed, <code>AerSimulator</code> should import successfully, and you can continue with the rest of the tutorial.</p>
<h3 id="heading-other-common-mistakes-beginners-make">Other Common Mistakes Beginners Make</h3>
<p>If your code doesn't work immediately, don't panic. Everyone hits errors.</p>
<p>Common issues include:</p>
<h4 id="heading-module-not-found">Module Not Found</h4>
<pre><code class="language-plaintext">ModuleNotFoundError
</code></pre>
<p>Solution: <code>pip install qiskit</code>.</p>
<h4 id="heading-wrong-virtual-environment">Wrong Virtual Environment</h4>
<p>Make sure your virtual environment is activated before running the script.</p>
<h4 id="heading-missing-simulator">Missing Simulator</h4>
<p>Install: <code>pip install qiskit-aer</code>.</p>
<h4 id="heading-indentation-errors">Indentation Errors</h4>
<p>Remember that Python cares about spacing. Check your indentation carefully.</p>
<h2 id="heading-visualizing-results-with-a-histogram">Visualizing Results With a Histogram</h2>
<p>Developers love visual feedback. A chart makes quantum behavior easier to understand. You can create one.</p>
<p>Add:</p>
<pre><code class="language-python">from qiskit.visualization import plot_histogram
import matplotlib.pyplot as plt

plot_histogram(counts)

plt.show()
</code></pre>
<p>Your <code>bell_state.py</code> file will now look like this:</p>
<pre><code class="language-python"># IMPORT DEPENDENCIES
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit.visualization import plot_histogram 
import matplotlib.pyplot as plt

# Create a Quantum Circuit with 2 qubits and 2 classical bits
qc = QuantumCircuit(2, 2)

# Create a Bell state (entanglement) using a Hadamard and a CNOT gate
qc.h(0)
qc.cx(0, 1)

# Measure all qubits into their corresponding classical bits
qc.measure([0, 1], [0, 1])


# Initialize the Aer simulator and execute the circuit for 1024 shots
simulator = AerSimulator()
result = simulator.run(
    qc,
    shots=1024
).result()

# Gather the resulting measurement counts
counts = result.get_counts()

# Print raw text counts and plot the histogram data
print(counts)
plot_histogram(counts) 
plt.show()
</code></pre>
<p>Run your program again, a histogram should appear.</p>
<p>It will look something like this:</p>
<img src="https://cdn.hashnode.com/uploads/covers/647d7b660f441a49aa878a9e/d9740d20-8a20-4e74-941b-e3db07d2e28b.png" alt="Bell State quantum circuit histogram generated with Python and Qiskit" style="display:block;margin:0 auto" width="1364" height="713" loading="lazy">

<p>For the complete project folder, you can get it from <a href="https://github.com/nuelcas/quantum-python.git">Github</a>.</p>
<h2 id="heading-understanding-what-just-happened">Understanding What Just Happened</h2>
<p>Let's pause for a second because something incredible just happened.</p>
<ul>
<li><p>You created entanglement using Python on your laptop without owning a quantum computer.</p>
</li>
<li><p>The first qubit entered superposition.</p>
</li>
<li><p>The second qubit became linked to it.</p>
</li>
</ul>
<p>When measurement happened, both became <code>0</code> or both become <code>1</code>. The outcome was random, but they always agreed. That's the key observation.</p>
<h2 id="heading-what-is-a-bell-state">What Is a Bell State?</h2>
<p>The Bell State is one of the most famous examples in quantum computing. It's often the first experiment beginners learn.</p>
<p>Why? Because it demonstrates two important quantum ideas:</p>
<ul>
<li><p>Superposition</p>
</li>
<li><p>Entanglement</p>
</li>
</ul>
<p>Without Bell States, many quantum algorithms wouldn't exist because:</p>
<ol>
<li><p>Quantum communication systems depend on them.</p>
</li>
<li><p>Quantum cryptography depends on them.</p>
</li>
<li><p>Future quantum networks depend on them.</p>
</li>
</ol>
<p>The Bell State is basically the "Hello World" of quantum computing. Every quantum developer encounters it sooner or later.</p>
<h3 id="heading-why-bell-states-matter">Why Bell States Matter</h3>
<p>At first glance, this experiment seems small: Two qubits, Two gates, and a few lines of Python. Yet, the idea behind it is huge.</p>
<p>Bell States do much more than demonstrate entanglement. Researchers use them as benchmark experiments to verify that quantum hardware can reliably create and measure entangled qubits.</p>
<p>For example, Bell State circuits are commonly executed on superconducting quantum processors to evaluate how accurately the hardware prepares entangled states before running more complex quantum algorithms.</p>
<p>Bell States also play an important role in quantum communication and serve as building blocks for larger quantum algorithms.</p>
<p>Think of them like functions in programming. A single function may seem small but complex applications are built from thousands of them.</p>
<p>The same idea applies here. Large quantum systems are built from smaller quantum operations.</p>
<h2 id="heading-real-world-applications-of-quantum-entanglement">Real World Applications of Quantum Entanglement</h2>
<p>A common question beginners ask is: "When will I actually use this?"</p>
<p>Fair question.</p>
<p>Here are some real examples.</p>
<h3 id="heading-quantum-cryptography">Quantum Cryptography</h3>
<p>While traditional encryption relies on mathematical difficulty, quantum cryptography relies on the laws of physics, ensuring that any attempt to intercept data changes the quantum state and makes eavesdropping immediately detectable.</p>
<h3 id="heading-quantum-networking">Quantum Networking</h3>
<p>Researchers developing quantum internet technologies are heavily leveraging quantum entanglement to connect quantum devices across large distances.</p>
<h3 id="heading-drug-discovery">Drug Discovery</h3>
<p>Quantum computers may eventually simulate molecules more accurately than classical computers. This could help researchers discover new medicines, improve materials, and understand chemical reactions.</p>
<h3 id="heading-financial-modeling">Financial Modeling</h3>
<p>Large financial institutions are exploring quantum algorithms for:</p>
<ul>
<li><p>Portfolio optimization</p>
</li>
<li><p>Risk analysis</p>
</li>
<li><p>Market simulation</p>
</li>
</ul>
<p>The field is still developing, but the potential is enormous.</p>
<h2 id="heading-beginner-experiments-to-try">Beginner Experiments to Try</h2>
<p>The best way you can learn quantum computing is exactly how developers learn programming:</p>
<ul>
<li><p>Break things.</p>
</li>
<li><p>Experiment.</p>
</li>
<li><p>Change the code.</p>
</li>
<li><p>Observe the results.</p>
</li>
</ul>
<p>Let's try a few simple experiments.</p>
<h3 id="heading-experiment-1-remove-the-hadamard-gate">Experiment 1: Remove the Hadamard Gate</h3>
<p>Delete: <code>qc.h(0)</code> and run the circuit again. What changes?</p>
<p>Observe the output. Why do you think that happened?</p>
<h3 id="heading-experiment-2-increase-the-number-of-shots">Experiment 2: Increase the Number of Shots</h3>
<p>Change: <code>shots=1024</code> to <code>shots=100000</code>.</p>
<p>Run the simulation again. Notice how the results become more balanced. This is probability in action.</p>
<h3 id="heading-experiment-3-add-an-x-gate">Experiment 3: Add an X Gate</h3>
<p>Insert: <code>qc.x(1)</code> before the CNOT gate.</p>
<p>Run the circuit.</p>
<p>While studying the new output distribution, try predicting the results before running the code.</p>
<h3 id="heading-experiment-4-create-three-qubits">Experiment 4: Create Three Qubits</h3>
<p>Change: <code>QuantumCircuit(2, 2)</code> to <code>QuantumCircuit(3, 3)</code>.</p>
<p>Can you create a larger entangled system? Experiment and see.</p>
<h2 id="heading-what-should-you-learn-next">What Should You Learn Next?</h2>
<p>You've now built your first quantum circuit. That's a big milestone.</p>
<p>Here are some great next steps you can explore through <a href="https://quantum.cloud.ibm.com/learning/en">IBM Quantum Platform</a>:</p>
<ul>
<li><p>X Gate</p>
</li>
<li><p>Y Gate</p>
</li>
<li><p>Z Gate</p>
</li>
<li><p>S Gate</p>
</li>
<li><p>T Gate</p>
</li>
</ul>
<h3 id="heading-build-larger-circuits">Build Larger Circuits</h3>
<p>Try:</p>
<ul>
<li><p>GHZ States</p>
</li>
<li><p>Quantum Teleportation</p>
</li>
<li><p>Deutsch Algorithm</p>
</li>
</ul>
<h3 id="heading-explore-real-quantum-hardware">Explore Real Quantum Hardware</h3>
<p>IBM allows developers to run circuits on actual quantum computers. This is one of the coolest experiences in modern programming.</p>
<h3 id="heading-learn-quantum-algorithms">Learn Quantum Algorithms</h3>
<p>Once you're comfortable with circuits, explore:</p>
<ul>
<li><p>Grover's Algorithm</p>
</li>
<li><p>Shor's Algorithm</p>
</li>
<li><p>Quantum Fourier Transform</p>
</li>
</ul>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>A few years ago, quantum computing felt impossible to approach. It seemed reserved for physicists and researchers.</p>
<p>Today, that's no longer true. If you know Python, you already have a pathway into quantum development.</p>
<p>In this tutorial, you learned:</p>
<ul>
<li><p>What quantum computing is</p>
</li>
<li><p>How qubits differ from bits</p>
</li>
<li><p>What quantum gates do</p>
</li>
<li><p>How to install Qiskit</p>
</li>
<li><p>How to create a Bell State</p>
</li>
<li><p>How to simulate a quantum circuit</p>
</li>
<li><p>How to visualize results</p>
</li>
<li><p>Why entanglement matters</p>
</li>
</ul>
<p>Most importantly, you wrote your first quantum program. That's how every quantum developer starts.</p>
<p>One circuit. One experiment. One curiosity-driven question at a time.</p>
<p>Now open your editor and modify the code. Break things. Try new gates. And start exploring the quantum world for yourself.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Key Metrics That Can Make or Break Your Startup ]]>
                </title>
                <description>
                    <![CDATA[ If you’ve built something worth pitching – something more than a fancy hobby with a login screen – you need to know your numbers. Not "I’ll get back to you" know them, know them like you know your co-founder's coffee order. I have seen too many found... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/key-metrics-that-can-make-or-break-your-startup/</link>
                <guid isPermaLink="false">6894eea1ba8a1138e41767a1</guid>
                
                    <category>
                        <![CDATA[ startup ]]>
                    </category>
                
                    <category>
                        <![CDATA[ finance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Founder ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ideas ]]>
                    </category>
                
                    <category>
                        <![CDATA[ business ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Business and Finance  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ metrics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Productivity ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Product Management ]]>
                    </category>
                
                    <category>
                        <![CDATA[ performance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ #reporting ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ycombinator ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Aditya Vikram Kashyap ]]>
                </dc:creator>
                <pubDate>Thu, 07 Aug 2025 18:21:21 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1754590848364/2e68c07e-d5d8-4da7-bc41-3798c991bfbc.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you’ve built something worth pitching – something more than a fancy hobby with a login screen – you need to know your numbers. Not "I’ll get back to you" know them, know them like you know your co-founder's coffee order.</p>
<p>I have seen too many founders who are smart, legit, and ambitious get ghosted by investors simply because they couldn't walk through their unit economics.</p>
<p>It's not personal. It's math.</p>
<p>So here it is: Numbers that will either carry your pitch or quietly kill it, explained by someone who has sat through them time and time again, with examples, and no fluff.</p>
<h3 id="heading-heres-what-well-cover">Here’s what we’ll cover:</h3>
<ul>
<li><p><a class="post-section-overview" href="#heading-1-burn-rate-how-fast-are-you-lighting-your-cash-on-fire">1. Burn Rate: How Fast Are You Lighting Your Cash on Fire?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-cash-runway-how-long-before-you-run-out-of-cash">2. Cash Runway: How Long Before You Run Out of Cash?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-cac-customer-acquisition-cost-how-much-does-it-cost-to-convince-someone-to-pay-you">3. CAC (Customer Acquisition Cost): How Much Does it Cost to Convince Someone to Pay You?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-4-customer-lifetime-value-ltv-how-much-is-one-customer-worth-over-time">4. Customer Lifetime Value (LTV): How Much is One Customer Worth Over Time?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-5-gross-profit-margin-what-do-you-actually-keep-after-delivering-your-service-or-product">5. Gross Profit Margin: What Do You Actually Keep After Delivering Your Service or Product?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-6-monthly-annual-recurring-revenue-mrr-arr">6. Monthly / Annual Recurring Revenue (MRR / ARR)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-7-churn-rate-how-fast-are-your-users-leaving">7. Churn Rate: How Fast Are Your Users Leaving</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-8-payback-period-how-long-before-you-recover-your-cac">8. Payback Period: How Long Before You Recover Your CAC?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-9-earnings-before-interest-taxes-depreciation-and-amortization-ebitda">9. Earnings Before Interest, Taxes, Depreciation, and Amortization (EBITDA)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-10-valuation-whats-your-company-worth-and-what-supports-that-number">10. Valuation: What’s Your Company Worth – and What Supports that Number?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-real-talk-before-you-close-that-tab">Real Talk Before You Close That Tab</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-real-experience">Real Experience</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-this-matters">Why This Matters</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion-and-final-thoughts">Conclusion and Final Thoughts</a></p>
</li>
</ul>
<h2 id="heading-1-burn-rate-how-fast-are-you-lighting-your-cash-on-fire">1. Burn Rate: How Fast Are You Lighting Your Cash on Fire?</h2>
<p>Burn rate is the speed at which a startup is spending its cash. Basically, how fast are you consuming your venture capital to cover over overhead until you generate positive cash flow from operations? It’s a measure of negative cash flow.</p>
<p>If you’re spending $80K a month to keep the lights on (payroll, AWS, your workspace snacks, and so on), that’s how much cash you’re burning each month. But many startups calculate two different burn rates: gross burn (how much cash you’re spending, ignoring any revenue), and net burn (monthly operating experiences minus any cash you take in each month). Net burn basically measures how fast your cash is shrinking, and it’s often what investors care more about.</p>
<p>Real talk: investors want to know when the plane runs out of fuel before they board. Thats what this metric helps them understand – how fast you’re going through the money you have.</p>
<p>At some point, if a company has a high burn rate, it has to reduce structural costs by cutting expenditures on labor, rent, marketing, and/or capital equipment. The burn rate is an important metric for any company, but it's particularly important for startups that aren't yet generating revenue. It tells managers and investors how fast the company is spending its capital</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=BpS3shZI35A">Watch this video</a> to understand more about Burn Rate.</p>
<h2 id="heading-2-cash-runway-how-long-before-you-run-out-of-cash">2. Cash Runway: How Long Before You Run Out of Cash?</h2>
<p>Cash runway tells how long a startup can continue to operate at a certain burn rate until they are out of cash. For startups without revenue, you can calculate this by dividing available cash by total monthly expenses. Available cash is defined as the funds that are accessible now or can be accessed at a later time relatively quickly to pay for expenses.</p>
<p>When you’re making this calculation, it’s important to not include any anticipated fundraising and other uncertain sources of capital.</p>
<p>Actively managing cash runway is crucial for startup survival and growth. With a significant percentage of startups failing due to cash shortages, founders need to closely monitor their cash burn rate and runway.</p>
<p>The length of runway needed varies based on factors including the startup’s stage, industry, and milestones. In tighter venture capital markets, startups should plan for longer runways and consider strategies such as increasing revenue, reducing expenses, or raising additional capital. Regularly updating financial models and understanding metrics like the burn multiple can help you make informed decisions to extend your runway and align your growth ambitions with financial stability.</p>
<p>While it’s a simple calculation at face value, a cash runway analysis is nuanced and unique to every startup and can be impacted by a multitude of circumstances.</p>
<p>To calculate this, you just divide your total cash reserves by the amount you’re spending each month. Say you’ve got $250K in the bank and you’re spending $50K/month: 250/50 = 5. So you’ve got 5 months. Not 6. Not “it depends” – 5. That’s your runway.</p>
<p>Investors ask “If we don’t fund you, how long do you survive?” If you don’t know that answer, you're not fundraising – you’re freelancing with hope.</p>
<p><a target="_blank" href="https://youtu.be/vtaMwtQgFGE?si=-Hcf_h_LxKYChdBa">Here is a video</a> that explains cash runway with real world examples and the thought process behind it.</p>
<p>And <a target="_blank" href="https://www.jpmorgan.com/insights/business-planning/does-your-startup-have-enough-runway-to-survive">here’s an article</a> from JP Morgan breaking down cash runway, its importance, and what can you to to maximize it.</p>
<h3 id="heading-burn-rate-vs-runway">Burn Rate vs Runway</h3>
<p>So, let’s just make this super clear: burn rate is simply how much you spend each month to run your operation – that is, your negative cash flow. Runway is how many months there are left before your bank balance reaches zero.</p>
<p>So again, why do these numbers matter?</p>
<p>Because burn rate tells you how quickly you need to find more revenue or funding. Runway tells investors whether you are going to still be around by the time they finish their due diligence.</p>
<p>They are not just numbers. They are your survival clock.</p>
<p>Smart founders utilize these metrics to:</p>
<ul>
<li><p>Trim the fat without cutting muscle – know what to focus on and what to let go</p>
</li>
<li><p>Forecast hiring/fundraising deadlines – know the process and prep for it. Numbers don’t line but they sure can get you ghosted.</p>
</li>
<li><p>Assure investors you’re not going to come knocking again in 90 days – establishing credibility is key, make an investor realize its not just a hobby, you mean business.</p>
</li>
</ul>
<p>The goal: Extend runway without stalling momentum. Keep the plane in the air, while building a bigger engine.</p>
<h2 id="heading-3-cac-customer-acquisition-cost-how-much-does-it-cost-to-convince-someone-to-pay-you">3. CAC (Customer Acquisition Cost): How Much Does it Cost to Convince Someone to Pay You?</h2>
<p>Cost of acquisition refers to the entire cost that a business incurs to obtain a new client or asset. This includes the purchase price, shipping, installation, and marketing costs for the asset acquired. CAC takes into account the total expenditure on all marketing, advertising, and sales for the period, which you then divide by the number of new customers for the period.</p>
<p>In this case, all the upfront costs incurred to purchase a business asset, including equipment or inventory, are part of the cost of acquisition. Cost of acquisition includes:</p>
<ul>
<li><p>Purchase price of the item</p>
</li>
<li><p>Costs to ship it to its point of use</p>
</li>
<li><p>Costs to install the item</p>
</li>
<li><p>Costs to get it up and running (in the case of equipment) or ready for sale (in the case of inventory) condition</p>
</li>
<li><p>Marketing sales teams salaries</p>
</li>
<li><p>All sales and consulting marketing expenses geared to get new consumers should all be included</p>
</li>
</ul>
<p><strong>Formula:</strong><br>CAC = (Total Marketing + Sales Expenses) / Number of New Customers Acquired</p>
<p>Say you spent $10K last month across paid ads, content creation, outbound campaigns, and sales team costs. You onboarded 100 new customers, so your CAC = $100.</p>
<p>But is that good?</p>
<p>It depends on:</p>
<ul>
<li><p>Your pricing model (one-time vs. subscription)</p>
</li>
<li><p>Your margin (how much of that sale do you actually keep?)</p>
</li>
<li><p>Your customer retention (how long do they stick around?)</p>
</li>
</ul>
<p>If you’re selling a $20 product once, a $100 CAC is a non-starter. But if that customer brings in $50/month for 12 months, you’ve got a solid return.</p>
<p><strong>Watch for red flags:</strong></p>
<ul>
<li><p>CAC is rising but revenue isn’t</p>
</li>
<li><p>You’re overly reliant on paid ads (especially if organic/referral is flat)</p>
</li>
<li><p>You don’t know CAC by channel (averages hide leaks)</p>
</li>
</ul>
<p>A healthy CAC is one that pays itself back quickly and can be improved over time as you optimize funnels and messaging</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=KFJ3ip30QPM">Here is a video</a> that breaks down CAC for you.</p>
<h2 id="heading-4-customer-lifetime-value-ltv-how-much-is-one-customer-worth-over-time">4. Customer Lifetime Value (LTV): How Much is One Customer Worth Over Time?</h2>
<p>Customer Lifetime Value is the average monetary value of each customer to your business. LTV takes into account how much a unique customer is expected to spend with your business. It’s an important metric so you know how much new customers are worth to your business over their lifespan as a customer.</p>
<p>Let’s say you charge $25/month. The average customer sticks around 12 months.<br>LTV = $300.</p>
<p>In this case, if your CAC is $80? You’re in the green. But if it’s $350? You’re basically paying people to hang out (and losing money on them).</p>
<p>Now, let’s connect this to CAC.</p>
<p>Say your CAC is $80. You’re doing fine – your LTV is ~4x CAC. That’s what investors want to see.</p>
<p>Rule of thumb: you want your LTV to be at least 3x your CAC. A 1:1 ratio means you’re barely breaking even, before operational costs and the math stops working at scale. So if you can hit a 3:1 ratio, great – and based off my experience, your business will be much more appealing if it’s closer to 5:1.</p>
<p>And keep in mind that different models can have different thresholds. For example, a SaaS company with low churn can afford higher CACs, while an e-commerce platform might need faster payback. And marketplaces and freemium models may have lower LTV per user, but they can often more easily offset it with volume.</p>
<p>If you don’t know your LTV or can’t defend it with data, it becomes hard to justify spend – and easy for investors to walk.</p>
<p>If you want to know more, <a target="_blank" href="https://www.youtube.com/watch?v=vA1YX8963ts">this video</a> walks you through the basics.</p>
<p>And <a target="_blank" href="https://www.youtube.com/watch?v=773zBQVPx_Q">here’s a video</a> that beautifully explains the CAC and LTV relationship.</p>
<h2 id="heading-5-gross-profit-margin-what-do-you-actually-keep-after-delivering-your-service-or-product">5. Gross Profit Margin: What Do You Actually Keep After Delivering Your Service or Product?</h2>
<p>Gross profit margin shows the amount of money a business collects after it pays for all its expenses. It’s usually calculated as a percentage of sales. This specific metric is also referred to as the gross margin ratio.</p>
<p>Companies use gross margin as a measure of how production costs relate to revenue. If a company's gross margin falls because it is making less revenue, it may try to cut labor costs, find cheaper suppliers of materials, or increase prices to increase revenue.</p>
<p>Gross profit margins can also allow a business to measure how efficient a company is, or compare two very differently sized companies that share a common revenue stream or product</p>
<p>If you sell a subscription for $50/month and it costs you $10/month to host, maintain, and support it, your gross margin is 80%.</p>
<ul>
<li><p>Good: SaaS companies often hit 70–90%.</p>
</li>
<li><p>Bad: If you're below 30%, your "scalable" business will collapse under weight.</p>
</li>
</ul>
<p>Want to know the conceptual math behind this metric and how it differs from Profit Margin? <a target="_blank" href="https://www.youtube.com/watch?v=9xAMe0QBFhU&amp;t=45s">Here is a fantastic video</a> that easily breaks it down.</p>
<h2 id="heading-6-monthly-annual-recurring-revenue-mrr-arr">6. Monthly / Annual Recurring Revenue (MRR / ARR)</h2>
<p>Annual recurring revenue (ARR) is revenue a company expects to see from its product and service offerings, calculated over the course of a year. Companies that sell annual subscriptions like using ARR as a sales metric to track what they anticipate making in a year.</p>
<p>ARR tends to be used if companies sell a product or service in the software as a service (SaaS) space, but it can also be useful in terms of streaming services, cell phone bills, and (almost) anything else with a predictable, recurring charge.</p>
<p>ARR is calculated annually, whereas monthly recurring revenue (MRR) is calculated monthly. MRR is useful in that it shows what’s happening on a month-to-month basis. For example, if you change your price in April, you can see the immediate effects of that change in May. MRR also helps track fluctuations in revenue based on outside factors like holiday shopping seasons and economic conditions.</p>
<p>In a nutshell, Monthly / Annual Recurring Revenue = predictable income.</p>
<p>If you’re pulling $20K/month in subscriptions, that’s $240K ARR. Simple.</p>
<p>What investors care about:</p>
<ul>
<li><ul>
<li><p>Is it growing?</p>
<ul>
<li><p>How fast?</p>
</li>
<li><p>And how stable is it?</p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<p><a target="_blank" href="https://youtu.be/qwo7WFWusO4?si=pCelTr2slb2OLuw9">Here is a founder breaking down the metric</a> and explaining the relationship between MRR/ARR.</p>
<h2 id="heading-7-churn-rate-how-fast-are-your-users-leaving">7. Churn Rate: How Fast Are Your Users Leaving</h2>
<p>The churn rate, also known as attrition rate, represents the rate at which a customer stops doing business with a company. Customer churn is typically expressed as the percentage of service subscribers that discontinue their service subscriptions within a time frame. Churn can also be expressed as the rate at which employees leave their jobs in a given time.</p>
<p>In order for a business to grow its number of clients, its growth rate (which takes into account new customers) must be higher than its churn rate.</p>
<p>The benefit of calculating a churn rate is that it can clarify how well a business is retaining its customers, which is a measure of the quality of service the business is providing and the usefulness of that service.</p>
<p>When a business can see its churn rate increasing from period to period, this suggests that a critical aspect of how it is running the business might be problematic or flawed.</p>
<p>It could be the result of:</p>
<ul>
<li><p>A faulty product(s)</p>
</li>
<li><p>Bad customer service</p>
</li>
<li><p>Costs exceed utility to customers</p>
</li>
</ul>
<p>And so on.</p>
<p>The churn rate will indicate to a business that it needs to learn why its customers are leaving, and where it needs to adjust its business. It’s more expensive to attract new customers than it is to retain them, so reducing the churn rate can save a business resources in the future.</p>
<p>Real talk: Say you had 500 users at the start of the month, and you lost 50 by the end of the month. That’s 10% churn – which is high! Annualize that and…ouch. You're not growing. You're replacing.</p>
<p>Make sure you fix this before you fundraise. Or at least explain why churn’s high and what you’re doing to plug the holes.</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=Jlg5J_Mpq7g">Here is a video</a> that beautifully explains Churn Rate.</p>
<h2 id="heading-8-payback-period-how-long-before-you-recover-your-cac">8. Payback Period: How Long Before You Recover Your CAC?</h2>
<p>The payback period is a popular tool for determining investment return. People invest money for the purpose of getting it back and generating a positive return on the money they invested. The shorter the payback period, the more beneficial the investment will be.</p>
<p>The payback period does not factor in the time value of money. You can determine it simply by counting the number of years until the principal paid in is returned.</p>
<p>This metric measures how quickly your customer pays you back for the cost of acquiring them. The payback period doesn’t take into account the total profitability of an investment. It’s just concerned with paying the investment back.</p>
<p>There are two common interpretations:</p>
<ol>
<li><p><strong>Customer-Level Payback:</strong> If your CAC is $250 and your customer pays $50/month, it’ll take 5 months to recover the acquisition cost.</p>
</li>
<li><p><strong>Investment-Level Payback:</strong> You spend $100,000 on a new sales hire, tool stack, or feature. You want to know how long it takes for that investment to generate $100,000 in profit.</p>
</li>
</ol>
<p>Both use the same principle: the shorter the payback period, the less cash you need to float your growth.</p>
<p>If you want a target, aim for 6 months for customer-level payback. Closer to 3-6 is ideal. Long payback periods mean you need deep pockets – or exceptional retention – to stay afloat.</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=KbtTk2azIjY">Here’s a video</a> where you can learn more.</p>
<h2 id="heading-9-earnings-before-interest-taxes-depreciation-and-amortization-ebitda">9. Earnings Before Interest, Taxes, Depreciation, and Amortization (EBITDA)</h2>
<p>EBITDA stands for Earning Before Interest, Taxes, Depreciation, and Amortization. You can think of this as just your company's operating profit if you wanted a very rudimentary way of referring to it.</p>
<p>It’s not flashy. It’s not fun. But it tells investors: “Here’s what we really make once the accounting fog clears.” and “Are we generating real profits from our actual operations?”</p>
<p>EBITDA is what investors look at because it is the best way of comparing apples to apples when considering startups. EBITDA can provide investors a measure of your operational health.</p>
<p>A negative EBITDA for an early stage company isn't going to raise any eyebrows. Just don’t act surprised when someone brings it up. You need to do that math before the pitch. But, if you have a growing early stage company that's moving from negative EBITDA to positive? Now your getting into grown folks business.</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=DH901SrBv9Q">Here’s a video</a> that explains the basics of EBITDA.</p>
<p>And <a target="_blank" href="https://www.youtube.com/watch?v=D58oCe_7BBM">here’s another video</a> that explains how investors look at EBITDA and its value in determining your business’s worth.</p>
<h2 id="heading-10-valuation-whats-your-company-worth-and-what-supports-that-number">10. Valuation: What’s Your Company Worth – and What Supports that Number?</h2>
<p>Valuation is a focused exercise that determines the value of an asset, investment, or company. So, how much your company’s worth. And the goal is typically to determine whether that value is a fair value.</p>
<p>Valuations can be conducted in one of two ways:</p>
<ul>
<li><p>an absolute valuation, which evaluates a company on its own merits and entirely independently of other factors/companies, or</p>
</li>
<li><p>a relative valuation, which evaluates the company relative to other similar firms, or assets, in the same sector or industry. This determines if the company, or asset, is worth that much relative to others.</p>
</li>
</ul>
<p>Depending on how the analysis and conclusions are reached, there are a variety of methods and techniques used to develop valuations. And as you’d expect, there’s often significant variability between outputs (or valuations) based on the inputs and context.</p>
<p>While valuations are predominantly quantitatively driven, there’s often a significant subjective influence that come from the assumptions and estimates made along the way. Valuations are also subject to developing situations and events outside of the analysis or the control of the analyst – for example, earnings reports or material news, or economic news – that can result in a change to a valuation stance.</p>
<p>If you’re pre-revenue and you’re saying $30M because a friend raised at that, please stop. Their experience likely has nothing to do with yours.</p>
<p>Valuation = traction + market comps + revenue + momentum + team.</p>
<p>Valuation isn’t just about what you want – it’s about what you can defend.</p>
<p>Startups are typically valued using:</p>
<ul>
<li><p><strong>Comparable Analysis (Comps):</strong> What similar companies are worth</p>
</li>
<li><p><strong>Discounted Cash Flow (DCF):</strong> Projecting future cash and discounting it back</p>
</li>
<li><p><strong>Revenue Multiples:</strong> Often 5x–10x for SaaS, but varies wildly</p>
</li>
<li><p><strong>Precedent Transactions:</strong> What investors paid in past rounds for similar startups</p>
</li>
</ul>
<p>But that’s the math.</p>
<p>Here’s the messy truth: <strong>Valuation = Traction + Team + TAM (total addressable market) + Timing + Storytelling.</strong></p>
<p>Hard factors:</p>
<ul>
<li><p>MRR/ARR</p>
</li>
<li><p>Growth rate</p>
</li>
<li><p>Churn</p>
</li>
<li><p>CAC:LTV</p>
</li>
<li><p>Gross margins</p>
</li>
</ul>
<p>Soft factors:</p>
<ul>
<li><p>Founding team’s track record</p>
</li>
<li><p>Market momentum</p>
</li>
<li><p>Hype or scarcity</p>
</li>
</ul>
<p>Don’t inflate. Don’t anchor to your friend’s raise. Know your comps. And show why <em>your</em> model is defensible, not just desirable. Inflated numbers make investors run. They don’t correct you – they just ghost you.</p>
<p>There are numerous books written on valuation and each technique could be its own PhD. But my role here is to give you a sneak peak into the metrics.</p>
<p>Here’s a <a target="_blank" href="https://www.youtube.com/watch?v=T3Ud5WQCrzQ">basic video on valuation</a> if you’re interested in a deeper dive.</p>
<p>And <a target="_blank" href="https://www.youtube.com/watch?v=znmQ7oMiQrM&amp;list=PLUkh9m2BorqnKWu0g5ZUps_CbQ-JGtbI9">here’s a more detailed video course</a> outlining different forms of valuation. Professor Damodaran from New York University is considered to be one of the aces and thought leaders when it comes to valuation. In this video course he explains stepwise and beautifully so you can understand and explore the fascinating world of valuations.</p>
<h2 id="heading-real-talk-before-you-close-that-tab">Real Talk Before You Close That Tab</h2>
<h3 id="heading-real-experience">Real Experience</h3>
<p>I met a founder once – early days, rough product, but you could tell he actually cared. He wasn't trying to look good. No buzzwords. No "disrupt" talk. Just someone trying to solve something annoying and important.</p>
<p>He walked into the room with a twinkle. Not swagger – just that gentle intensity. We were leaning in.</p>
<p>Then, in the middle of the pitch, someone asked, "So what's your monthly burn?" And I swear to you, he said, "Umm... I think my co-founder has that. I haven't looked in a while."</p>
<p>That was it.</p>
<p>No freak out. No awkward pause. Just... a cluck. Like a window closing in the background.</p>
<p>The product? Still smart. But the moment? Gone.</p>
<p>Nobody was mad. Nobody laughed. We even said thank you. But nobody followed up.</p>
<p>Why? Because it didn't feel like a business. It felt like a maybe.</p>
<h3 id="heading-why-this-matters">Why This Matters</h3>
<p>I’ve seen so many versions of that same scene play out. It’s never about charisma. It’s not even about the idea, half the time.</p>
<p>It’s about whether the person asking for money actually knows what they’re building. Not the dream, the mechanics. The guts, nuts and bolds of the business. The ugly Excel math nobody brags about on Twitter.</p>
<p>Unfortunately, no simple pitch deck will do that part for you. No co-founder can answer those questions on your behalf.</p>
<p>If it’s your vision, own the math. If it’s your company, learn the cost of keeping it alive.</p>
<p>The rest? The logos, the taglines, the “go-to-market” plans?.... All of that’s just packaging.</p>
<p>And you don’t have to be perfect either. You just have to be in it. Eyes open. Numbers in your head.<br>Because if you’re asking people to believe in what you’re building, you’d better believe in the scaffolding holding it up.</p>
<p>So yeah, know your CAC. Your LTV. Your margins. Your churn. Not to check some box on an investor’s sheet, but to prove to yourself and the investor that the thing you’re spending your life on…has legs. That it can stand. And run.</p>
<p>And maybe, someday, outlast you. Maybe!</p>
<h2 id="heading-conclusion-and-final-thoughts"><strong>Conclusion and Final Thoughts</strong></h2>
<p>I hope this was helpful to you, especially if you’re a founder or aspiring founder trying to build the next big thing. While there a many more ratios and concepts, these are the crux of them.</p>
<p>A lot of other complex ratios and valuations are either built using these metrics or refer them in some way. And each of these metrics could be an article of its own. But I wanted to give you my top 10 run down so that you could get a head start. Numbers are very much a part of the ideation stage itself, and omitting them from your strategy could prove to be a fatal mistake.</p>
<p>I’ll leave you with <a target="_blank" href="https://youtu.be/Pg72m3CjuK4?si=GtIFdvC5WzbKna79">one last video</a> on How to Start a Start Up with Michael Seibel (Reddit, YC, Twitch) that I hope you find valuable. It lays out, in a crash course format, the mindset of a founder who has been there and done that. The fun fact is that a lot of the themes he speaks of tie in to the metrics here, directly or indirectly.</p>
<p>I hope this gives you a perspective of being on the other side, evaluating your hard work and passion, and I hope it sets you up for success in your next Investor Review.</p>
<p>I look forward to your thoughts, comments, and feedback. If this was helpful, engaging, and informative, do share it – you never know who may need it, or could benefit from it. I wish you all the very best in your funding rounds.</p>
<p>Until then, keep learning, unlearning, and relearning, folks.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript vs C#: How to Choose the Right Language as a Beginner ]]>
                </title>
                <description>
                    <![CDATA[ If you're just starting your coding journey or trying to pick your next language, two names you’ll often hear — among others — are JavaScript and C#. Both are powerful, widely used, and respected in the software world. But they serve different purpos... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/choose-the-right-language-js-vs-c-sharp/</link>
                <guid isPermaLink="false">6893b598ffc433dd809aa59d</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C# ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Manish Shivanandhan ]]>
                </dc:creator>
                <pubDate>Wed, 06 Aug 2025 20:05:44 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1754510673710/75f0501b-9d42-43ee-bc90-cc028afdeb3a.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you're just starting your coding journey or trying to pick your next language, two names you’ll often hear — among others — are JavaScript and C#. Both are powerful, widely used, and respected in the software world.</p>
<p>But they serve different purposes, feel different to write, and open up different types of job opportunities.</p>
<p>This article will help you understand what each language is, what they’re good at, and how they compare in real-world use cases.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-javascript">What Is JavaScript?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-c">What Is C#?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-performance">Performance</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-community-and-support">Community and Support</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-ease-of-learning">Ease of Learning</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-career-opportunities">Career Opportunities</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-final-thoughts">Final Thoughts</a></p>
</li>
</ul>
<h2 id="heading-what-is-javascript">What Is JavaScript?</h2>
<p><a target="_blank" href="https://www.freecodecamp.org/news/what-is-javascript-definition-of-js/">JavaScript</a> is the language of the web. It runs in your browser and powers everything from simple websites to complex web apps. Want to make a button do something when clicked? That’s JavaScript. Want to load data without reloading the page? JavaScript again.</p>
<p>But here’s the cool part, JavaScript isn’t just for the front end anymore. With <a target="_blank" href="https://nodejs.org/en">Node.js</a>, it can run on servers too. This means JavaScript is now used to build entire applications, front to back. You can build APIs, handle databases, run background jobs, and more, all with the same language.</p>
<p>This makes JavaScript beginner-friendly. You can write your first script in a browser and still use the same language to build large systems. It’s fast to start, and you’ll find lots of resources and jobs if you go down this path.</p>
<h2 id="heading-what-is-c"><strong>What Is C#?</strong></h2>
<p><a target="_blank" href="https://www.freecodecamp.org/news/learn-c-sharp-programming-1/">C# (pronounced “C sharp”)</a> is a language built by Microsoft. It’s often used in combination with the .NET framework to create desktop apps, web services, and enterprise software. If a business runs a Windows-based software, chances are that it’s built with C#.</p>
<p>C# is also a top choice for game development, thanks to its strong connection with <a target="_blank" href="https://unity.com/">Unity</a>, one of the most popular game engines in the world.</p>
<p>Unlike JavaScript, C# is statically typed. This means you need to define your variables clearly and follow more rules. That sounds like a lot at first, but it actually helps you catch errors early and keep big projects neat and tidy.</p>
<p>Now that you know what JavaScript and C# are, let’s compare them across five key areas.</p>
<h2 id="heading-performance"><strong>Performance</strong></h2>
<p>C# usually performs better than JavaScript, especially when dealing with heavy workloads or tasks that demand a lot from the processor. This advantage comes from the fact that C# is a compiled language.</p>
<p>When you run a C# program, the code is first converted into an intermediate language and then compiled into machine code that your computer’s processor can execute directly. This compilation step removes much of the overhead that comes with interpreting code on the fly.</p>
<p>The result is faster execution and more efficient memory usage, which makes C# ideal for scenarios like handling large files, running complex mathematical calculations, or powering game engines where every millisecond counts.</p>
<p>JavaScript works differently. It’s an interpreted language, which means the code runs line by line in a runtime environment like a web browser or Node.js. Instead of being compiled to machine code ahead of time, the JavaScript engine reads and executes the code as it runs.</p>
<p>This approach offers flexibility and makes it easy to develop and deploy scripts quickly, which is a big reason why JavaScript dominates web development. But because it doesn’t have the same direct link to the machine as compiled languages do, it can struggle in situations that require extremely high performance, like processing massive datasets, rendering complex graphics, or building high-frequency trading systems.</p>
<p>However, modern JavaScript engines have come a long way. Engines like V8, which powers Chrome and Node.js, use <a target="_blank" href="https://en.wikipedia.org/wiki/Just-in-time_compilation">Just-In-Time (JIT)</a> compilation to optimize code while it’s running. They can identify patterns and compile parts of the code into machine instructions on the fly, dramatically improving speed compared to older interpreters.</p>
<p>This means that for most everyday web applications, the difference in performance between JavaScript and C# won’t be noticeable. Web dashboards, e-commerce sites, and typical server-side APIs run perfectly fine in JavaScript. But if your project involves raw computational power, game graphics, or real-time simulations, C# will still give you a clear edge.</p>
<h2 id="heading-community-and-support"><strong>Community and Support</strong></h2>
<p>JavaScript has one of the largest and most active developer communities in the world. Since it's used in almost every corner of the tech world, from websites and browsers to mobile apps and even desktop apps, it has become a go-to language for millions of developers.</p>
<p>That popularity means you’re never alone when learning or building with JavaScript. Whatever problem you run into, chances are that someone else has already faced it and posted about it online. Whether you prefer watching YouTube tutorials, reading blog posts, browsing GitHub repositories, or asking questions on Stack Overflow, you’ll find an overwhelming amount of help and resources to guide you.</p>
<p>C# also has a strong and dedicated community, though it’s more concentrated in the enterprise and professional development space. Backed by Microsoft, C# is consistently updated, well-documented, and deeply integrated with tools like Visual Studio and the .NET ecosystem.</p>
<p>You’ll find a wealth of high-quality documentation, official guides, and forums where professionals share their knowledge. While it might not generate the same buzz as JavaScript in startup circles or web-first communities, C# has a long-standing presence in large-scale systems, corporate software, game development (especially with Unity), and Windows applications. In those environments, it’s not uncommon to find teams of seasoned developers with years of experience in C#.</p>
<p>In short, both languages enjoy excellent support. JavaScript might feel more beginner-friendly due to its widespread usage and endless online tutorials, making it easy to pick up quickly. C#, on the other hand, shines in more structured, professional settings where stability, performance, and long-term maintainability are key. It may not have the same trendy reputation, but within its ecosystem, it’s trusted, respected, and well-loved.</p>
<h2 id="heading-ease-of-learning"><strong>Ease of Learning</strong></h2>
<p>JavaScript is one of the easiest languages to start with because it requires almost no setup. You can open your browser, type a few lines of code in the console, and immediately see the results.</p>
<p>This instant feedback loop makes learning feel exciting and interactive, especially for beginners who want to experiment and see quick outcomes. You can start small, tweak your code, and watch it come to life without installing tools, setting up projects, or even leaving the browser. This low barrier to entry is one of the biggest reasons JavaScript has become the go-to language for people taking their very first steps in programming.</p>
<p>But this simplicity comes with quirks. JavaScript is a very flexible language, which is both a blessing and a curse. It often lets you write code that “just works,” even if it isn’t the best approach. While this makes it forgiving in the early stages, it can also lead to confusing bugs down the line.</p>
<p>Small mistakes might not throw errors immediately, and behavior can change in unexpected ways. Anyone who has wrestled with tricky type conversions knows that JavaScript’s freedom can sometimes backfire. This flexibility demands that you develop discipline on your own if you want to avoid messy, hard-to-maintain code.</p>
<p>C#, on the other hand, feels more structured from the start. It enforces rules like defining types, organizing code into classes, and following a clear syntax. This can feel strict and even a little intimidating at first because you can’t just write anything and hope it works.</p>
<p>The compiler checks your code before it runs and points out mistakes early, which can be frustrating as a beginner. But this structure pays off as your projects grow. The rules and strong typing help you catch errors before they become serious problems, guide you toward better programming habits, and make large, complex codebases easier to manage. Once you get used to its style, C# actually makes programming feel more predictable and less error-prone.</p>
<p>In simple terms, JavaScript gives you the quickest path to start coding and see results, which is perfect for learning and experimenting. C# takes longer to warm up to, but it rewards that effort with cleaner, safer, and more maintainable projects as they grow in size and complexity.</p>
<h2 id="heading-career-opportunities"><strong>Career Opportunities</strong></h2>
<p>Learning JavaScript unlocks a wide range of career opportunities because it powers so much of the modern digital world.</p>
<p>Starting with front-end development, you can build interactive websites and web applications that run in the browser using frameworks like <a target="_blank" href="https://react.dev/">React</a>, Vue, or Angular. If you want to go deeper, Node.js allows you to use JavaScript for back-end development as well, which means you can handle server logic, databases, and APIs without ever switching languages.</p>
<p>This flexibility makes full-stack roles especially accessible to JavaScript developers, since you can manage both the front-end and back-end with a single skillset. On top of that, JavaScript extends into mobile app development with tools like React Native and Ionic, letting you build apps for both iOS and Android.</p>
<p>Because nearly every business needs a website or web application, the demand for JavaScript developers is both high and consistent, making it a strong career path for anyone entering the tech industry.</p>
<p>C# leads to a slightly different set of roles, often tied to enterprise or specialized development. It is heavily used in backend systems that run on the .NET ecosystem, where reliability and performance are critical. Many large companies rely on C# for internal tools, financial applications, and large-scale software products that power their core operations.</p>
<p>One of the most exciting areas for C# developers is game development, thanks to its deep integration with Unity, the most popular game engine in the world. From indie studios to major game companies, Unity uses C# as its primary scripting language, opening the door to careers in the gaming industry. Additionally, C# is a natural fit for building Windows desktop applications and enterprise-level cloud solutions, especially within companies already invested in Microsoft technologies.</p>
<p>Both languages can lead to solid salaries and stable careers, but the paths they open are different. JavaScript thrives in web and mobile-focused roles with a steady demand across startups, agencies, and tech companies of all sizes. C# excels in enterprise, backend, and game development, where the projects are often larger, more complex, and built for long-term reliability. Choosing between them really comes down to the type of work that excites you most and the industry you want to grow in.</p>
<h2 id="heading-final-thoughts"><strong>Final Thoughts</strong></h2>
<p>JavaScript and C# are both modern, useful, and in demand. JavaScript is light, fast, and flexible, perfect for websites and small-to-large web apps. C# is powerful, structured, and ideal for Windows apps, enterprise systems, and games.</p>
<p>If you're new to coding and want to see results fast, start with JavaScript. If you're interested in game dev or building strong business apps, try C#.</p>
<p>You don’t have to choose forever. Many developers learn both. Start with one, explore the other later, and you’ll become a well-rounded coder ready for anything.</p>
<p><a target="_blank" href="https://blog.manishshivanandhan.com/">Join my newsletter</a> for a summary of my articles every Friday. You can also <a target="_blank" href="https://linkedin.com/in/manishmshiva">connect with me on Linkedin</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Collections in C# – Lists, Arrays, Dictionaries, and More ]]>
                </title>
                <description>
                    <![CDATA[ One of the first challenges beginners face when developing applications in C# is organising and managing data efficiently. Imagine keeping track of a list of items, mapping unique keys to values, or ensuring there are no duplicates in a collection – ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-collections-in-csharp/</link>
                <guid isPermaLink="false">6793a90ea69c4db6e76c194a</guid>
                
                    <category>
                        <![CDATA[ C# ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Tutorial ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Grant Riordan ]]>
                </dc:creator>
                <pubDate>Fri, 24 Jan 2025 14:51:58 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1737729136643/4cc12d37-da1c-45f0-928f-fbe02d7fdf52.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>One of the first challenges beginners face when developing applications in C# is organising and managing data efficiently. Imagine keeping track of a list of items, mapping unique keys to values, or ensuring there are no duplicates in a collection – these are all common tasks where choosing the right data structure can make a big difference.</p>
<p>C# provides a rich set of built-in data structures, such as <strong>lists</strong>, <strong>dictionaries</strong>, and more, making it easier to work with data differently. Each structure has strengths and is optimised for specific scenarios, so understanding their differences is key to writing clean, efficient, and maintainable code.</p>
<p>In this tutorial, we’ll explore:</p>
<ul>
<li><p><strong>Lists</strong>: Your go-to for dynamic, ordered collections where elements can grow and shrink effortlessly.</p>
</li>
<li><p><strong>Arrays</strong>: The efficient choice for fixed-size collections with predictable memory usage and blazing-fast indexing.</p>
</li>
<li><p><strong>Dictionaries</strong>: Perfect for quick lookups and managing key-value pairs with unmatched speed and clarity.</p>
</li>
<li><p><strong>Stacks</strong>: Ideal for last-in-first-out (LIFO) operations, like tracking history or nested structures.</p>
</li>
<li><p><strong>Queues</strong>: Best for first-in-first-out (FIFO) tasks, like processing jobs or managing sequential workflows.</p>
</li>
<li><p><strong>HashSets:</strong> The choice for collections where uniqueness matters and fast lookups are key.</p>
</li>
</ul>
<p>By the end of this guide, you'll understand the differences between these structures and be equipped to choose the right one for your next project.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-arrays">Arrays in C#</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-lists">Lists in C#</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-dictionaries">Dictionaries in C#</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-hashsets">HashSets in C#</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-queues">Queues in C#</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-stacks">Stacks in C#</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-common-problems">Common Problems</a></p>
</li>
</ol>
<p>For some of the following examples, you’ll need the <code>Animal</code> record below:</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">Animal</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> Age, <span class="hljs-keyword">string</span> Name, <span class="hljs-keyword">int</span> Legs, <span class="hljs-keyword">string</span> Sound</span>)</span>;
</code></pre>
<h2 id="heading-arrays">Arrays</h2>
<p>An <strong>array</strong> in C# is a fixed-size collection of elements. Arrays are indexed, and their size is set when they are created unlike Lists and other collections. Once defined, the size of an array cannot be changed, making the memory efficient with a low overhead.</p>
<h3 id="heading-single-dimension-arrays">Single-Dimension Arrays</h3>
<p>Arrays are zero-index based, meaning their index begins at 0, rather than 1. If you’re not familiar, an index is a pointer to help you find an item.</p>
<p>For example, if you have 5 names in an Array, the first name is index [0], and the last name would be at index [4].</p>
<p>Arrays are great in scenarios where low-level performance is critical, as they have very little overhead due to their lack of metadata (additional attached information).</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span>[] numbers = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[] { <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span> };

<span class="hljs-keyword">foreach</span>(<span class="hljs-keyword">var</span> number <span class="hljs-keyword">in</span> numbers){
    Console.Write(number);
}
<span class="hljs-comment">//Ouput</span>
<span class="hljs-comment">// 1 2 3 4 5</span>
</code></pre>
<p>In the above example, we instantiate an array with its values (thus giving it a fixed length). But we can assign values after the array is created by using index assignment.</p>
<p><em>Note: You must still specify the size of the array at the time of creation, as the code needs to know the fixed size of the Array.</em></p>
<pre><code class="lang-csharp"><span class="hljs-comment">// create an empty array of 20 indexes</span>
<span class="hljs-keyword">var</span> numbers = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">20</span>];

<span class="hljs-comment">// loop over available indexes and assign `i` </span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; numbers.Length; i++)
{
    numbers[i] = i + <span class="hljs-number">1</span>;
}

<span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">var</span> number <span class="hljs-keyword">in</span> numbers)
{
    Console.Write(<span class="hljs-string">$" <span class="hljs-subst">{number}</span>"</span>);
}
<span class="hljs-comment">// Output</span>
<span class="hljs-comment">//  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20</span>
</code></pre>
<h3 id="heading-multi-dimensional-arrays">Multi-Dimensional Arrays</h3>
<p>Arrays can also be multi-dimensional (for example, rows and columns), meaning they can hold two values. This makes them perfect for building grid-like structures.  </p>
<p>Unlike a jagged array, where each element is an array that can have different lengths, a multidimensional array is a matrix-like structure where each dimension has a fixed size.</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Create a 2D multi-dimensional array to represent a chessboard</span>

<span class="hljs-keyword">string</span>[,] chessBoard = <span class="hljs-keyword">new</span> <span class="hljs-keyword">string</span>[<span class="hljs-number">8</span>, <span class="hljs-number">8</span>];

<span class="hljs-comment">// Creating the starting positions of a Chessboard</span>
chessBoard[<span class="hljs-number">0</span>, <span class="hljs-number">0</span>] = <span class="hljs-string">"Rook"</span>;
chessBoard[<span class="hljs-number">0</span>, <span class="hljs-number">1</span>] = <span class="hljs-string">"Knight"</span>;
chessBoard[<span class="hljs-number">0</span>, <span class="hljs-number">2</span>] = <span class="hljs-string">"Bishop"</span>;
chessBoard[<span class="hljs-number">0</span>, <span class="hljs-number">3</span>] = <span class="hljs-string">"Queen"</span>;
chessBoard[<span class="hljs-number">0</span>, <span class="hljs-number">4</span>] = <span class="hljs-string">"King"</span>;
chessBoard[<span class="hljs-number">0</span>, <span class="hljs-number">5</span>] = <span class="hljs-string">"Bishop"</span>;
chessBoard[<span class="hljs-number">0</span>, <span class="hljs-number">6</span>] = <span class="hljs-string">"Knight"</span>;
chessBoard[<span class="hljs-number">0</span>, <span class="hljs-number">7</span>] = <span class="hljs-string">"Rook"</span>;

chessBoard[<span class="hljs-number">1</span>, <span class="hljs-number">0</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">1</span>, <span class="hljs-number">1</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">1</span>, <span class="hljs-number">3</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">1</span>, <span class="hljs-number">4</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">1</span>, <span class="hljs-number">5</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">1</span>, <span class="hljs-number">6</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">1</span>, <span class="hljs-number">7</span>] = <span class="hljs-string">"Pawn"</span>;

chessBoard[<span class="hljs-number">6</span>, <span class="hljs-number">0</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">6</span>, <span class="hljs-number">1</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">6</span>, <span class="hljs-number">2</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">6</span>, <span class="hljs-number">3</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">6</span>, <span class="hljs-number">4</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">6</span>, <span class="hljs-number">5</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">6</span>, <span class="hljs-number">6</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">6</span>, <span class="hljs-number">7</span>] = <span class="hljs-string">"Pawn"</span>;

chessBoard[<span class="hljs-number">7</span>, <span class="hljs-number">0</span>] = <span class="hljs-string">"Rook"</span>;
chessBoard[<span class="hljs-number">7</span>, <span class="hljs-number">1</span>] = <span class="hljs-string">"Knight"</span>;
chessBoard[<span class="hljs-number">7</span>, <span class="hljs-number">2</span>] = <span class="hljs-string">"Bishop"</span>;
chessBoard[<span class="hljs-number">7</span>, <span class="hljs-number">3</span>] = <span class="hljs-string">"Queen"</span>;
chessBoard[<span class="hljs-number">7</span>, <span class="hljs-number">4</span>] = <span class="hljs-string">"King"</span>;
chessBoard[<span class="hljs-number">7</span>, <span class="hljs-number">5</span>] = <span class="hljs-string">"Bishop"</span>;
chessBoard[<span class="hljs-number">7</span>, <span class="hljs-number">6</span>] = <span class="hljs-string">"Knight"</span>;
chessBoard[<span class="hljs-number">7</span>, <span class="hljs-number">7</span>] = <span class="hljs-string">"Rook"</span>;


<span class="hljs-comment">// Print the chessboard</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> row = <span class="hljs-number">0</span>; row &lt; <span class="hljs-number">8</span>; row++)
{
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> col = <span class="hljs-number">0</span>; col &lt; <span class="hljs-number">8</span>; col++)
    {
        <span class="hljs-keyword">string</span> piece = chessBoard[row, col] ?? <span class="hljs-string">"Empty"</span>;
        Console.Write(<span class="hljs-string">$"<span class="hljs-subst">{piece}</span>\t"</span>);
    }
    Console.WriteLine();
}
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-bash">Rook    Knight  Bishop  Queen   King    Bishop  Knight  Rook    
Pawn    Pawn    Pawn    Pawn    Pawn    Pawn    Pawn    Pawn    
Empty   Empty   Empty   Empty   Empty   Empty   Empty   Empty   
Empty   Empty   Empty   Empty   Empty   Empty   Empty   Empty   
Empty   Empty   Empty   Empty   Empty   Empty   Empty   Empty   
Empty   Empty   Empty   Empty   Empty   Empty   Empty   Empty   
Pawn    Pawn    Pawn    Pawn    Pawn    Pawn    Pawn    Pawn    
Rook    Knight  Bishop  Queen   King    Bishop  Knight  Rook
</code></pre>
<h3 id="heading-jagged-array">Jagged Array</h3>
<p>Welcome to inception. A <strong>jagged array</strong> in C# is an array of arrays, where each "inner" array can have a different length.</p>
<p>Unlike multi-dimensional arrays, jagged arrays are not rectangular, meaning the rows can have varying sizes.</p>
<p>A usage example could be building a Calendar app. Below is a basic usage outputting the days of each month in the year:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span>[][] daysInMonths = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">12</span>][];

<span class="hljs-comment">// Initialize each month with its corresponding number of days</span>
daysInMonths[<span class="hljs-number">0</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">31</span>]; <span class="hljs-comment">// January</span>
daysInMonths[<span class="hljs-number">1</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">28</span>]; <span class="hljs-comment">// February (non-leap year)</span>
daysInMonths[<span class="hljs-number">2</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">31</span>]; <span class="hljs-comment">// March</span>
daysInMonths[<span class="hljs-number">3</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">30</span>]; <span class="hljs-comment">// April</span>
daysInMonths[<span class="hljs-number">4</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">31</span>]; <span class="hljs-comment">// May</span>
daysInMonths[<span class="hljs-number">5</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">30</span>]; <span class="hljs-comment">// June</span>
daysInMonths[<span class="hljs-number">6</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">31</span>]; <span class="hljs-comment">// July</span>
daysInMonths[<span class="hljs-number">7</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">31</span>]; <span class="hljs-comment">// August</span>
daysInMonths[<span class="hljs-number">8</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">30</span>]; <span class="hljs-comment">// September</span>
daysInMonths[<span class="hljs-number">9</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">31</span>]; <span class="hljs-comment">// October</span>
daysInMonths[<span class="hljs-number">10</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">30</span>]; <span class="hljs-comment">// November</span>
daysInMonths[<span class="hljs-number">11</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">31</span>]; <span class="hljs-comment">// December</span>

<span class="hljs-comment">// Print the number of days in each month</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> month = <span class="hljs-number">0</span>; month &lt; daysInMonths.Length; month++)
{
    Console.WriteLine(<span class="hljs-string">$"Month <span class="hljs-subst">{month + <span class="hljs-number">1</span>}</span>: <span class="hljs-subst">{daysInMonths[month].Length}</span> days"</span>);
}
</code></pre>
<p>You should use an <code>Array</code> in:</p>
<ul>
<li><p><strong>Performance-critical applications</strong> where memory overhead and speed matter.</p>
</li>
<li><p><strong>Fixed data sets</strong> where the size will not change.</p>
</li>
<li><p><strong>Multi-dimensional data</strong>, for example, graph coordinates (x, y)</p>
</li>
</ul>
<h2 id="heading-lists">Lists</h2>
<p>A <code>List&lt;T&gt;</code> in C# is a resizable collection of items of the same type, signaled above by the letter <code>T</code>. It allows adding, removing, and accessing items by index. Unlike arrays, lists grow dynamically as needed.  </p>
<p>Commonly used for sequential data, they support <a target="_blank" href="https://www.freecodecamp.org/news/how-to-use-linq/">LINQ</a> queries and various utility methods for data manipulation.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> animals = <span class="hljs-keyword">new</span> List&lt;Animal&gt;()
{
    <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">10</span>, <span class="hljs-string">"Dog"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Woof"</span>),
    <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">5</span>, <span class="hljs-string">"Cat"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Meow"</span>),
    <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">2</span>, <span class="hljs-string">"Lion"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Roar"</span>),
    <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">6</span>, <span class="hljs-string">"Giraffe"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Trumpet"</span>),
    <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">15</span>, <span class="hljs-string">"Red-Panda"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Squeak"</span>)    
};

animals.Add(<span class="hljs-keyword">new</span> Animal(<span class="hljs-number">2</span>, <span class="hljs-string">"Hamster"</span>,<span class="hljs-number">4</span>,<span class="hljs-string">"Squeak"</span>));
animals.Remove(x=&gt;x.Sound == <span class="hljs-string">"Meow"</span>); <span class="hljs-comment">// Remove all squeaking animals</span>
</code></pre>
<p>Lists are a highly versatile data structure, where the order of items remains the same order in which they are added or removed (no manipulation. For example, whenever you call <code>.Add()</code> a method on a list, it will append the item to the list, and the order stays the same as before but with the additional animal.</p>
<p>You can modify the data (for example, filter, map, or sort) before sending lists to other areas of your application thanks to the extensive utility methods available in the <code>List&lt;T&gt;</code> class.</p>
<h2 id="heading-dictionaries">Dictionaries</h2>
<p>Dictionaries work just like the term we know in the English language.</p>
<p>We have a key (a lookup term) and a value (the mapped object or data). Because of this, you might hear the term 'key-value pair' when referring to dictionaries.</p>
<p>Dictionaries are best used to efficiently retrieve data based on a unique identifier, such as an ID, name, or other uniquely identifying fields. They ensure their unique keys are ideal for scenarios requiring optimal performance without iterative searching.  </p>
<p>I recommend using dictionaries when the order of elements is unimportant and you need to represent relationships, such as mapping countries to capitals, products to prices, or people to addresses.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> animalDictionary = <span class="hljs-keyword">new</span> Dictionary&lt;<span class="hljs-keyword">string</span>, Animal&gt;()
{
    { <span class="hljs-string">"Dog"</span>, <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">10</span>, <span class="hljs-string">"Dog"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Woof"</span>) },
    { <span class="hljs-string">"Cat"</span>, <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">5</span>, <span class="hljs-string">"Cat"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Meow"</span>) },
    { <span class="hljs-string">"Elephant"</span>, <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">8</span>, <span class="hljs-string">"Elephant"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Trumpet"</span>) },
    { <span class="hljs-string">"Lion"</span>, <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">2</span>, <span class="hljs-string">"Lion"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Roar"</span>) },
    { <span class="hljs-string">"Giraffe"</span>, <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">6</span>, <span class="hljs-string">"Giraffe"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Trumpet"</span>) },
};
<span class="hljs-comment">// Add</span>
animalDictionary.Add(<span class="hljs-string">"Red panda"</span>, <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">2</span>, <span class="hljs-string">"Red Panda"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Squeaker"</span>));

<span class="hljs-comment">// Remove</span>
animalDictionary.Remove(<span class="hljs-string">"Cat"</span>);

<span class="hljs-comment">//Get</span>
<span class="hljs-keyword">var</span> giraffe = animalDictionary[<span class="hljs-string">"Giraffe"</span>];
</code></pre>
<h2 id="heading-hashsets">HashSets</h2>
<p>A <code>HashSet&lt;T&gt;</code> is a collection in C# that stores unique elements. It uses a hash-based implementation to ensure very efficient lookups, additions, and deletions. This means it uses hash functions to quickly map keys to values, you can read more about that here.</p>
<p>Duplicate elements are automatically ignored.</p>
<p>How does this differ from a Dictionary? HashSets don't have keys like Dictionaries. Instead, they store values directly and are accessed by iterating over the elements using a <code>foreach</code> loop or LINQ queries.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> animalHashSet = <span class="hljs-keyword">new</span> HashSet&lt;Animal&gt;()
{
    <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">3</span>, <span class="hljs-string">"Lion"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Roar"</span>),
    <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">5</span>, <span class="hljs-string">"Tiger"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Roar"</span>),
    <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">2</span>, <span class="hljs-string">"Elephant"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Trumpet"</span>),
    <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">1</span>, <span class="hljs-string">"Giraffe"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Neigh"</span>)
};
<span class="hljs-comment">// Add</span>
animalHashSet.Add(<span class="hljs-keyword">new</span> Animal(<span class="hljs-number">3</span>, <span class="hljs-string">"Lion"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Roar"</span>));
<span class="hljs-comment">// Remove</span>
animalHashSet.Remove(x=&gt;x.Sound == <span class="hljs-string">"Neigh"</span>);
<span class="hljs-comment">// Get</span>
animalHashSet.FirstOrDefault(x=&gt;x.Name == <span class="hljs-string">"Elephant"</span>);
</code></pre>
<p>Above, we create a <code>HashSet&lt;Animal&gt;</code> and attempt to add a duplicate object. You may expect this to throw an error, as we know HashSets can only store unique values. But instead it handles it quite beautifully and simply doesn’t add the duplicate object, so the output is:</p>
<pre><code class="lang-bash">Animal { Age = 3, Name = Lion, Legs = 4, Sound = Roar }
Animal { Age = 5, Name = Tiger, Legs = 4, Sound = Roar }
Animal { Age = 2, Name = Elephant, Legs = 4, Sound = Trumpet }
</code></pre>
<h2 id="heading-queues">Queues</h2>
<p>Queues work in just the same way as a queue does in everyday life, with a first-in, first-out approach.</p>
<p><code>Queue&lt;T&gt;</code> does not implement the ICollection interface like Dictionaries and Lists, meaning it doesn't have an <strong>Add()</strong> method. This means you cannot add elements to the Queue whilst instantiating. It also means you cannot use the <strong>Add()</strong> method to add items – instead, you use the <strong>Enqueue()</strong> method.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> arc = <span class="hljs-keyword">new</span> Queue&lt;<span class="hljs-keyword">string</span>&gt;();
arc.Enqueue(<span class="hljs-string">"2 Lions"</span>);
arc.Enqueue(<span class="hljs-string">"2 Tigers"</span>);
arc.Enqueue(<span class="hljs-string">"2 Bears"</span>);

<span class="hljs-comment">// Peek method allows to peek at the front of the queue</span>
Console.WriteLine(<span class="hljs-string">"Front of the Queue: "</span> + arc.Peek());

<span class="hljs-comment">// Output</span>
<span class="hljs-comment">// Front of the Queue: 2 Lions</span>

Console.WriteLine(<span class="hljs-string">$"Processing: <span class="hljs-subst">{arc.Dequeue()}</span>"</span>); <span class="hljs-comment">// Output: 2 Lions</span>
Console.WriteLine(<span class="hljs-string">$"Processing: <span class="hljs-subst">{arc.Dequeue()}</span>"</span>); <span class="hljs-comment">// Output: 2 Tigers</span>
</code></pre>
<p>The <code>Dequeue</code> method not only returns the next item in the queue but also removes the item from the queue as expected. You can also clear the queue using the <code>Clear()</code> method.</p>
<h2 id="heading-stacks">Stacks</h2>
<p>Stacks work oppositely to <code>Queue&lt;T&gt;</code>, in that instead of first-in-first-out, they work on a last-in-first-out mechanic.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> stack = <span class="hljs-keyword">new</span> Stack&lt;<span class="hljs-keyword">int</span>&gt;();
stack.Push(<span class="hljs-number">1</span>);
stack.Push(<span class="hljs-number">2</span>);
stack.Push(<span class="hljs-number">3</span>);
stack.Push(<span class="hljs-number">4</span>);
stack.Push(<span class="hljs-number">5</span>);

<span class="hljs-comment">// iterate over the Stack</span>
<span class="hljs-keyword">foreach</span>(<span class="hljs-keyword">var</span> number <span class="hljs-keyword">in</span> stack )
{
    Console.WriteLine(number);
}

<span class="hljs-comment">// Output</span>
<span class="hljs-comment">// 5 4 3 2 1</span>
</code></pre>
<p>You may think looping through the items in a <code>Stack</code> would work the same as a List or Queue and would still print them out in order of going in. But the system knows it’s a stack, and so it enumerates the items in reverse order of how they were added – that is, the most recently added element (<code>5</code>) is returned first.</p>
<p>You can also utilise the <code>Pop()</code> method which will return the last item in the collection, and remove it at the same time.</p>
<h2 id="heading-common-problems">Common Problems</h2>
<p>When using various collections, you will more than likely come across common problems, such as <code>KeyNotFoundException</code> when using dictionaries, <code>IndexOutOfRangeException</code> on lists/arrays, or <code>InvalidOperationException</code> when modifying a collection during iteration.</p>
<h3 id="heading-keynotfoundexception"><code>KeyNotFoundException</code></h3>
<p><strong>Scenario:</strong> You try to access a Dictionary key that doesn’t exist in the Dictionary. This will result in a <code>KeyNotFoundException</code>, and error.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> dictionary = <span class="hljs-keyword">new</span> Dictionary&lt;<span class="hljs-keyword">string</span>, <span class="hljs-keyword">string</span>&gt;()
{
    { <span class="hljs-string">"Morning"</span>, <span class="hljs-string">"Good Morning"</span> },
    { <span class="hljs-string">"Afternoon"</span>, <span class="hljs-string">"Good afternoon"</span> },
    { <span class="hljs-string">"Evening"</span>, <span class="hljs-string">"Good evening"</span> },
    { <span class="hljs-string">"Night"</span>, <span class="hljs-string">"Good night"</span> },
};

<span class="hljs-keyword">var</span> message = dictionary[<span class="hljs-string">"Dusk"</span>];

Console.WriteLine(message);

<span class="hljs-comment">// Output</span>
<span class="hljs-comment">//Unhandled exception. System.Collections.Generic.KeyNotFoundException: The given key 'Dusk' was not present in the dictionary.</span>
</code></pre>
<p><strong>Solution:</strong> I recommend using the <code>TryGetValue</code> function, which will handle it gracefully and return the item as an <code>out</code> parameter (if it can be found, otherwise the default value).</p>
<p><code>TryGetValue</code> returns a boolean to show whether it could or couldn’t find the provided key. This boolean value can then be utilised to determine functionality based on successful retrieval or not, rather than checking the output parameter, for example (if it is null/empty or not).</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> dictionary = <span class="hljs-keyword">new</span> Dictionary&lt;<span class="hljs-keyword">string</span>, <span class="hljs-keyword">string</span>&gt;()
{
    { <span class="hljs-string">"Morning"</span>, <span class="hljs-string">"Good Morning"</span> },
    { <span class="hljs-string">"Afternoon"</span>, <span class="hljs-string">"Good afternoon"</span> },
    { <span class="hljs-string">"Evening"</span>, <span class="hljs-string">"Good evening"</span> },
    { <span class="hljs-string">"Night"</span>, <span class="hljs-string">"Good night"</span> },
};

<span class="hljs-keyword">var</span> input = Console.ReadLine(); <span class="hljs-comment">// Dusk</span>

dictionary.TryGetValue(input, <span class="hljs-keyword">out</span> <span class="hljs-keyword">var</span> message);
Console.WriteLine(<span class="hljs-string">$"`Message:<span class="hljs-subst">{message}</span>`"</span>);
<span class="hljs-comment">// Ouput = `Message ` (blank message as default string value is empty string</span>

<span class="hljs-comment">//or check if was able to retrieve and access output if it was</span>
<span class="hljs-keyword">if</span>(dictionary.TryGetValue(input,<span class="hljs-keyword">out</span> <span class="hljs-keyword">var</span> m)){
    Console.WriteLine(message);
}
</code></pre>
<h3 id="heading-indexoutofrangeexception-listsarrays"><code>IndexOutOfRangeException</code> (Lists/Arrays):</h3>
<p><strong>Scenario</strong>: Trying to access an index that’s outside the valid range of a list or array.  </p>
<p>As we know, Arrays are 0 index-based, so trying to access an index of [5] on an Array of 5 items will throw the <code>IndexOutOfRangeException</code>.</p>
<p><strong>Solutions:</strong></p>
<ol>
<li>Ensure the index is within bounds using <code>list.Count</code> or <code>array.Length</code> before access.</li>
</ol>
<ol start="2">
<li>Use the <code>ElementAtOrDefault()</code> method. If it can’t access an item at the given index, it will return the default value, which can then be handled accordingly.</li>
</ol>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> names = <span class="hljs-keyword">new</span> <span class="hljs-keyword">string</span>[]
{
    <span class="hljs-string">"Tony"</span>, <span class="hljs-string">"Clint"</span>, <span class="hljs-string">"Bob"</span>, <span class="hljs-string">"Alice"</span>, <span class="hljs-string">"Lisa"</span>
};

<span class="hljs-keyword">var</span> name = names.ElementAtOrDefault(<span class="hljs-number">6</span>);
Console.WriteLine(name ?? <span class="hljs-string">"Name not found."</span>);
</code></pre>
<h3 id="heading-invalidoperationexception-iterating-collections"><code>InvalidOperationException</code> (Iterating Collections):</h3>
<p><strong>Scenario</strong>: Modifying a collection (for example, adding or removing items) while iterating over it with a <code>foreach</code> loop will throw an <code>InvalidOperationException</code> because you're trying to remove an item from the list while iterating over it with a <code>foreach</code> loop.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> myList = <span class="hljs-keyword">new</span> List&lt;<span class="hljs-keyword">string</span>&gt; { <span class="hljs-string">"Apple"</span>, <span class="hljs-string">"Banana"</span>, <span class="hljs-string">"Cherry"</span>, <span class="hljs-string">"Banana"</span> };

<span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">var</span> item <span class="hljs-keyword">in</span> myList)
{
    <span class="hljs-keyword">if</span> (item == <span class="hljs-string">"Banana"</span>)
    {
        myList.Remove(item); <span class="hljs-comment">// Throws InvalidOperationException</span>
    }
}
</code></pre>
<h4 id="heading-why-this-happens"><strong>Why This Happens:</strong></h4>
<ul>
<li><p>The <code>foreach</code> loop maintains an internal enumerator for the collection.</p>
</li>
<li><p>Modifying the collection (for example, adding/removing items) invalidates the enumerator, which causes the runtime to throw an <code>InvalidOperationException</code>.</p>
</li>
</ul>
<p><strong>Solution 1: Use a</strong> <code>for</code> <strong>Loop</strong></p>
<p>You can use a <code>for</code> loop with an index to safely modify the list during iteration:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> fruits = <span class="hljs-keyword">new</span> List&lt;<span class="hljs-keyword">string</span>&gt; { <span class="hljs-string">"Apple"</span>, <span class="hljs-string">"Banana"</span>, <span class="hljs-string">"Cherry"</span>, <span class="hljs-string">"Banana"</span> };

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; fruits; i++)
{
    <span class="hljs-keyword">if</span> (fruits[i] == <span class="hljs-string">"Banana"</span>)
    {
        fruits.RemoveAt(i);
        <span class="hljs-comment">// Adjust the index to account for the removed item</span>
        i--; 
    }
}
Console.WriteLine(<span class="hljs-keyword">string</span>.Join(<span class="hljs-string">", "</span>, fruits)); 
<span class="hljs-comment">// Output: Apple, Cherry</span>
</code></pre>
<p><strong>Solution 2: Iterate Over a Copy</strong></p>
<p>Another approach is to iterate over a copy of the list using <code>ToList()</code>. This way, you’re not directly iterating over the original collection, so modifications won’t affect the loop.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> originalList = <span class="hljs-keyword">new</span> List&lt;<span class="hljs-keyword">string</span>&gt; { <span class="hljs-string">"Apple"</span>, <span class="hljs-string">"Banana"</span>, <span class="hljs-string">"Cherry"</span>, <span class="hljs-string">"Banana"</span> };

<span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">var</span> item <span class="hljs-keyword">in</span> originalList.ToList()) <span class="hljs-comment">// Create a copy</span>
{
    <span class="hljs-keyword">if</span> (item == <span class="hljs-string">"Banana"</span>)
    {
        originalList.Remove(item); <span class="hljs-comment">// Safe removal</span>
    }
}
Console.WriteLine(<span class="hljs-keyword">string</span>.Join(<span class="hljs-string">", "</span>, originalList)); 
<span class="hljs-comment">// Output: Apple, Cherry</span>
</code></pre>
<p><strong>Solution 3: Use LINQ to Filter</strong></p>
<p>If you only want to remove items based on a condition, you can use LINQ to create a new filtered list:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> fruits = <span class="hljs-keyword">new</span> List&lt;<span class="hljs-keyword">string</span>&gt; { <span class="hljs-string">"Apple"</span>, <span class="hljs-string">"Banana"</span>, <span class="hljs-string">"Cherry"</span>, <span class="hljs-string">"Banana"</span> };

fruits = fruits.Where(item =&gt; item != <span class="hljs-string">"Banana"</span>).ToList(); <span class="hljs-comment">// Filter out "Banana"</span>

Console.WriteLine(<span class="hljs-keyword">string</span>.Join(<span class="hljs-string">", "</span>, fruits)); 
<span class="hljs-comment">// Output: Apple, Cherry</span>
</code></pre>
<h2 id="heading-closing-thoughts">Closing Thoughts</h2>
<p>In this article, you’ve learned about many of the common Data Structures for storing multiple objects and values.</p>
<p>Whether you're storing data in a fixed-size array, managing a dynamic list, working with first-in-first-out queues, last-in-first-out stacks, or key-value pair dictionaries, knowing when and how to use each collection is key to becoming a confident and proficient C# developer.</p>
<p>Mastering these concepts will not only improve your ability to handle data effectively but also lay the groundwork for more advanced topics in data structures and algorithms. Combining these data structures with LINQ can provide some performant and easy-to-use mechanics. To learn more about LINQ you can check out my article <a target="_blank" href="https://www.freecodecamp.org/news/how-to-use-linq/">here</a>.  </p>
<p>As you continue your coding journey, keep experimenting with these collections, apply them in real-world scenarios, and deepen your understanding of their inner workings.</p>
<p>As always should you wish to discuss this article further, any other coding-related problems, or hear about other articles I’m writing, drop me a follow on <a target="_blank" href="https://x.com/grantdotdev">X(Twitter)</a>  </p>
<p>Happy coding! 😊</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Variables and Data Types in JavaScript – Explained With Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ A variable is like a box where you can store data or a reference to data. In this article, you will learn how to create and use variables. You'll also learn about the different data types in JavaScript and how to use them. Let's get started! Table of... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-variables-and-data-types-in-javascript/</link>
                <guid isPermaLink="false">66c3499e4f7405e6476b019b</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ variables ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Austin Asoluka ]]>
                </dc:creator>
                <pubDate>Mon, 19 Aug 2024 13:33:18 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723754441356/34416215-e12b-41ec-8c11-332d2c8214e1.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A variable is like a box where you can store data or a reference to data.</p>
<p>In this article, you will learn how to create and use variables. You'll also learn about the different data types in JavaScript and how to use them.</p>
<p>Let's get started!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-a-variable-example-1">What is a Variable? Example #1</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-a-variable-example-2">What is a Variable? Example #2</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-a-variable-example-3">What is a Variable? Example #3</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-declare-a-variable">How to Declare a Variable</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-variable-assignment-and-initialization">Variable Assignment and Initialization</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-call-a-variable">How to Call a Variable</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-name-variables">How to Name Variables</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-reserved-words-in-javascript">Reserved Words in JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-rules-for-naming-variables-in-javascript">Rules for Naming Variables in JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-popular-variable-naming-conventions">Popular Variable Naming Conventions</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-variable-data-types">Variable Data Types</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-primitive-data-types">Primitive Data Types</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-reference-types-in-javascript">Reference types in JavaScript</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-summary">Summary</a></p>
</li>
</ul>
<h3 id="heading-what-is-a-variable-example-1">What is a Variable? Example #1</h3>
<p>When a child is born, they are given a name and throughout their life, they'll be referred to b<a class="post-section-overview" href="#reference-types-in-javascript">y</a> that name (unless the name gets changed at some point).</p>
<p>Have you seen anyone without a name? How were you able to call them?<br>In an ideal world, everyone should have a name or a unique way we can refer to them. In JavaScript, every variable has a name.</p>
<blockquote>
<p>Everyone must have a name or a way by which we can refer to them.</p>
</blockquote>
<h3 id="heading-what-is-a-variable-example-2"><strong>What is a Variable? Example #2</strong></h3>
<p>In a math equation, when we say <code>x = 1</code> it means, "anywhere you see <code>x</code>, you should replace it with <code>1</code>". In this case, <code>x</code> is a variable, while <code>1</code> is the value of it. That is: <code>x</code> points to <code>1</code>.</p>
<p>This means that without <code>x</code>, there will be no reference to <code>1</code>. There could be other occurrences of <code>1</code> in the equation but those will be different than the <code>1</code> which <code>x</code> was referring to. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">/* The code below means x is 1 
 * So during execution, anywhere x appears after the line below, 
 * the complier replace x with 1.
 */</span>
<span class="hljs-keyword">let</span> x = <span class="hljs-number">1</span>;
<span class="hljs-keyword">let</span> y = <span class="hljs-number">1</span>; <span class="hljs-comment">// the value which y refers to is different from that of x</span>
<span class="hljs-built_in">console</span>.log(x); <span class="hljs-comment">// This line will log 1 to the console.</span>
</code></pre>
<p>In the code snippet above, <code>x</code> refers to the value 1, and <code>y</code> It also refers to another value 1, but note that both values are distinct, just like you can have two different brands of bottled water even though they both contain water.</p>
<p>So, when we mention the variable name <code>x</code>, we get the value assigned to that variable.</p>
<h3 id="heading-what-is-a-variable-example-3"><strong>What is a Variable? Example #3</strong></h3>
<p>A variable can be conceptualized as a container. The variable's name serves as its identifier, its value represents the container's contents, and its type specifies the nature of those contents.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690903992237/a783721f-1fbc-4c84-8df6-24a49e7dddb3.jpeg" alt="Bottle of water" class="image--center mx-auto" width="1280" height="851" loading="lazy"></p>
<p>A popular water brand here in Nigeria is known as "Eva".</p>
<p>Let's say you bought Eva water, took it home, and placed it amongst other water brands. You can easily say to someone, "Please get me the Eva water over there" and because of the name, it becomes easy for the person to identify and get exactly what you need.</p>
<p>Just as you can easily distinguish your Eva water from other water brands by its name, a variable is uniquely identified by its name within a program. While there may be multiple variables storing data, the specific name of a variable allows you to reference its contents precisely.</p>
<p>In JavaScript, values are assigned a name and anytime we need that value, we simply mention the name to which it was assigned. When the code executes, the name of that variable is replaced by the value it refers to.</p>
<p>In the case of the analogy above, the content of the bottle is water and the type is a liquid. But assuming we have a variable <code>x</code> which refers to the value <code>1</code>, the type of the variable is <code>number</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Add the line of code below to the previous code snippet to</span>
<span class="hljs-comment">// find out the data type of x;</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> x)
</code></pre>
<p>In the code snippet above, <code>number</code> is printed to the console because variable x holds the value <code>1</code> which is a number.</p>
<p><strong>Variables exist in our program to help us hold values and be able to refer to them whenever we need to</strong>. <strong>Anywhere a variable is mentioned, the value of that variable is what's being used for the computation at the time</strong>.</p>
<h2 id="heading-how-to-declare-a-variable">How to Declare a Variable</h2>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> score;
</code></pre>
<p>The program above declares/creates a variable called <code>score</code>.</p>
<p>In JavaScript, creating variables is that simple. The type of the variable is the type of the value stored in it. That is, if the variable <code>score</code> holds a value of <code>1</code>, the type for the <code>score</code> variable is <code>number</code>. So we can say, <code>score</code> is a number variable.</p>
<p>To create a variable, we have to do the following;</p>
<ol>
<li><p>Declare the variable using one of these keywords: <code>let</code>, <code>const</code> or <code>var</code>.</p>
</li>
<li><p>Determine a name to call the variable and write it on the same line as the keyword used in step 1.</p>
</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> score; <span class="hljs-comment">// creates variable 'score'</span>
</code></pre>
<p>Notice that this time, we did not give it a value. We just simply created a container that will store something. For now, it is empty. Although it has no content at the moment, we'll surely provide content for it.</p>
<h2 id="heading-variable-assignment-and-initialization">Variable Assignment and Initialization</h2>
<p>We can assign a value to a variable by using the assignment (<code>=</code>) operator—the variable name to the left of it, and the value to the right.</p>
<pre><code class="lang-javascript">score = <span class="hljs-number">1</span>;
</code></pre>
<p>The code snipped above assigns <code>1</code> as the value of <code>score</code> (this is called <strong>variable assignment</strong>).</p>
<p>When we combine variable declaration and assignment in one operation, it is called <strong>variable initialization</strong>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> score = <span class="hljs-number">1</span>;
</code></pre>
<p>As seen above, we declare the variable <code>score</code>, and immediately on the same line, assign the value <code>1</code> to it.</p>
<p>This means that we provided an initial value for the variable when it was created.</p>
<h2 id="heading-how-to-call-a-variable">How to Call a Variable</h2>
<p>If you want to use a variable for an operation at any time in your program, you can simply just "call" it. To <strong>call</strong> a variable is the same as <strong>mentioning</strong> or <strong>using</strong> it.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(score + <span class="hljs-number">1</span>) <span class="hljs-comment">// 2</span>
</code></pre>
<p>In the code snippet above, the variable <code>score</code> was <strong>used</strong> in the line of code. Therefore, It will be replaced with its actual value <code>1</code> during the code execution. This means we'd have <code>1 + 1</code> executed, resulting in <code>2</code>.</p>
<p>In the next section, let's learn how to properly name our variables in other to ensure our codes are neat and readable.</p>
<h2 id="heading-how-to-name-variables">How to Name Variables</h2>
<p>Just like naming a human or pet or labeling an object, we always put in much thought to ensure that the name tells a story and gives an idea of how we feel about the role of that pet, human, or object.</p>
<p>JavaScript is somewhat liberal when it comes to how variable naming can be done and also how long it could be.</p>
<p>For example, <code>pneumonoultramicroscopicsilicovolcanoconiosis</code> is a valid variable name in JavaScript even though it is long.</p>
<p>It is generally a good practice to give meaningful names to variables and they should be of a reasonable length.</p>
<p>Let your variables be simple and contextual. For example: <code>author</code>, <code>publishedDate</code>, <code>readTime</code>, <code>shouldCompress</code>, and so on.</p>
<p>It should be self-explanatory. Just avoid cryptic names where possible.</p>
<h3 id="heading-reserved-words-in-javascript">Reserved Words in JavaScript</h3>
<p>Even though we can create variables as we wish, some names are already being used within JavaScript to mean something specific. These names cannot be used by a developer to identify a variable. They are called reserved words.</p>
<p>For instance, the keyword <code>catch</code> is used to properly handle an error and prevent it from crashing an application. Hence, you cannot call a variable <code>catch</code> in your program.</p>
<p>Below are all the reserved words in JavaScript:</p>
<p><code>arguments</code> <code>await</code> <code>break</code> <code>case</code> <code>catch</code> <code>class</code> <code>const</code> <code>continue</code> <code>debugger</code> <code>default</code> <code>delete</code> <code>do</code> <code>else</code> <code>enum</code> <code>eval</code> <code>export</code> <code>extends</code> <code>false</code> <code>finally</code> <code>for</code> <code>function</code> <code>if</code> <code>implements</code> <code>import</code> <code>in</code> <code>Infinity</code> <code>instanceof</code> <code>interface</code> <code>let</code> <code>NaN</code> <code>new</code> <code>null</code> <code>package</code> <code>private</code> <code>protected</code> <code>public</code> <code>return</code> <code>static</code> <code>super</code> <code>switch</code> <code>this</code> <code>throw</code> <code>true</code> <code>try</code> <code>typeof</code> <code>undefined</code> <code>var</code> <code>void</code> <code>while</code> <code>with</code> <code>yield</code></p>
<p><strong>NOTE</strong>: You do not need to memorize these keywords. If you try to use them, you'll get an error and you'll learn to recognize and know them with experience.</p>
<p>Also, JavaScript has some rules that you must follow when naming variables as well as generally accepted conventions (best practices) that you should know about. Let's talk about them in the next section.</p>
<h3 id="heading-rules-for-naming-variables-in-javascript"><strong>Rules for Naming Variables in JavaScript</strong></h3>
<ul>
<li><p>Reserved words cannot be used as variable names.</p>
</li>
<li><p>The first letter of your variable name should be an alphabet, underscore (_), or a dollar sign ($). You cannot use a number as the first character of your variable name. Even though other kinds of special characters are allowed to start a variable name, as a way of good practice and avoiding complexities at the start, you should just always start with a letter. Using an underscore or dollar sign is symbolic by convention and we'll learn what they mean in the future.</p>
</li>
<li><p>The rest of the variable name may contain anything but symbols, punctuations, and reserved characters (+, -, *, and so on).</p>
</li>
<li><p>Variable names are case-sensitive. This means <code>Boy</code> and <code>boy</code> will be treated as different variables in your program.</p>
</li>
<li><p>A variable name can be as long as is necessary for it to make sense. There is no limit imposed by the language.</p>
</li>
<li><p>Spaces are not allowed in variable names.</p>
</li>
</ul>
<h3 id="heading-popular-variable-naming-conventions"><strong>Popular Variable Naming Conventions</strong></h3>
<ul>
<li><p>Variable names with multiple words should use <strong>camel casing.</strong> That is, the first word has to be all lowercase while the first letter of subsequent words should be uppercase: <code>studentRegistrationNumber</code></p>
</li>
<li><p>Use uppercase letters for constant variables: <code>const PI = 3.1432</code></p>
</li>
<li><p>If a constant variable is composed of multiple words, use snake casing (separation of words with an underscore): <code>const PROGRAM_NAME = "Vacation planner"</code></p>
</li>
<li><p>If a variable is meant to be private, prefix its name with an underscore: <code>let _memorySize = 2042</code>.<br>  <strong>Note</strong>: This is just to let the team (others working on the project) know that the author intends to use it as private. It doesn't prevent the value of the variable from being accessed (there are other ways to ensure this).</p>
</li>
<li><p>It is common practice to prefix Boolean variables with <code>is</code> or <code>has</code>: <code>let isMarked = true</code>.</p>
</li>
</ul>
<p>In the next section, we'll learn about different data types and how to work with them.</p>
<h2 id="heading-variable-data-types">Variable Data Types</h2>
<p>Data type simply means "type of data" 😉.</p>
<p>The word "data" in this context means a piece of information. We'll use the word "value<strong>"</strong> sometimes to mean data and vice versa.</p>
<p>In JavaScript, we store values of different types in variables. These values have different attributes/properties and the type of data a variable holds will determine the operations you can perform with that variable.</p>
<p>For example, if you have water (value) stored in a container (variable), you can use the water (value) to wash or drink, but if what is stored in the container are candies, you can eat them but you won't be able to use them for washing.</p>
<p>If you have a variable that holds numbers, you can use them to perform arithmetic operations. If the variable holds a Boolean, you cannot use it for arithmetic operations but it can be used for logical operations.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">The kind of value stored in the variable determines what you can do with it.</div>
</div>

<p>The data types in JavaScript are categorized into two primary groups, namely;</p>
<ul>
<li><p><strong>Primitive</strong>: Number, String, Boolean, Undefined, Null, BigInt, Symbol</p>
</li>
<li><p><strong>Reference</strong>: Object, Array, Function</p>
</li>
</ul>
<p>In this article, we will not talk about Symbols and BigInt to avoid complexities. The goal is to do our best to explain fundamental concepts to beginners in the most simple way possible.</p>
<p>Let's consider primitive data types.</p>
<h3 id="heading-primitive-data-types"><strong>Primitive Da</strong>ta Types</h3>
<p>Variables having these type of data are called primitives because they hold simple values. The word <a target="_blank" href="https://www.google.com/search?q=primitive&amp;rlz=1C5CHFA_enNG1050NG1050&amp;oq=primitive&amp;aqs=chrome..69i57j0i271.760j0j7&amp;sourceid=chrome&amp;ie=UTF-8">primitive</a> can be translated to mean non-complex.</p>
<p>Primitive values are usually a single unit like 1, "cup", null, undefined, true, and so on. Let's briefly consider how these data types are used and what kind of operations you can perform with them.</p>
<ul>
<li><strong>NUMBER:</strong> In JavaScript, all numbers are floating-point values. Whether they are numbers without decimal points like a whole number that can be negative, positive, zero, or values with a decimal point like 0.2, -0.5, 1, -2, 0. They are all of the <code>number</code> type.</li>
</ul>
<p>This type of value can be used in arithmetic operations like multiplication, division, subtraction, addition, modulus, and so on.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> score1 = <span class="hljs-number">2</span>;
<span class="hljs-keyword">let</span> score2 = <span class="hljs-number">5</span>;
<span class="hljs-keyword">let</span> averageScore = (score1 + score2) <span class="hljs-comment">// 2</span>
<span class="hljs-built_in">console</span>.log(averageScore) <span class="hljs-comment">// 3.5</span>
</code></pre>
<p>To check the data type of a variable's value, use the <code>typeof</code> operator like this: <code>typeof variableName</code>. That is: <code>typeof score1</code></p>
<p>In the code snippet above, <code>score1</code> is a variable which holds a value of <code>2</code>, <code>score2</code> holds a value of <code>5</code>, while the <code>averageScore</code> variable stores the result from dividing the sum of <code>score1</code> and <code>score2</code> by <code>2</code>, which evaluates to <code>3.5</code>.</p>
<p>Using the <code>typeof</code> operator on the <code>score1</code> variable will return <code>number</code>.</p>
<p><strong>Exercise</strong>: Copy the code in the snippet above and run it in your code editor to see how it works for you. You can play around with the values and use the <code>typeof</code> operator to check the variables' data type.</p>
<p>When performing arithmetic operations, you may run into other Number types like <code>Infinity</code>, <code>-Infinity</code> and <code>NaN</code>.</p>
<p><strong>Infinity</strong> means something without any limit. One way to reach infinity is to divide a number by 0.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> result = <span class="hljs-number">12</span> / <span class="hljs-number">0</span>;

<span class="hljs-built_in">console</span>.log(result) <span class="hljs-comment">// Infinity</span>
</code></pre>
<p>In the code above, we divided <code>12</code> by <code>0</code> and logged the result to the console which prints out <code>Infinity</code>.</p>
<p><strong>Negative Infinity</strong> is used to denote a number that is less than any natural number. To arrive at negative infinity, copy the code in the snippet below and run it in your coding environment.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Number</span>.NEGATIVE_INFINITY) <span class="hljs-comment">// -Infinity</span>
</code></pre>
<p><strong>NaN</strong> means Not <strong>a</strong> Number. This will occur when you try to carry out an impossible mathematical operation as shown below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> result = <span class="hljs-string">"Ella"</span> / <span class="hljs-number">2</span>; <span class="hljs-comment">// Trying to divide a string with a number</span>
<span class="hljs-built_in">console</span>.log(result) <span class="hljs-comment">// NaN</span>
</code></pre>
<p>The first line in the code above tries to divide a string by a number and the result is <code>NaN</code>.</p>
<p>You will not often reach infinity or -Infinity as a beginner doing basic/intermediate stuff, but it is something you should be aware of so that you do not get worked up when you see it occur in your code (this is something you do not want to cram in your head). <code>NaN</code> is will occur more often than the others. When you see it, just know something is wrong with the operation you are trying to perform.</p>
<ul>
<li><strong>STRING:</strong> In JavaScript, a string is a collection of characters enclosed in quotes: <code>"Cathy"</code>.</li>
</ul>
<p>The snippet below shows how a string can be used in a JavaScript program:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> author = <span class="hljs-string">"Sleekcodes"</span>;
<span class="hljs-keyword">let</span> publishedDate = <span class="hljs-string">"14 August 2023"</span>;

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Written by: "</span> + author); <span class="hljs-comment">// Written by: Sleekcodes</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Published on: "</span> + publishedDate); <span class="hljs-comment">// Published on: 14 August 2023"</span>
</code></pre>
<p>I am sure you noticed the + operator used with strings. When this occurs, the result is that the string on the right and that on the left will be joined together to become one. This is called string concatenation.</p>
<p>The code above is simply saying, "Create a variable called <code>author</code> and store the text <code>"sleekCodes"</code> as its value, create another variable <code>publishedDate</code> and store the text <code>"14 August 2023"</code> in it."</p>
<p>Then in line 4, we tell the JavaScript engine to log (print) the string "Written by: Sleekcodes<strong>"</strong> to the console. Line 5 also says log <strong>"</strong>Published on: 14 August 2023<strong>"</strong> to the console.</p>
<p>Notice that in the code above, during execution, <code>author</code> gets replaced with the value "Sleekcodes" and <code>publishedDate</code> gets replaced with "14 August 2023" where used.</p>
<p>Strings are used to depict or convey data in text/alphabetic format. A string can be made up of zero or more characters. A string that has no character in it is called an empty string. For example: <code>""</code>.</p>
<ul>
<li><strong>BOOLEAN</strong>: When we need to represent data in two possible states only like true/false, on/of, or yes/no, we use Boolean values. The value of a Boolean variable is either <code>true</code> or <code>false</code>.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> isQualified = <span class="hljs-literal">true</span>

<span class="hljs-keyword">if</span> (isQualified) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Tola is qualified"</span>); <span class="hljs-comment">// Tola is qualified</span>
}
</code></pre>
<p>The code above will print the statement "Tola is qualified", because the value of the variable <code>isQualified</code> is true. That operation is a type of conditional operation. This is where Boolean values shine.</p>
<p><strong>Exercise</strong>: Change the value of <code>isQualified</code> to be <code>false</code> and observe what happens.</p>
<ul>
<li><strong>UNDEFINED</strong>: This is both a value and a data type. <code>undefined</code> is used to indicate that a variable has no defined value. For instance, when a variable is declared (<code>let age</code>), and you try to access its value, the result would be <code>undefined</code>.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> age; <span class="hljs-comment">// note that there is no value assigned to the variable here</span>

<span class="hljs-built_in">console</span>.log(age); <span class="hljs-comment">// undefined</span>
</code></pre>
<p>In the code snippet above, because age isn't given any explicit value, the compiler assigns the value <code>undefined</code> to the variable by default.</p>
<p><strong>Exercise</strong>: Use the <code>typeof</code> operator on the variable <code>age</code> and see what you get. Also, assign the value <code>undefined</code> to <code>age</code> and use the <code>typeof</code> operator on it again to see the result.</p>
<ul>
<li><strong>NULL</strong>: Null is a value we can assign to a variable to indicate that it has no value. It is used to represent "empty" or "unknown".</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> age = <span class="hljs-literal">null</span>;

<span class="hljs-built_in">console</span>.log(age); <span class="hljs-comment">// null</span>
</code></pre>
<p>As seen in the code snippet above, instead of letting the compiler assign <code>undefined</code> for us, we explicitly indicate that the variable has no value by assigning the value <code>null</code> to it.</p>
<p>This means <code>age</code> is empty or unknown.</p>
<p>People often get confused about the difference between <code>undefined</code> and <code>null</code>. One is the default value assigned to a variable without an explicit value, while the other (<code>null</code>) is a value assigned to a variable by the programmer deliberately to indicate that the variable is empty. As a rule of thumb, do not assign <code>undefined</code> to a variable, instead use <code>null</code> (the compiler auto-assigns <code>undefined</code> where needed).</p>
<p>Primitive data types have no complexity. They are plain and simple (a single value). This statement will make more sense when you read about how reference types work in the next section.</p>
<p>Consider the image below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691169563292/8cd6a8de-e6c5-46fe-8271-c2a522b6c663.png" alt="primitive types concept" class="image--center mx-auto" width="1782" height="1447" loading="lazy"></p>
<p><strong>Part A</strong> above is the code you write, while <strong>Part</strong> <strong>B</strong> is what happens when the code runs. For primitive data types, the value is simply assigned to the variable (it is straightforward).</p>
<p>Primitive values are passed by value (they generate no reference). Do not worry about what this means yet because we'll explain in the next section.</p>
<h2 id="heading-reference-types-in-javascript">Reference Types in JavaScript</h2>
<p>Reference data types are data passed by "reference". A thorough understanding of this statement is crucial throughout your career as a JavaScript developer, so do well to pay close attention to the concept we are about to learn.</p>
<p>Consider the image below carefully.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691062567476/e31e1bfe-6b85-418e-a88a-e19810f11839.png" alt="Reference types concept" class="image--center mx-auto" width="2338" height="1633" loading="lazy"></p>
<p>In the image above, <strong>part A</strong> is the code you write, while <strong>part B</strong> is what happens "behind the scenes".</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Use the image above to follow through with the following explanation.sa</div>
</div>

<p>When you create a variable whose data type is in the reference category (objects, functions, arrays), instead of the value being directly assigned to the variable, a reference is generated for the value and that reference is what gets assigned to the variable<strong>.</strong></p>
<p>The reference gets assigned to the variable, but it points to the actual value.</p>
<p>This means that when you try to use the variable anywhere, you are working with the reference to the actual value and anything done to the reference affects the actual value.</p>
<p>Think of it like a middleman between the actual value and the variable name.</p>
<p>Consider the example below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> studentInfo = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"John Doe"</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">205</span>
}

<span class="hljs-keyword">let</span> staffInfo = studentInfo <span class="hljs-comment">//6. This means; assign the ref of studentInfo to staffInfo</span>

staffInfo.name = <span class="hljs-string">"Lorry Sante"</span> <span class="hljs-comment">//8. Change the value of name key in the reference which staffInfo holds.</span>

<span class="hljs-built_in">console</span>.log(studentInfo.name) <span class="hljs-comment">//9. Lorry Sante</span>
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><strong>Try this:</strong> In line 7 and 8, log the value of <a target="_blank" href="http://studentInfo.name"><code>studentInfo.name</code></a> and <a target="_blank" href="http://staffInfo.name"><code>staffInfo.name</code></a> to the console to see what they are.</div>
</div>

<p>You should notice that, changing <code>name</code> in <code>staffInfo</code> object (line 8), causes the name in <code>studentInfo</code> object to change too (as seen in the output of line 9).</p>
<p>In fact, both variables are pointing to the same value technically (see image below);</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691069171621/a53d4f52-6b86-4581-85fc-57452cbc90be.png" alt="reference types variable storage " class="image--center mx-auto" width="1114" height="269" loading="lazy"></p>
<p>When we say that a variable is passed by reference<strong>,</strong> it means that anywhere that variable is used, you are interacting with a reference (that points) to its actual value.</p>
<p>So in the code snippet above, when <code>studentInfo</code> was assigned to <code>staffInfo</code>, we just made <code>staffInfo</code> to store the reference of the <code>studentInfo</code> variable, effectively saying that both <code>staffInfo</code> and <code>studentInfo</code> variables are pointing to the same value.</p>
<p>Therefore, if the reference generated for <code>studentInfo</code> is <code>000xx2</code> and it is true that during execution, variables are replaced by whatever they hold, then <code>staffInfo = studentInfo</code> would become <code>staffInfo = 000xx2</code> during execution, while <code>staffInfo.name</code> would become <code>000xx2.name</code>.</p>
<p>If we had written <code>studentInfo.name</code>, then during execution, it becomes <code>000xx2.name</code>, it should be clear now that both <code>studentInfo</code> and <code>staffInfo</code> holds references to one value. They are like different roads to one destination.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">If this is your first time learning this concept, you should repeat the section above before you proceed. It will become clearer and when we start operating with reference types, you'll be glad you read this article.</div>
</div>

<p>There are three main reference data types that you'll mostly come across in your journey as a JavaScript developer: Object, Array, and Function. Let's look into them one after the other.</p>
<ul>
<li><strong>OBJECT</strong>: An object is a data structure used to store complex data in key/value pairs. The variable created in the previous session has an object type like this:</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> studentInfo = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"John Doe"</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">205</span>
}
</code></pre>
<p>You can see that it isn't primitive (simple). Unlike primitive types with just simple values, an object can be used to store different information which can be made up of even primitive and reference types.</p>
<p>Objects store data in key/value pairs like so: <code>{key: value}</code></p>
<p>In the code snippet above, <code>name</code> is key, while <code>"John Doe"</code> is its value. Also, <code>age</code> is key, while <code>205</code> is its value.</p>
<p>If you notice, both <code>name</code> and <code>age</code> have primitive values (string and number).</p>
<p>To access the value of an object, we use the object name, dot (.) notation, and the key whose value we want to access. For example: <code>objectName.key</code>.</p>
<p>Objects can also contain nested objects like so:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> studentInfo = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"John Doe"</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">205</span>,
    <span class="hljs-attr">beneficiary</span>: {
       <span class="hljs-attr">name</span>: <span class="hljs-string">"Tira Doe"</span>,
       <span class="hljs-attr">age</span>: <span class="hljs-number">200</span>,
       <span class="hljs-attr">relationship</span>: <span class="hljs-string">"Wife"</span>
    }
}
</code></pre>
<p>In the above example, the <code>studentInfo</code> object has a nested object called <code>beneficiary</code>. <code>beneficiary</code> is a key whose value is an object (reference type). Objects can still hold arrays and functions too.</p>
<p>Accessing the value associated with a key in an object within another object (nested object) is natural. We simply use dot notation. Like so: <code>parentObjectName.nestedObjectName.key</code></p>
<p>For example, to access the name of the beneficiary in <code>studentInfo</code> object above, we simply write <code>studentInfo.beneficiary.name</code>.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">There's no limit to nesting objects in objects. However, ensure that nesting is necessary for what you want to achieve and too much nesting should be avoided for simplicity.</div>
</div>

<p>This is not all that you need to know about objects but it is a very sound way to start.</p>
<ul>
<li><strong>ARRAY</strong>: An array is a kind of object but stores data using automatically assigned indexes instead of keys.</li>
</ul>
<p>An array is created by writing a comma-separated list of values enclosed with square brackets: <code>[0, 1, 2, 3, "Tosin", "Mike", {name: "Abel Joe", age: 250}]</code></p>
<p>If you pay close attention to the values used in the array above, you'll notice that they are of different data types. Yes, arrays also allow you to store values of different types in one place but this is strongly discouraged (you shouldn't do it at all). The values in an array should all be of the same type<strong><em>.</em></strong></p>
<p>Example of a proper array: <code>let scores = [1, 3, 5, 6, 9, 12]</code></p>
<p>To access a value in an array, we simply specify the array name, followed by a square bracket <code>[]</code> without any space between the name and the bracket. Then inside the square bracket, provide the index of the value you wish to access. That is: <code>arrayName[index]</code>.</p>
<p>What's an index and how do we know what index refers to the value we want to access?</p>
<p>An index is simply a number automatically assigned to an array value<strong>.</strong> You can think of it as an address for values in the array. Arrays are <code>0</code> indexed (meaning they start counting from zero)<strong>.</strong></p>
<p>To determine the index of the value you wish to access, start counting from the start of the array and your count should start from 0.</p>
<p>Consider the image below;</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691072847798/ca5bc276-f024-40eb-b69e-b8e31f17314f.png" alt="array and indexes" width="483" height="183" loading="lazy"></p>
<p>To access the value <code>80</code> in the <code>scores</code> array depicted in the image above, we simply write <code>scores[3]</code></p>
<p>There is a lot you can do with arrays as a JavaScript developer. For now, this is a simple introduction to the array data type.</p>
<ul>
<li><strong>FUNCTION</strong>: A function is a different kind of variable and it's declared differently (using the <code>function</code> keyword instead of <code>let</code>, <code>const</code> or <code>var</code>). It is a construct used to carry out a specific task.</li>
</ul>
<p>For example, if you need to add two numbers together multiple times within your code, it's best practice to create a dedicated function for this task. By reusing this function, you avoid redundant code and improve code maintainability compared to repeatedly writing the addition logic. Wait!!! You are not lost. The example below will confirm this 😊</p>
<p>Scenario 1 (without function):</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> num1 = <span class="hljs-number">2</span>;
<span class="hljs-keyword">let</span> num2 = <span class="hljs-number">3</span>;
<span class="hljs-keyword">let</span> result = num1 + num2;

<span class="hljs-built_in">console</span>.log(result) <span class="hljs-comment">// 5</span>

<span class="hljs-keyword">let</span> num3 = <span class="hljs-number">3</span>;
<span class="hljs-keyword">let</span> num4 = <span class="hljs-number">8</span>;
<span class="hljs-keyword">let</span> result2 = num3 + num4;

<span class="hljs-built_in">console</span>.log(result2) <span class="hljs-comment">// 11</span>
</code></pre>
<p>Scenario 2 (with function):</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// function declaration.</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span> (<span class="hljs-params">num1, num2</span>) </span>{
    <span class="hljs-keyword">return</span> num1 + num2;
}

<span class="hljs-built_in">console</span>.log(addNumbers(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)); <span class="hljs-comment">// 5</span>
<span class="hljs-built_in">console</span>.log(addNumbers(<span class="hljs-number">3</span>, <span class="hljs-number">8</span>)); <span class="hljs-comment">// 11</span>
</code></pre>
<p>You will agree that, scenario 2 contains less code, looks neater, and even feels more natural.</p>
<p>Functions allow us write helpers that we can call to get a specific job done for us any time we want. We just have to tell it how to do the job once and call it anytime we need it to do that job (passing in any information required for the task as arguments) and it delivers.</p>
<p>Function Syntax:</p>
<p>To write a function, we use the <code>function</code> keyword, followed by the name of the function: <code>functionName</code>, a pair of brackets <code>()</code>, and a pair of curly braces <code>{}</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">functionName</span> (<span class="hljs-params"></span>) </span>{}
</code></pre>
<p>There are a few things/conventions you should have in mind when writing functions:</p>
<ul>
<li><p>Function names should follow the same naming rules as variables.</p>
</li>
<li><p>Function names should be verbs (to depict an action).</p>
</li>
<li><p>The code logic for the actual task should be written between the opening <code>{</code> and closing <code>}</code> curly braces.</p>
</li>
<li><p>If there are values required to carry out the task, they should be passed into the function as arguments. In this case, during the function declaration, parameters should be stated between the opening <code>(</code> and closing <code>)</code> brackets in a comma-separated fashion. That is: <code>function addNumbers(num1, num2)...</code>.</p>
</li>
<li><p>If no data is required to carry out the task, then the opening <code>(</code> and closing <code>)</code> brackets should be left empty: <code>function sayHi()...</code>.</p>
</li>
</ul>
<p>A parameter is a variable defined between the opening <code>(</code> and closing <code>)</code> of a function during its declaration: <code>function doSomething (param1, param2) {...}</code>.</p>
<p>An argument is the value passed into the function during its invocation/call: <code>doSomething(1, 2)</code></p>
<p>As seen above, to call/invoke a function, write the function name, followed by an opening and a closing bracket (without any whitespace). Required arguments should be provided between the opening and closing brackets (if any).</p>
<p>To drive this concept home, let's create a function to multiply two digits:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//        functionName   param1 param2</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">multiplyNumbers</span> (<span class="hljs-params">num1, num2</span>) </span>{
    <span class="hljs-keyword">return</span> num1 * num2; <span class="hljs-comment">// task to carry out.</span>
}
</code></pre>
<p>It's as simple as that.</p>
<p>Having done that, let's call/invoke the function.</p>
<pre><code class="lang-javascript">multiplyNumbers(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>) <span class="hljs-comment">// 6</span>
</code></pre>
<p>Notice that while creating the function, we declared two parameters: <code>num1</code> and <code>num2</code>. When calling the function, we assigned values to the two arguments: 1 and 2.</p>
<p><code>return</code> <strong>keyword</strong></p>
<p>Functions may return values or not.</p>
<p>If a function contains a <code>return</code> statement, like the <code>multiplyNumbers</code> function, then it will return a value if everything goes well. If there is no return statement for the function, it will return <code>undefined</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHi</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hi"</span>);
}
</code></pre>
<p>If we invoke <code>sayHi</code>, it would log the text <code>Hi</code> to the console and it will also return <code>undefined</code>.</p>
<p>Remember that functions are like helpers, when you send a helper to carry out an assignment, you may require them to give you feedback (the result of the task they carried out) or you may not need feedback.</p>
<p>If you need feedback, add a <code>return</code> statement about what feedback you need. Otherwise, do not add a <code>return</code> statement to the function.</p>
<p>There is still a lot to learn about every data type we have highlighted in this article so take your time to practice these basics and when you feel comfortable enough using them, you'll see the need to dive deeper.</p>
<h2 id="heading-summary">Summary</h2>
<p>Variables are "pointers" to values. When you mention (use) a variable anywhere in your code, the variable identifier (name) is replaced with the value it points to. It's just like calling someone's name. The name doesn't respond, the person (value) behind the name is what you hope to get as a response.</p>
<p>By way of retention, do not try to cram all these rules and conventions. Feel free to refer back to this article when programming and in a short amount of time, you'll be used to all of them and you won't need to refer to any article ever again to name your variables properly.</p>
<p>If you should have anything in mind, remember to start variables with a lowercase letter if the variable is made of multiple words, subsequent words should start with uppercase letters. That is: <code>age</code>, <code>dateOfBirth</code>.</p>
<p>To create a variable, use the keyword <code>let</code>, <code>const</code>, or <code>var</code>, followed by the variable name. If you wish to initialize the variable, then on the same line before the semi-colon, input the assignment operator and variable value after it.</p>
<p>For example: <code>let score;</code> or <code>let score = 3;</code> (if you wish to initialize during declaration).</p>
<p>If you wish to use a variable, just mention its name and the value will be used during the execution of your code.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> a = <span class="hljs-number">2</span>;
<span class="hljs-keyword">let</span> b = <span class="hljs-number">3</span>;
<span class="hljs-built_in">console</span>.log(a + b) <span class="hljs-comment">// 4</span>
</code></pre>
<p>This article also showed you the different data types in JavaScript and how to use them.</p>
<p>Did this post help? Let’s keep the conversation going. Feel free to share your thoughts or questions on Twitter (x) or LinkedIn. You can find me on Twitter (x) <a target="_blank" href="https://x.com/asoluka_tee">@asoluka_tee</a> and <a target="_blank" href="https://www.linkedin.com/in/tochukwu-austin-asoluka-415326155/">Tochukwu Austin Asoluka</a> on LinkedIn.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What are Variables and Constants in Go? Explained With Examples ]]>
                </title>
                <description>
                    <![CDATA[ Variables and constants are fundamental concepts in most programming languages. They are the building blocks for storing and managing data. In this article, we'll take a look at how variables and constant work in Go. Table of contents: What are Vari... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/variables-and-constants-in-go/</link>
                <guid isPermaLink="false">66c2f3bae041c8717c0645d2</guid>
                
                    <category>
                        <![CDATA[ Go ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Temitope Oyedele ]]>
                </dc:creator>
                <pubDate>Mon, 19 Aug 2024 07:26:50 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1724052347929/f54eba57-fa4b-4b81-821e-41826d592933.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Variables and constants are fundamental concepts in most programming languages. They are the building blocks for storing and managing data.</p>
<p>In this article, we'll take a look at how variables and constant work in Go.</p>
<h2 id="heading-table-of-contents">Table of contents:</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-are-variables">What are Variables?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-create-a-variable-in-go">How to Create a Variable</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-explicit-declaration">Explicit Declaration</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-shorthand-variable-declaration">Shorthand Variable Declaration</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-multiple-variable-declarations">Multiple Variable Declarations</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-zero-values">Zero Values</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-a-variable-scope">What is a Variable Scope</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-naming-conventions-in-go">Naming Conventions in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-are-constants-in-go">What are Constants in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-declare-constants-in-go">How to Declare Constants in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-types-of-constants-in-go">Type of Constants in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-thats-a-wrap">That's a Wrap</a></p>
</li>
</ul>
<h2 id="heading-what-are-variables">What are Variables ?</h2>
<p>A variable is a storage location identified by a name (or identifier) that holds a value. This value can change (or vary) during a program's execution. This is why it's called a variable.</p>
<p>For example:</p>
<pre><code class="lang-go">myName := “temitope”

fmt.Println(myName)

myName:= ”oyedele”

fmt.Println(myName)
</code></pre>
<p>We created a variable with an identifier of <code>myName</code> which holds a string value.</p>
<p>If you noticed, we changed the value to another string, and we can do that multiple times because variables are allowed to do that.</p>
<p>Variables allow you to store data, which can be of different types, such as integers, floating-point numbers, strings, or objects.</p>
<h2 id="heading-how-to-create-a-variable-in-go">How to Create a Variable in Go</h2>
<p>There are two primary ways to create a variable in Go, explicit declaration and shorthand declaration.</p>
<h3 id="heading-explicit-declaration">Explicit Declaration</h3>
<p>This is the traditional way to create a variable in Go. It works by using the <code>var</code> keyword and declaring the variable’s type, making your code more readable and clear.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {

    <span class="hljs-keyword">var</span> age <span class="hljs-keyword">int</span> = <span class="hljs-number">25</span>

    <span class="hljs-keyword">var</span> name <span class="hljs-keyword">string</span> = <span class="hljs-string">"Temitope"</span>

    <span class="hljs-keyword">var</span> height <span class="hljs-keyword">float64</span> = <span class="hljs-number">5.7</span>

    fmt.Println(age, name, height)

}
</code></pre>
<p>You can see that, for each variable, we declared its datatype before assigning a value to it.</p>
<pre><code class="lang-plaintext">output:
25 Temitope 5.7
</code></pre>
<p>The <code>var</code> keyword and data type can also be used without having an initial value:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">var</span> age <span class="hljs-keyword">int</span>
    <span class="hljs-keyword">var</span> name <span class="hljs-keyword">string</span>
    <span class="hljs-keyword">var</span> height <span class="hljs-keyword">float64</span>

    age = <span class="hljs-number">25</span>
    name = <span class="hljs-string">"Temitope"</span>
    height = <span class="hljs-number">5.7</span>

    fmt.Println(age, name, height)
}
</code></pre>
<p>This way, the variables are declared first without an initial value. They are then assigned values later in the code. You'll still have the same output as the first.</p>
<h3 id="heading-shorthand-variable-declaration">Shorthand Variable Declaration</h3>
<p>The shorthand variable declaration syntax (<code>:=</code>) is a more concise way to declare variables. This method allows you to declare and initialize a variable in a single line without explicitly stating its type, as the type is inferred from the value assigned.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {

    age := <span class="hljs-number">25</span>

    name := <span class="hljs-string">"Temitope"</span>

    height := <span class="hljs-number">5.7</span>

    fmt.Println(age, name, height)

}
</code></pre>
<p>Here, each variable was declared alongside its value, with Go inferring the datatype. For example, <code>age</code> was declared and initialized with a value of 25, and Go inferred its type as <code>int</code>. <code>name</code> was declared with the value "Temitope", and Go inferred its type as <code>string</code>. Lastly, <code>height</code> was declared with 5.7, and Go inferred its type as <code>float64</code>.</p>
<pre><code class="lang-plaintext">output:
25 Temitope 5.7
</code></pre>
<p>One of the drawbacks of the shorthand variable declaration is that you can only use it inside of a function.</p>
<h2 id="heading-multiple-variable-declarations">Multiple Variable Declarations</h2>
<p>You can declare and initialize multiple variables on the same line by separating each variable with a comma. This approach is simple and straightforward. it is commonly used when the variables are related or when you want to initialize them together. For example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {

    <span class="hljs-keyword">var</span> age, height <span class="hljs-keyword">int</span> = <span class="hljs-number">25</span>, <span class="hljs-number">180</span>

    <span class="hljs-keyword">var</span> name, city <span class="hljs-keyword">string</span> = <span class="hljs-string">"Temitope"</span>, <span class="hljs-string">"New York"</span>

    fmt.Println(age, height)

    fmt.Println(name, city)
}
</code></pre>
<p>Here, the variable <code>age</code> and <code>height</code> are both declared as integers and initialized with the values 25 and 180, respectively. Variable <code>name</code> and <code>city</code> are also both declared as strings and initialized with "Temitope" and "New York":</p>
<pre><code class="lang-plaintext">Output:
25 180
Temitope New York
</code></pre>
<p>You can also declare multiple variables in a block like so:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {

    <span class="hljs-keyword">var</span> (
        age <span class="hljs-keyword">int</span> = <span class="hljs-number">25</span>

        name <span class="hljs-keyword">string</span> = <span class="hljs-string">"Temitope"</span>

        height <span class="hljs-keyword">int</span> = <span class="hljs-number">180</span>

        city <span class="hljs-keyword">string</span> = <span class="hljs-string">"New York"</span>
    )

    fmt.Println(age, name, height, city)

}
</code></pre>
<p>Here, the variables <code>age</code>, <code>name</code>, <code>height</code>, and <code>city</code> are declared within a single var block, with each variable getting its own line.</p>
<pre><code class="lang-plaintext">Output:
25 Temitope 180 New York
</code></pre>
<h3 id="heading-zero-values">Zero Values</h3>
<p>When variables are declared without being initialized, they are assigned zero values by default. These values differ depending on the type of variable. Below is an example of how you can declare default values:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {

    <span class="hljs-keyword">var</span> intValue <span class="hljs-keyword">int</span>

    <span class="hljs-keyword">var</span> floatValue <span class="hljs-keyword">float64</span>

    <span class="hljs-keyword">var</span> boolValue <span class="hljs-keyword">bool</span>

    <span class="hljs-keyword">var</span> stringValue <span class="hljs-keyword">string</span>

    <span class="hljs-keyword">var</span> ptrValue *<span class="hljs-keyword">int</span>

    <span class="hljs-keyword">var</span> sliceValue []<span class="hljs-keyword">int</span>

    <span class="hljs-keyword">var</span> mapValue <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>

    fmt.Println(<span class="hljs-string">"Zero values:"</span>)

    fmt.Println(<span class="hljs-string">"int:"</span>, intValue)

    fmt.Println(<span class="hljs-string">"float64:"</span>, floatValue)

    fmt.Println(<span class="hljs-string">"bool:"</span>, boolValue)

    fmt.Println(<span class="hljs-string">"string:"</span>, stringValue)

    fmt.Println(<span class="hljs-string">"pointer:"</span>, ptrValue)

    fmt.Println(<span class="hljs-string">"slice:"</span>, sliceValue)

    fmt.Println(<span class="hljs-string">"map:"</span>, mapValue)

}
</code></pre>
<p>In the code above, here’s what’s going to happen:</p>
<ul>
<li><p>The integer <code>intValue</code> will be given the zero value 0.</p>
</li>
<li><p>The floating-point number <code>floatValue</code> will be given the zero value 0.</p>
</li>
<li><p>The Boolean <code>boolValue</code> will be given the zero value <code>false</code>.</p>
</li>
<li><p>The string <code>stringValue</code> will be given the zero value "" (empty string).</p>
</li>
<li><p>The pointer <code>ptrValue</code>, slice <code>sliceValue</code>, and map <code>mapValue</code> will all be given the zero value <code>nil</code>.</p>
</li>
</ul>
<p>Output:</p>
<pre><code class="lang-plaintext">Output:
Zero values:
int: 0
float64: 0
bool: false
string: 
pointer: &lt;nil&gt;
slice: []
map: map[]
</code></pre>
<h3 id="heading-what-is-a-variable-scope">What is a Variable Scope?</h3>
<p>Variables can be declared either globally or locally. The scope of a variable determines where it can be accessed and modified within your code.</p>
<p>Global variables are declared outside of any function, typically at the top of a file, and they can be accessed by any function within the same package.  Here’s an example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-keyword">var</span> globalCounter <span class="hljs-keyword">int</span> = <span class="hljs-number">0</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">incrementCounter</span><span class="hljs-params">()</span></span> {

    globalCounter++

}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {

    fmt.Println(<span class="hljs-string">"Initial Counter:"</span>, globalCounter)

    incrementCounter()

    fmt.Println(<span class="hljs-string">"After Increment:"</span>, globalCounter)

}
</code></pre>
<p>In the above example, <code>globalCounter</code> is the global variable, and it is accessible by both the <code>incrementCounter</code> function and the <code>main</code> function.</p>
<p>Also, the value of <code>globalCounter</code> persists across function calls. This means that whatever change is made to it in one function affects its value in other parts of the program.</p>
<p>Local variables, on the other hand, are declared within a function or a block and are only accessible within that specific function or block. They are created when the function or block is executed and destroyed once it is completed. For example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">incrementCounter</span><span class="hljs-params">()</span></span> {

    localCounter := <span class="hljs-number">0</span>

    localCounter++

    fmt.Println(<span class="hljs-string">"Local Counter:"</span>, localCounter)

}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {

    incrementCounter()

    incrementCounter()

}
</code></pre>
<p>In the code above, we have the <code>localCounter</code> as the local variable inside the <code>incrementCounter</code> function. Each time <code>incrementCounter</code> is called, a new <code>localCounter</code> is created, initialized to 0, and incremented.</p>
<p>The value of <code>localCounter</code> does not persist between function calls, so it cannot affect any part of a program when a change is made to the function.</p>
<h2 id="heading-naming-conventions-in-go">Naming Conventions in Go</h2>
<p>Proper naming of variables is crucial for writing clean, readable, and maintainable code. Go has some specific conventions and rules for naming variables. Below are some of them:</p>
<ul>
<li><p><strong>Use descriptive names:</strong>  Use names that clearly describe the purpose or content of the variable. For example, instead of using vague names like x or y, use names like <code>age</code>, <code>totalPrice</code>, or <code>userName</code> that clearly convey what the variable represents.</p>
</li>
<li><p><strong>Use CamelCase for Multi-Word Names:</strong> In Go, it's common practice to use camelCase for variable names that consist of multiple words. The first word is lowercase, and the first letter of each subsequent word is capitalized.</p>
</li>
<li><p><strong>Avoid Using Underscores:</strong> Unlike some other languages, Go prefers camelCase over using underscores to separate words in variable names. Stick to camelCase to adhere to Go’s idiomatic style.</p>
</li>
<li><p><strong>Use Short Names for Short-Lived Variables:</strong> For short-lived variables, such as loop counters or indices, it's acceptable to use short names like i, j, or k.</p>
</li>
</ul>
<h2 id="heading-what-are-constants-in-go">What are Constants in Go?</h2>
<p>Constants are immutable values defined at compile time that cannot be modified throughout the program's execution. They are useful for defining values that are known ahead of time and will remain the same.</p>
<p>Imagine you're building an online store where the standard shipping fee is always $10. You can declare it as a constant, so you can use it throughout your program whenever shipping charges need to be applied. If the shipping rates change, you only need to update the value in one place.</p>
<h2 id="heading-how-to-declare-constants-in-go">How to Declare Constants in Go</h2>
<p>You can declare constants using the <code>const</code> keyword, followed by the name, the type (optional if the value implies the type), and the value of the constant. Here’s how:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {

    <span class="hljs-keyword">const</span> pi <span class="hljs-keyword">float64</span> = <span class="hljs-number">3.14159</span>

    <span class="hljs-keyword">const</span> greeting <span class="hljs-keyword">string</span> = <span class="hljs-string">"Hello, World!"</span>

    fmt.Println(<span class="hljs-string">"Pi:"</span>, pi)

    fmt.Println(<span class="hljs-string">"Greeting:"</span>, greeting)

}
</code></pre>
<p>If you try to change a constant after being declared, then you’ll get a compile-time error.</p>
<h2 id="heading-types-of-constants-in-go">Types of Constants in Go</h2>
<p>Constants can be categorized as either typed or untyped. Both types of constants serve the same purpose. They provide fixed, immutable values throughout the program. However, they differ in how Go handles their types and how flexible they are when used.</p>
<p>Untyped constants are not assigned a type unless they are used in a context that requires a type. When you declare an untyped constant, Go will infer the type at the point where the constant is used. This makes untyped constants more flexible because they can be used in a number of settings without requiring type conversion.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-keyword">const</span> gravity = <span class="hljs-number">9.81</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {

    <span class="hljs-keyword">var</span> height <span class="hljs-keyword">int</span> = <span class="hljs-number">10</span>

    <span class="hljs-keyword">var</span> acceleration <span class="hljs-keyword">float64</span> = gravity * <span class="hljs-keyword">float64</span>(height)

    fmt.Println(<span class="hljs-string">"Acceleration:"</span>, acceleration)

}
</code></pre>
<p>Here, <code>gravity</code> is the untyped constant. This means Go can infer its type based on how it is used. When <code>gravity</code> is used in a calculation with a <code>float64</code>, Go will automatically treat it as a <code>float64</code>.</p>
<p>Unlike untyped constants, the typed constants have an explicitly declared type. This means they can only be used in contexts that match that type or can be converted to a compatible type. Typed constants are stricter, ensuring that the value is always treated as the specific type it was declared with.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-keyword">const</span> speedOfLight <span class="hljs-keyword">int</span> = <span class="hljs-number">299792458</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {

    <span class="hljs-keyword">var</span> distance <span class="hljs-keyword">int</span> = speedOfLight * <span class="hljs-number">2</span>

    fmt.Println(<span class="hljs-string">"Distance:"</span>, distance)

}
</code></pre>
<p>Here, <code>speedOfLight</code> is the typed constant with the type <code>int</code>.</p>
<p>It can only be used in operations with other <code>int</code> values or converted explicitly to a different type.</p>
<h2 id="heading-thats-a-wrap">That’s a Wrap</h2>
<p>In this article, we took a look at what variables and constants are and how to declare them in Go.</p>
<p>Variables and constants are critical tools in programming. They allow developers to efficiently manage and manipulate data. When you understand how to use them, you can improve the quality of your code. </p>
<p>Please share if you found this helpful.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ A Beginner's Guide to LLMs – What's a Large-Language Model and How Does it Work? ]]>
                </title>
                <description>
                    <![CDATA[ ChatGPT was released in November 2022. Since then, we’ve witnessed rapid advancements in the field of AI and technology. But did you know that the journey of AI chatbots began way back in 1966 with ELIZA? ELIZA was not as sophisticated as today’s mod... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/a-beginners-guide-to-large-language-models/</link>
                <guid isPermaLink="false">66be59dfcea37428c836a987</guid>
                
                    <category>
                        <![CDATA[ llm ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Beginner Developers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Open Source ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Machine Learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Data Science ]]>
                    </category>
                
                    <category>
                        <![CDATA[ AI ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Artificial Intelligence ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Bhavishya Pandit ]]>
                </dc:creator>
                <pubDate>Thu, 15 Aug 2024 19:41:19 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723750839199/0dc3a4ff-3e4e-4055-b3c1-955474946b0f.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>ChatGPT was released in November 2022. Since then, we’ve witnessed rapid advancements in the field of AI and technology.</p>
<p>But did you know that the journey of AI chatbots began way back in 1966 with ELIZA? ELIZA was not as sophisticated as today’s models like GPT, but it marked the beginning of the exciting path that led us to where we are now.</p>
<p>Language is the essence of human interaction, and in the digital age, teaching machines to understand and generate language has become a cornerstone of artificial intelligence.</p>
<p>The models we interact with today—such as GPT, Llama3, Gemini, and Claude—are known as Large Language Models (LLMs). This is because they are trained on vast datasets of text, enabling them to perform a wide range of language-related tasks.</p>
<p>But what exactly are LLMs, and why is there so much hype surrounding them?</p>
<p>In this article, you'll learn what LLMs are and what is the hype all about.</p>
<h2 id="heading-what-are-llms"><strong>What Are LLMs?</strong></h2>
<p>Large Language Models are AI models trained on vast amounts of text data to understand, generate, and manipulate human language. They are based on deep learning architectures like transformers, which allow them to process and predict text in a way that mimics human understanding.</p>
<p>In simpler terms, an LLM is a computer program that has been trained on many examples to differentiate between an apple and a Boeing 787 – and to be able to describe each of them.</p>
<p>Before they're ready for use and can answer your questions, LLMs are trained on massive datasets. Realistically, a program cannot conclude anything from a single sentence. But after analyzing, say, trillions of sentences, it's able to build a logic to complete sentences or even generate its own.</p>
<h3 id="heading-how-to-train-an-llm">How to Train an LLM</h3>
<p>Here’s how the training process works:</p>
<ol>
<li><p><strong>Data Collection:</strong> The first step involves gathering millions (or even billions) of text documents from diverse sources, including books, websites, research papers, and social media. This extensive dataset serves as the foundation for the model’s learning process.</p>
</li>
<li><p><strong>Learning Patterns:</strong> The model analyzes the collected data to identify and learn patterns in the text. These patterns include grammar rules, word associations, contextual relationships, and even some level of common sense. By processing this data, the model begins to understand how language works.</p>
</li>
<li><p><strong>Fine-Tuning:</strong> After the initial training, the model is fine-tuned for specific tasks. This involves adjusting the model’s parameters to optimize its performance for tasks such as translation, summarization, sentiment analysis, or question-answering.</p>
</li>
<li><p><strong>Evaluation and Testing:</strong> Once trained, the model is rigorously tested against a series of benchmarks to evaluate its accuracy, efficiency, and reliability. This step ensures that the model performs well in real-world applications.</p>
</li>
</ol>
<p>After the training process is completed, the models are heavily tested on a series of benchmarks for accuracy, efficiency, security, and so on.</p>
<h2 id="heading-applications-of-llms"><strong>Applications of LLMs</strong></h2>
<p>LLMs have a wide range of applications, from content generation to prediction and a lot more.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1723742816242/6e40d678-96ed-4f51-aa35-61c565548a32.png" alt="Applications of LLMs in different domains like Healthcare, Education, Customer Support, and so on." class="image--center mx-auto" width="762" height="742" loading="lazy"></p>
<h3 id="heading-content-creation"><strong>Content Creation:</strong></h3>
<ul>
<li><p><strong>Writing Assistance:</strong> Tools like Grammarly utilize LLMs to provide real-time suggestions for improving grammar, style, and clarity in writing. Whether you’re drafting an email or writing a novel, LLMs can help you polish your text.</p>
</li>
<li><p><strong>Automated Storytelling:</strong> AI models can now generate creative content, from short stories to full-length novels. These models can emulate the style of famous authors or even create entirely new literary styles.</p>
</li>
</ul>
<h3 id="heading-customer-service"><strong>Customer Service:</strong></h3>
<ul>
<li><p><strong>Chatbots:</strong> Many companies deploy AI-powered chatbots that can understand and respond to customer inquiries in real time. These chatbots can handle a wide range of tasks, from answering frequently asked questions to processing orders.</p>
</li>
<li><p><strong>Personal Assistants:</strong> Virtual assistants like Siri and Alexa use LLMs to interpret and respond to voice commands, providing users with information, reminders, and entertainment on demand.</p>
</li>
</ul>
<h3 id="heading-healthcare"><strong>Healthcare:</strong></h3>
<ul>
<li><p><strong>Medical Record Summarization:</strong> LLMs can assist healthcare professionals by summarizing patient records, making it easier to review critical information and make informed decisions.</p>
</li>
<li><p><strong>Diagnostic Assistance:</strong> AI models can analyze patient data and medical literature to assist doctors in diagnosing diseases and recommending treatments.</p>
</li>
</ul>
<h3 id="heading-research-and-education"><strong>Research and Education:</strong></h3>
<ul>
<li><p><strong>Literature Review:</strong> LLMs can sift through vast amounts of research papers to provide concise summaries, identify trends, and suggest new research directions.</p>
</li>
<li><p><strong>Educational Tools:</strong> AI-powered tutors can offer personalized learning experiences by adapting to a student’s progress and needs. These tools can provide instant feedback and tailored study plans.</p>
</li>
</ul>
<h3 id="heading-entertainment"><strong>Entertainment:</strong></h3>
<ul>
<li><p><strong>Game Development:</strong> LLMs are used to create more dynamic and responsive characters in video games. These AI-driven characters can engage with players more realistically and interactively.</p>
</li>
<li><p><strong>Music and Art Generation:</strong> AI models are now capable of composing music, generating artwork, and even writing scripts for movies, pushing the boundaries of creative expression.</p>
</li>
</ul>
<h2 id="heading-challenges-with-llms"><strong>Challenges with LLMs</strong></h2>
<p>While LLMs are powerful, they are not without their challenges. ChatGPT has over 150 Million monthly users, this gives us an idea about how big the impact of AI is. But new technologies pose some challenges too.</p>
<h3 id="heading-bias-and-fairness"><strong>Bias and Fairness:</strong></h3>
<ul>
<li>LLMs learn from the data they are trained on, which can include biases present in society. This can lead to biased or unfair outcomes in their predictions or responses. Addressing this requires careful dataset curation and algorithm adjustments to minimize bias.</li>
</ul>
<h3 id="heading-data-privacy"><strong>Data Privacy:</strong></h3>
<ul>
<li>LLMs may inadvertently learn and retain sensitive information from the data they are trained on, raising privacy concerns. There’s ongoing research on how to make LLMs more privacy-preserving.</li>
</ul>
<h3 id="heading-resource-intensive"><strong>Resource Intensive:</strong></h3>
<ul>
<li>Training LLMs require immense computational power and large datasets, which can be costly and environmentally taxing. Efforts are being made to create more efficient models that require less energy and data.</li>
</ul>
<h3 id="heading-interpretability"><strong>Interpretability:</strong></h3>
<ul>
<li>LLMs are often seen as "black boxes," meaning it’s challenging to understand exactly how they arrive at certain conclusions. Developing methods to make AI more interpretable and explainable is an ongoing research area.</li>
</ul>
<h2 id="heading-coding-with-llms-a-replicate-example"><strong>Coding with LLMs: A Replicate Example</strong></h2>
<p>For those of you who like to get your hands dirty with code, here’s a quick example of how to use an LLM with the Replicate library.</p>
<p><strong>Replicate</strong> is a Python package that simplifies the process of running machine learning models in the cloud. It provides a user-friendly interface to access and utilize a vast collection of pre-trained models from the Replicate platform.</p>
<p>With Replicate, you can easily:</p>
<ul>
<li><p>Run models directly from your Python code or Jupyter notebooks.</p>
</li>
<li><p>Access various model types, including image generation, text generation, and more.</p>
</li>
<li><p>Leverage powerful cloud infrastructure for efficient model execution.</p>
</li>
<li><p>Integrate AI capabilities into your applications without the complexities of model training and deployment.</p>
</li>
</ul>
<p>Here’s a simple code snippet to generate text using Meta's llama3-70b-instruct model. <strong>Llama 3</strong> is one of the latest open-source large language models developed by Meta. It's designed to be highly capable, versatile, and accessible, allowing users to experiment, innovate, and scale their AI applications.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> os
<span class="hljs-keyword">import</span> replicate <span class="hljs-comment"># pip install replicate</span>

<span class="hljs-comment"># Get your token from -&gt; https://replicate.com/account/api-tokens</span>
os.environ[<span class="hljs-string">"REPLICATE_API_TOKEN"</span>] = <span class="hljs-string">"TOKEN"</span>
api = replicate.Client(api_token=os.environ[<span class="hljs-string">"REPLICATE_API_TOKEN"</span>])

<span class="hljs-comment"># Running llama3 model using replicate</span>
output = api.run(
    <span class="hljs-string">"meta/meta-llama-3-70b-instruct"</span>,
        input={<span class="hljs-string">"prompt"</span>: <span class="hljs-string">'Hey how are you?'</span>}
    )

<span class="hljs-comment"># Printing llama3's response</span>
<span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> output:
    print(item, end=<span class="hljs-string">""</span>)
</code></pre>
<p>Explanation:</p>
<ul>
<li><p>We first save the replicate token using the os package as an environment variable.</p>
</li>
<li><p>Then we use the Llama3 70b-instruct model to give a response based on our prompt. You can customize the output by changing the prompt.</p>
</li>
</ul>
<p>And what is a prompt? <strong>A prompt is essentially a text-based instruction or query given to an AI model.</strong> It's like providing a starting point or direction for the AI to generate text, translate languages, write different kinds of creative content, and answer your questions in an informative way.</p>
<p>For example:</p>
<ul>
<li><p><strong>"Write a poem about a robot exploring the ocean."</strong></p>
</li>
<li><p><strong>"Translate 'Hello, how are you?' into Spanish."</strong></p>
</li>
<li><p><strong>"Explain quantum computing in simple terms."</strong></p>
</li>
</ul>
<p>These are all prompts that guide the AI to produce a specific output.</p>
<p>Using Meta's <strong>llama-3-70b-instruct</strong>, you can build various tools around applications that are mentioned in this article. Tweak the prompts based on your use case and you will be ready to go! ⚡️</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>In this article, we explored the world of Large Language Models, providing a high-level understanding of how they work and their training process. We delved into the core concepts of LLMs, including data collection, pattern learning, and fine-tuning, and discussed the extensive applications of LLMs across various industries.</p>
<p>While LLMs offer immense potential, they also come with challenges such as bias, privacy concerns, resource demands, and interpretability. Addressing these challenges is crucial as AI continues to evolve and integrate more deeply into our lives.</p>
<p>We also provided a glimpse into how you can start working with LLMs using the Replicate library, showing that even complex models like Llama3 70b-instruct can be accessible to developers with the right tools.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Create A Color Picker Tool Using HTML, CSS, and JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ Have you ever wanted to create your own interactive tools using just HTML, CSS, and JavaScript? In this article, we'll create a fun and straightforward project: a color picker tool. This handy little tool will let users select any color they like and... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/create-color-picker-using-html-css-and-javascript/</link>
                <guid isPermaLink="false">66bde01135055423d89b698f</guid>
                
                    <category>
                        <![CDATA[ HTML5 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Fanny Nyayic ]]>
                </dc:creator>
                <pubDate>Thu, 15 Aug 2024 11:01:37 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723709466316/80aae148-6211-4070-ba33-eb4290408912.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Have you ever wanted to create your own interactive tools using just HTML, CSS, and JavaScript? In this article, we'll create a fun and straightforward project: a color picker tool.</p>
<p>This handy little tool will let users select any color they like and instantly see its HEX and RGB values.</p>
<p>So, grab your favorite code editor, and let's get started!</p>
<h2 id="heading-step-1-set-up-your-project">Step 1: Set Up Your Project</h2>
<ol>
<li><p><strong>Create a New Folder</strong>: Start by creating a new folder on your computer for this project. You can name it <strong>color-picker-tool</strong>.</p>
</li>
<li><p><strong>Create Files</strong>: Inside the folder, create three files:</p>
<ul>
<li><p><strong>index.html</strong></p>
</li>
<li><p><strong>styles.css</strong></p>
</li>
<li><p><strong>script.js</strong></p>
</li>
</ul>
</li>
</ol>
<p>    <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1723707100431/55c7cc93-7b0d-4d67-abb1-8104dbeda18d.png" alt="55c7cc93-7b0d-4d67-abb1-8104dbeda18d" class="image--center mx-auto" width="1920" height="1080" loading="lazy"></p>
<h2 id="heading-step-2-build-the-html-structure">Step 2: Build the HTML Structure</h2>
<ol>
<li><p>Open the <strong>index.html</strong> file in your code editor.</p>
</li>
<li><p><strong>Add Basic HTML Structure</strong>: Add the following code into <strong>index.html</strong>: or press <code>SHIFT+!</code> then press <code>Enter</code> to set the Emmet structure, then change the document title to <code>"Color Picker Tool".</code></p>
</li>
<li><p>Link your <strong>styles.css</strong> and <strong>script.js</strong> files too.</p>
<pre><code class="lang-html"> <span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
 <span class="hljs-tag">&lt;<span class="hljs-name">html</span> <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">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>Color Picker Tool<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"styles.css"</span>&gt;</span>
 <span class="hljs-tag">&lt;/<span class="hljs-name">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">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
 <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
 <span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
</li>
</ol>
<h3 id="heading-explanation">Explanation:</h3>
<ul>
<li><p><code>&lt;!DOCTYPE html&gt;</code>: This tells the browser that the document is an HTML5 document.</p>
</li>
<li><p><code>&lt;html lang="en"&gt;</code>: The root element of the HTML document, with the language set to English.</p>
</li>
<li><p><code>&lt;head&gt;</code>: Contains meta-information about the document, like character set and title.</p>
</li>
<li><p><code>&lt;title&gt;</code>: Sets the title of the webpage, which appears in the browser tab.</p>
</li>
<li><p><code>&lt;link rel="stylesheet" href="styles.css"&gt;</code>: Links to the CSS file that styles the page.</p>
</li>
<li><p><code>&lt;body&gt;</code>: Contains the content of the webpage.</p>
</li>
<li><p><code>&lt;script src="script.js"&gt;&lt;/script&gt;</code>: Links to the JavaScript file that adds interactivity to the page.</p>
</li>
</ul>
<ol start="3">
<li><p><strong>Add the body content:</strong></p>
<pre><code class="lang-xml"> <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"color-picker"</span>&gt;</span>
   <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"color"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"colorInput"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"#ff0000"</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"color-info"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>HEX: <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"hexValue"</span>&gt;</span>#ff0000<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>RGB: <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"rgbValue"</span>&gt;</span>rgb(255, 0, 0)<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
     <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
 <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<h3 id="heading-explanation-1">Explanation:</h3>
</li>
</ol>
<ul>
<li><p><code>&lt;div class="color-picker"&gt;</code>: A container for the color picker elements.</p>
</li>
<li><p><code>&lt;input type="color" id="colorInput" value="#ff0000"&gt;</code>: An input element that lets users pick a color. The <code>value</code> attribute sets the default color.</p>
</li>
<li><p><code>&lt;div class="color-info"&gt;</code>: A container for displaying color information.</p>
</li>
<li><p><code>&lt;p&gt;HEX: &lt;span id="hexValue"&gt;#ff0000&lt;/span&gt;&lt;/p&gt;</code>: Displays the HEX value of the selected color.</p>
</li>
<li><p><code>&lt;p&gt;RGB: &lt;span id="rgbValue"&gt;rgb(255, 0, 0)&lt;/span&gt;&lt;/p&gt;</code>: Displays the RGB value of the selected color.</p>
</li>
</ul>
<p>Here is what we'll have:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1723708023384/8a3b4b0f-39a3-4cc6-9550-64b593cd5662.png" alt="8a3b4b0f-39a3-4cc6-9550-64b593cd5662" class="image--center mx-auto" width="2120" height="1130" loading="lazy"></p>
<h2 id="heading-step-3-style-with-css">Step 3: Style with CSS</h2>
<ol>
<li><p>Open the <strong>styles.css</strong> file in your code editor.</p>
</li>
<li><p><strong>Add CSS Styles</strong>: Copy and paste the following code into <strong>styles.css</strong>:</p>
<pre><code class="lang-css"> <span class="hljs-selector-tag">body</span> {
     <span class="hljs-attribute">font-family</span>: Arial, sans-serif;
     <span class="hljs-attribute">display</span>: flex;
     <span class="hljs-attribute">justify-content</span>: center;
     <span class="hljs-attribute">align-items</span>: center;
     <span class="hljs-attribute">height</span>: <span class="hljs-number">100vh</span>;
     <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
     <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#f0f0f0</span>;
 }
 <span class="hljs-selector-class">.color-picker</span> {
     <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#fff</span>;
     <span class="hljs-attribute">padding</span>: <span class="hljs-number">20px</span>;
     <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">8px</span>;
     <span class="hljs-attribute">box-shadow</span>: <span class="hljs-number">0</span> <span class="hljs-number">4px</span> <span class="hljs-number">8px</span> <span class="hljs-built_in">rgba</span>(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0.1</span>);
     <span class="hljs-attribute">text-align</span>: center;
 }
 <span class="hljs-selector-class">.color-info</span> {
     <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">20px</span>;
 }
 <span class="hljs-selector-tag">p</span> {
     <span class="hljs-attribute">margin</span>: <span class="hljs-number">5px</span> <span class="hljs-number">0</span>;
     <span class="hljs-attribute">font-size</span>: <span class="hljs-number">16px</span>;
 }
</code></pre>
</li>
</ol>
<h3 id="heading-explanation-2">Explanation:</h3>
<ul>
<li><p><code>body</code>: Styles the body of the page. It centers the content both vertically and horizontally and sets a light gray background.</p>
</li>
<li><p><code>font-family: Arial, sans-serif;</code>: Sets the font for the text on the page.</p>
</li>
<li><p><code>display: flex;</code>: Uses Flexbox to layout the page.</p>
</li>
<li><p><code>justify-content: center;</code> and <code>align-items: center;</code>: Centers the content.</p>
</li>
<li><p><code>height: 100vh;</code>: Sets the height to 100% of the viewport height.</p>
</li>
<li><p><code>margin: 0;</code>: Removes default margin.</p>
</li>
<li><p><code>background-color: #f0f0f0;</code>: Sets the background color of the page.</p>
</li>
<li><p><code>.color-picker</code>: Styles the color picker container with a white background, padding, rounded corners, and a shadow for a card-like appearance.</p>
</li>
<li><p><code>.color-info</code>: Adds a margin at the top to separate it from the color input.</p>
</li>
<li><p><code>p</code>: Styles the paragraphs within the color info, setting margin and font size.</p>
</li>
</ul>
<p>Here is what we will have:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1723708068790/0b16e350-d292-4076-b5ee-29016970f762.png" alt="0b16e350-d292-4076-b5ee-29016970f762" class="image--center mx-auto" width="901" height="654" loading="lazy"></p>
<p>At this point, we can pick a color but the color codes won't be displayed. To have the color codes displayed, we'll have to add some JavaScript.</p>
<h2 id="heading-step-4-add-javascript-functionality">Step 4: Add JavaScript Functionality</h2>
<ol>
<li><p>Open the <code>script.js</code> file in your code editor.</p>
</li>
<li><p><strong>Add JavaScript Code</strong>: Add the following code into <code>script.js</code>:</p>
<pre><code class="lang-javascript"> <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'colorInput'</span>).addEventListener(<span class="hljs-string">'input'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
     <span class="hljs-keyword">const</span> color = <span class="hljs-built_in">this</span>.value;
     <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'hexValue'</span>).textContent = color;
     <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'rgbValue'</span>).textContent = hexToRgb(color);
 });
 <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">hexToRgb</span>(<span class="hljs-params">hex</span>) </span>{
     <span class="hljs-keyword">const</span> r = <span class="hljs-built_in">parseInt</span>(hex.slice(<span class="hljs-number">1</span>, <span class="hljs-number">3</span>), <span class="hljs-number">16</span>);
     <span class="hljs-keyword">const</span> g = <span class="hljs-built_in">parseInt</span>(hex.slice(<span class="hljs-number">3</span>, <span class="hljs-number">5</span>), <span class="hljs-number">16</span>);
     <span class="hljs-keyword">const</span> b = <span class="hljs-built_in">parseInt</span>(hex.slice(<span class="hljs-number">5</span>, <span class="hljs-number">7</span>), <span class="hljs-number">16</span>);
     <span class="hljs-keyword">return</span> <span class="hljs-string">`rgb(<span class="hljs-subst">${r}</span>, <span class="hljs-subst">${g}</span>, <span class="hljs-subst">${b}</span>)`</span>;
 }
</code></pre>
<h3 id="heading-explanation-3">Explanation:</h3>
<ul>
<li><p><code>document.getElementById('colorInput')</code>: Selects the color input element by its <code>ID</code>.</p>
</li>
<li><p><code>.addEventListener('input', function() {...})</code>: Adds an event listener that triggers whenever the user selects a new color.</p>
</li>
<li><p><code>const color = this.value;</code>: Gets the current value of the color input, which is in HEX format.</p>
</li>
<li><p><code>document.getElementById('hexValue').textContent = color;</code>: Updates the text content of the HEX value display with the selected color.</p>
</li>
<li><p><code>document.getElementById('rgbValue').textContent = hexToRgb(color);</code>: Converts the HEX color to RGB and updates the RGB value display.</p>
</li>
<li><p><code>function hexToRgb(hex) {...}</code>: A function that converts a HEX color string to an RGB string.</p>
<ul>
<li><p><code>parseInt(hex.slice(1, 3), 16)</code>: Converts the first two characters of the HEX color (after the <code>#</code>) to a decimal number, representing the red component.</p>
</li>
<li><p><code>parseInt(hex.slice(3, 5), 16)</code>: Converts the next two characters to the green component.</p>
</li>
<li><p><code>parseInt(hex.slice(5, 7), 16)</code>: Converts the last two characters to the blue component.</p>
</li>
<li><p><code>return</code> rgb(${r}, ${g}, ${b})<code>;</code>: Returns the RGB color as a string.</p>
</li>
</ul>
</li>
</ul>
</li>
</ol>
<h2 id="heading-step-5-test-your-color-picker-tool">Step 5: Test Your Color Picker Tool</h2>
<ol>
<li><p><strong>Open the Project in a Browser</strong>: Open the <strong>index.html</strong> file in a web browser to view your color picker tool.</p>
</li>
<li><p><strong>Interact with the Tool</strong>: Use the color input to select different colors. The HEX and RGB values should update automatically as you select new colors.</p>
</li>
</ol>
<h3 id="heading-final-thoughts">Final Thoughts</h3>
<p>Congratulations! You've successfully created a color picker tool using HTML, CSS, and JavaScript.</p>
<p>This project is a great way to practice working with user input and manipulating the DOM. You can further enhance this tool by adding features like copying color values to the clipboard or saving favorite colors.</p>
<p>Enjoy experimenting and learning!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Does Recursion Work? Explained with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ In this article, you will learn about recursion and how it works. You need a good understanding of how functions work before learning recursion. I have used Python code for examples in this article because of its simple syntax, but the concept of rec... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-recursion/</link>
                <guid isPermaLink="false">66d4608b230dff016690584b</guid>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Recursion ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Palistha Singh ]]>
                </dc:creator>
                <pubDate>Thu, 25 Jul 2024 15:03:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/07/Frame-1--6-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this article, you will learn about recursion and how it works.</p>
<p>You need a good understanding of how functions work before learning recursion. I have used Python code for examples in this article because of its simple syntax, but the concept of recursion is the same for every programming language.</p>
<h2 id="heading-what-is-recursion">What is Recursion?</h2>
<p>In most programming languages, a function can call another function. But a function can also call itself. Recursion is the technique where a function calls itself.</p>
<p>Here's an example:</p>
<pre><code class="lang-bash">def call_me():
    call_me()
</code></pre>
<p>Here, the function calls itself, which is called recursion.</p>
<p>But "calling itself" is just a programmatic definition of recursion. Recursion involves breaking down a problem into smaller pieces to the point that it cannot be further broken down. You solve the small pieces and put them together to solve the overall problem.</p>
<h2 id="heading-real-life-analogy-of-recursion">Real Life Analogy of Recursion</h2>
<p>Lets understand how recursion really works with the help of an example.</p>
<p>Imagine you're in line for a Disney ride, and you don't know how many people are ahead of you.</p>
<p>To find out, you ask the person in front of you.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/How-many--4-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Trying to find out how many people are in front of you in line</em></p>
<p>That person also doesn't know, so they ask the person in front of them.</p>
<p>This process continues until the question reaches the person at the very front of the line, who sees that there is no one in front of them and replies that there are zero people ahead.</p>
<p>The replies then start to propagate back through the line. Each person adds one to the number they were told before passing the information back.</p>
<p>When the person at the front replies, <strong>"There are 0 people ahead"</strong> the next person adds one and replies, <strong>"There is 1 person ahead"</strong> and so on.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/How-many--5-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Everyone knows how many people are in front of them in line</em></p>
<p>By the time the response reaches the person directly in front of you, they add one more and tell you. This way, you can determine your position in the line by just adding <strong>1</strong> to the number the person in front of you gave.</p>
<p>This example illustrates how recursion breaks a problem into smaller subproblems and then combines their solutions to solve the original problem.</p>
<p>Each person in the line represents a smaller instance of the same problem: determining the number of people ahead. By solving these smaller instances and combining their results, the overall problem is resolved. This is exactly how recursion works.</p>
<h2 id="heading-technical-details-of-recursion">Technical Details of Recursion</h2>
<p>The most important things to consider while coding recursion is to find out:</p>
<ul>
<li><p><strong>Recursive Case:</strong> Minimum work we can do. In the above example, asking the person in front of you how many people are ahead of them is the least amount of work we can do.</p>
</li>
<li><p><strong>Base Case:</strong> Condition where no work is required. In the above example, the person on the front of the line doesn’t have to ask anything so it is the condition where no work is required.</p>
</li>
</ul>
<h2 id="heading-simple-example-of-recursion">Simple Example of Recursion</h2>
<p>Calculating a factorial is the simplest example of recursion that will really help you understand how it works.</p>
<p>There are many ways to calculate the factorial of a number. But here we will see the recursive way to find it.</p>
<p>Before thinking about how we do it, we need to know what the factorial of a number is.</p>
<p>The factorial of a number is the multiplication of all numbers from <strong>1</strong> up to that number.</p>
<p>For example, the factorial of <strong>5</strong> is <strong>120</strong> – that is <strong>5</strong>×<strong>4</strong>×<strong>3</strong>×<strong>2</strong>×<strong>1</strong>.</p>
<p>We can also represent this mathematically like this:</p>
<p><code>5×(5−1)!</code></p>
<p>This means that if we know the value of <code>(5−1)!</code> we can easily get the factorial by just multiplying <strong>5</strong> by it.</p>
<p>Here’s how we find the factorials of <strong>4</strong>, <strong>3</strong>, <strong>2</strong>, <strong>1</strong>, and <strong>0</strong>:</p>
<pre><code class="lang-bash">Factorial of 4 = 4×(4−1)!
Factorial of 3 = 3×(3−1)!
Factorial of 2 = 2×(2−1)!
Factorial of 1 = 1
Factorial of 0 = 1
</code></pre>
<p>By looking at this, it is clear that to find the factorial of <strong>5</strong>, we must multiply <strong>5</strong> by <code>4!</code>.</p>
<h3 id="heading-more-general-example">More general example</h3>
<p>To find the factorial of <code>n</code>, we need to multiply <code>n</code> with <code>(n−1)!</code>. This is something you need to do recursively.</p>
<p>Now, there must be a stopping condition for recursion. The stopping condition is where we perform no further operation. When <code>n</code> is <strong>1</strong> or <code>n</code> is <strong>0</strong>, we can simply stop the recursion as these values have known factorials. We can simply say the factorial of <strong>1</strong> is <strong>1</strong> and the same is true for <strong>0</strong>.</p>
<p>So, breaking it down, the minimum amount of work we need to do to find the factorial of n is <code>n×(n−1)!</code>. And we can stop performing operations on it when we find the factorial of <strong>1</strong> or <strong>0</strong>.</p>
<p>Let's see how it looks in code:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># calculate factorial of n</span>
def fact(n):

   <span class="hljs-comment"># no work required</span>
    <span class="hljs-keyword">if</span> n == 1 or n == 0:
        <span class="hljs-built_in">return</span> 1

    <span class="hljs-comment"># minimum amount of work</span>
    <span class="hljs-built_in">return</span> n * fact(n - 1)

n = 5

<span class="hljs-comment"># calculate factorial</span>
factorial = fact(n)
<span class="hljs-built_in">print</span>(factorial)
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-bash">120
</code></pre>
<p>Let's see how it works:</p>
<p>In the first function call, the factorial of <strong>5</strong> is evaluated. Then in the second call, the factorial of <strong>4</strong> is evaluated, and so on until the factorial of <strong>2</strong> is evaluated.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/Frame-1--5-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Recursively calculating Factorial of 5</em></p>
<p>While calling the factorial of <strong>2</strong>, we have <code>2×fact(2−1)</code>, which is <code>2×fact(1)</code>.</p>
<p>This hits our base case. So, the recursion stops and <code>2×fact(1)</code> returns <code>2×1</code> to the preceding function call, and the result gets popped up the stack.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/Frame-3.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Fourth function call returning 2 to preceding function call and getting popped up from the stack</em></p>
<p>Similarly, here’s how everything else evaluates:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/Frame-4.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>3rd function call returning 6 to the preceding function call and getting popped up from the stack</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/Frame-5.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>2nd function call returning 24 to the preceding function call and getting popped up from the stack</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/Frame-6.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>1st function call returning 120 to the initial function call and getting popped up from the stack</em></p>
<p>So the function finally returns the value <strong>120</strong> to the initial function call.</p>
<h3 id="heading-why-do-we-need-a-base-case">Why Do We Need a Base Case?</h3>
<p>In the above example we have used the stopping condition for the code. But what if we don’t add a stopping condition or what if the function we write never meets the stopping condition?</p>
<p>Will the code run forever?</p>
<p>No – even if you don’t terminate, your code won't run forever. Let’s understand why this is the case with the help of an example.</p>
<pre><code class="lang-bash">def print_five():
    <span class="hljs-built_in">print</span>(5)

    <span class="hljs-comment"># call itself</span>
    print_five()

<span class="hljs-comment"># function call</span>
print_five()
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-bash">5
5
5
...

RecursionError: maximum recursion depth exceeded
</code></pre>
<p>If you run the above code, you will see that the function doesn’t run forever and ends with a message <code>RecursionError: maximum recursion depth exceeded</code>.</p>
<p>When a function is invoked, it is stored in a call stack. Here's how the function <code>print_five()</code> is stored in the call stack when it is invoked for the first time.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/How-many--6-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Call stack on the first function call</em></p>
<p>The function calls itself again and again, and the function is stored in the call stack with each call.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/How-many--8-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Call stack after n function calls</em></p>
<p>But the call stack has a limited size and cannot store an unlimited number of functions.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/How-many--7-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>No space on call stack resulting in stack overflow</em></p>
<p>When the stack is full, it cannot accommodate any more calls, causing a stack overflow error.</p>
<p>Therefore, the base case is essential to prevent such errors and ensure the recursion terminates properly.</p>
<p>Now let's see another example to understand recursion even more.</p>
<h2 id="heading-how-to-check-if-a-word-is-a-palindrome">How to Check if a Word is a Palindrome</h2>
<p>Before we dive into the code, you should know what a palindrome is. A palindrome is a word that reads the same forwards and backwards.</p>
<p>For example, <code>racecar</code> reads the same forwards and backwards.</p>
<p>To check if a word is a palindrome, we have to check if the first and last letters are the same. If they are, we then check if the second and second-to-last letters are the same.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/Frame-7.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Check if first and last characters of racecar are the same</em></p>
<p>In the context of <code>racecar</code>, the first and last letters are the same, so we check if the second and second-to-last letters are the same. They are, so now we check if the third and third-to-last letters are the same. Now there is only one letter left to check. A single letter is always a palindrome because it reads the same both ways.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/Frame-8.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>How to check if racecar is a palindrome</em></p>
<p>So, now let's try thinking about it recursively, which involves the minimum amount of work and determining when no work is required.</p>
<h3 id="heading-minimum-amount-of-work">Minimum amount of work</h3>
<p>Check if the first and last letters are the same, and if they are, remove the first and last letters from the word.</p>
<h3 id="heading-no-work-required">No work required</h3>
<p>When there is one letter or no letters left at all, we can simply say it is a palindrome.</p>
<p>Now, let's see how the code looks:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># check palindrome</span>
def check_palindrome(text):

    <span class="hljs-comment"># stopping condition</span>
    <span class="hljs-comment"># if the size of text is 1 or 0 return true</span>
    <span class="hljs-keyword">if</span> len(text) == 0 or len(text) == 1:
        <span class="hljs-built_in">return</span> True

    <span class="hljs-comment"># least amount of work</span>
    <span class="hljs-comment"># check if first and last char are the same</span>
    <span class="hljs-comment"># if same remove first and last char from string</span>
    <span class="hljs-keyword">if</span>(text[0]==text[-1]):
        <span class="hljs-built_in">return</span>(check_palindrome(text[1:-1]))

    <span class="hljs-built_in">return</span> False

<span class="hljs-comment"># check if string is palindrome</span>
text = <span class="hljs-string">"racecar"</span>
is_palindrome = check_palindrome(text)
<span class="hljs-built_in">print</span>(is_palindrome)
</code></pre>
<p>Here's how the above code works:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/Frame-9.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Check if racecar is a palindrome</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/checkpalindrome.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Check if racecar is a palindrome</em></p>
<h2 id="heading-when-to-use-recursion">When to Use Recursion</h2>
<p>Recursion can appear elegant and simple. But it often requires many steps to solve even simple problems due to the CPU overhead from repeatedly adding methods to the stack. So before using it, make sure you carefully consider whether it's the right solution for your problem.</p>
<p>When code requires multiple loops and looks confusing and messy, recursion can offer a cleaner solution. Its use, however, depends on the specific code and the type of data or data structure involved. For data structures like trees and graphs, recursion can be particularly useful.</p>
<p>Despite its simplicity in appearance, recursion can be hard to understand and may take multiple steps even for simple problems. So again, make sure you think about your particular use case.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>This is just an introduction to recursion. There are many cases where recursion is used, and you might be confused about how everything works. I will cover more advanced examples on recursion in the next article.</p>
<p>By the way, here are the resources that I found simple and useful while learning recursion:</p>
<ul>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=IJDJ0kBx2LM&amp;t=657s">freeCodeCamp video on recursion</a>: I have to give a shout-out to freeCodeCamp for their excellent video on recursion, which inspired much of this article.</p>
</li>
<li><p><a target="_blank" href="https://programiz.pro/course/learn-recursion-with-python">Recursion by Programiz Pro</a>: Another good resource is the Recursion course by Programiz. It's a premium course, so it's not free, but it's thoughtfully designed. Plus, you can actually practice directly on their platform, which makes it well worth it.</p>
</li>
</ul>
<p>No matter where you learn from, don't spend too much time searching for the perfect resource. Just grasp the concepts and start practicing—that's the only way you'll truly learn.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn Linux for Beginners: From Basics to Advanced Techniques [Full Book] ]]>
                </title>
                <description>
                    <![CDATA[ Learning Linux is one of the most valuable skills in the tech industry. It can help you get things done faster and more efficiently. Many of the world's powerful servers and supercomputers run on Linux. While empowering you in your current role, lear... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-linux-for-beginners-book-basic-to-advanced/</link>
                <guid isPermaLink="false">66912d3051ed9fa23c06c654</guid>
                
                    <category>
                        <![CDATA[ Linux ]]>
                    </category>
                
                    <category>
                        <![CDATA[ book ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zaira Hira ]]>
                </dc:creator>
                <pubDate>Fri, 12 Jul 2024 13:18:40 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1720790242560/764782a4-1bf3-45a5-857c-7fe3921bfb08.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Learning Linux is one of the most valuable skills in the tech industry. It can help you get things done faster and more efficiently. Many of the world's powerful servers and supercomputers run on Linux.</p>
<p>While empowering you in your current role, learning Linux can also help you transition into other tech careers like DevOps, Cybersecurity, and Cloud Computing.</p>
<p>In this handbook, you'll learn the basics of the Linux command line, and then transition to more advanced topics like shell scripting and system administration. Whether you are new to Linux or have been using it for years, this book has something for you.</p>
<p>Important Note: All examples in this book are demonstrated in Ubuntu 22.04.2 LTS (Jammy Jellyfish). Most command line tools are more or less the same in other distributions. However, some GUI applications and commands may differ if you are working on another Linux distribution.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-part-1-introduction-to-linux">Part 1: Introduction to Linux</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-11-getting-started-with-linux">1.1. Getting Started with Linux</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-part-2-introduction-to-bash-shell-and-system-commands">Part 2: Introduction to Bash Shell and System Commands</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-21-getting-started-with-the-bash-shell">2.1. Getting Started with the Bash shell</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-22-command-structure">2.2. Command Structure</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-23-bash-commands-and-keyboard-shortcuts">2.3. Bash Commands and Keyboard Shortcuts</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-24-identifying-yourself-the-whoami-command">2.4. Identifying Yourself: The <code>whoami</code> Command</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-part-3-understanding-your-linux-system">Part 3: Understanding Your Linux System</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-31-discovering-your-os-and-specs">3.1. Discovering Your OS and Specs</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-part-4-managing-files-from-the-command-line">Part 4: Managing Files From the Command line</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-41-the-linux-file-system-hierarchy">4.1. The Linux File-system Hierarchy</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-42-navigating-the-linux-file-system">4.2. Navigating the Linux File-system</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-43-managing-files-and-directories">4.3. Managing Files and Directories</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-45-basic-commands-for-viewing-files">4.5. Basic Commands for Viewing Files</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-part-5-the-essentials-of-text-editing-in-linux">Part 5: The Essentials of Text Editing in Linux</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-51-mastering-vim-the-complete-guide">5.1. Mastering Vim: The Complete Guide</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-52-mastering-nano">5.2. Mastering Nano</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-part-6-bash-scripting">Part 6: Bash Scripting</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-61-definition-of-bash-scripting">6.1. Definition of Bash scripting</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-62-advantages-of-bash-scripting">6.2. Advantages of Bash Scripting</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-63-overview-of-bash-shell-and-command-line-interface">6.3. Overview of Bash Shell and Command Line Interface</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-64-how-to-create-and-execute-bash-scripts">6.4. How to Create and Execute Bash scripts</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-65-bash-scripting-basics">6.5. Bash Scripting Basics</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-part-7-managing-software-packages-in-linux">Part 7: Managing Software Packages in Linux</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-71-packages-and-package-management">7.1. Packages and Package Management</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-72-installing-a-package-via-command-line">7.2. Installing a Package via Command Line</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-73-installing-a-package-via-an-advanced-graphical-method-synaptic">7.3. Installing a Package via an Advanced Graphical Method – Synaptic</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-74-installing-downloaded-packages-from-a-website">7.4. Installing downloaded packages from a website</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-part-8-advanced-linux-topics">Part 8: Advanced Linux Topics</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-81-user-management">8.1. User Management</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-82-connecting-to-remote-servers-via-ssh">8.2 Connecting to Remote Servers via SSH</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-83-advanced-log-parsing-and-analysis">8.3. Advanced Log Parsing and Analysis</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-84-managing-linux-processes-via-command-line">8.4. Managing Linux Processes via Command Line</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-85-standard-input-and-output-streams-in-linux">8.5. Standard Input and Output Streams in Linux</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-86-automation-in-linux-automate-tasks-with-cron-jobs">8.6 Automation in Linux – Automate Tasks with Cron Jobs</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-87-linux-networking-basics">8.7. Linux Networking Basics</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-88-linux-troubleshooting-tools-and-techniques">8.8. Linux Troubleshooting: Tools and Techniques</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-89-general-troubleshooting-strategy-for-servers">8.9. General Troubleshooting Strategy for Servers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-810-diagnosing-hardware-problems">8.10 Diagnosing Hardware Problems</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-part-1-introduction-to-linux">Part 1: Introduction to Linux</h2>
<h3 id="heading-11-getting-started-with-linux">1.1. Getting Started with Linux</h3>
<h4 id="heading-what-is-linux">What is Linux?</h4>
<p>Linux is an open-source operating system that is based on the Unix operating system. It was created by Linus Torvalds in 1991.</p>
<p>Open source means that the source code of the operating system is available to the public. This allows anyone to modify the original code, customise it, and distribute the new operating system to potential users.</p>
<h4 id="heading-why-should-you-learn-about-linux">Why should you learn about Linux?</h4>
<p>In today's data center landscape, Linux and Microsoft Windows stand out as the primary contenders, with Linux having a major share.</p>
<p>Here are several compelling reasons to learn Linux:</p>
<ul>
<li><p>Given the prevalence of Linux hosting, there is a high chance that your application will be hosted on Linux. So learning Linux as a developer becomes increasingly valuable.</p>
</li>
<li><p>With cloud computing becoming the norm, chances are high that your cloud instances will rely on Linux.</p>
</li>
<li><p>Linux serves as the foundation for many operating systems for the Internet of Things (IoT) and mobile applications.</p>
</li>
<li><p>In IT, there are many opportunities for those skilled in Linux.</p>
</li>
</ul>
<h4 id="heading-what-does-it-mean-that-linux-is-an-open-source-operating-system">What does it mean that Linux is an open-source operating system?</h4>
<p>First, what is open source? Open source software is software whose source code is freely accessible, allowing anyone to utilize, modify, and distribute it.</p>
<p>Whenever source code is created, it is automatically considered copyrighted, and its distribution is governed by the copyright holder through software licenses.</p>
<p>In contrast to open source, proprietary or closed-source software restricts access to its source code. Only the creators can view, modify, or distribute it.</p>
<p>Linux is primarily open source, which means that its source code is freely available. Anyone can view, modify, and distribute it. Developers from anywhere in the world can contribute to its improvement. This lays the foundation of collaboration which is an important aspect of open source software.</p>
<p>This collaborative approach has led to the widespread adoption of Linux across servers, desktops, embedded systems, and mobile devices.</p>
<p>The most interesting aspect of Linux being open source is that anyone can tailor the operating system to their specific needs without being restricted by proprietary limitations.</p>
<p>Chrome OS used by Chromebooks is based on Linux. Android, that powers many smartphones globally, is also based on Linux.</p>
<p><strong>What is a Linux Kernel?</strong></p>
<p>The kernel is the central component of an operating system that manages the computer and its hardware operations. It handles memory operations and CPU time.</p>
<p>The kernel acts as a bridge between applications and the hardware-level data processing using inter-process communication and system calls.</p>
<p>The kernel loads into memory first when an operating system starts and remains there until the system shuts down. It is responsible for tasks like disk management, task management, and memory management.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719844849011/f4bb226e-f319-4cb5-bfc9-c1a80401123e.png" alt="Linux Kernel Layout showing interaction of kernal with applications and OS" class="image--center mx-auto" width="563" height="393" loading="lazy"></p>
<p>If you are curious about what the Linux kernel looks like, <a target="_blank" href="https://github.com/torvalds/linux">here</a> is the GitHub link.</p>
<h4 id="heading-what-is-a-linux-distribution">What is a Linux distribution?</h4>
<p>By this point, you know that you can re-use the Linux kernel code, modify it, and create a new kernel. You can further combine different utilities and software to create a completely new operating system.</p>
<p>A Linux distribution or distro is a version of the Linux operating system that includes the Linux kernel, system utilities, and other software. Being open source, a Linux distribution is a collaborative effort involving multiple independent open-source development communities.</p>
<p><strong>What does it mean that a distribution is derived?</strong> When you say that a distribution is "derived" from another, the newer distro is built upon the base or foundation of the original distro. This derivation can include using the same package management system (more on this later), kernel version, and sometimes the same configuration tools.</p>
<p>Today, there are thousands of Linux distributions to choose from, offering differing goals and criteria for selecting and supporting the software provided by their distribution.</p>
<p>Distributions vary from one to the other, but they generally have several common characteristics:</p>
<ul>
<li><p>A distribution consists of a Linux kernel.</p>
</li>
<li><p>It supports user space programs.</p>
</li>
<li><p>A distribution may be small and single-purpose or include thousands of open-source programs.</p>
</li>
<li><p>Some means of installing and updating the distribution and its components should be provided.</p>
</li>
</ul>
<p>If you view the <a target="_blank" href="https://upload.wikimedia.org/wikipedia/commons/1/1b/Linux_Distribution_Timeline.svg">Linux Distributions Timeline</a>, you'll see two major distros: Slackware and Debian. Several distributions are derived from them. For example, Ubuntu and Kali are derived from Debian.</p>
<p><strong>What are the advantages of derivation?</strong> There are various advantages of derivation. Derived distributions can leverage the stability, security, and large software repositories of the parent distribution.</p>
<p>When building on an existing foundation, developers can drive their focus and effort entirely on the specialized features of the new distribution. Users of derived distributions can benefit from the documentation, community support, and resources already available for the parent distribution.</p>
<p>Some popular Linux distributions are:</p>
<ol>
<li><p><strong>Ubuntu</strong>: One of the most widely used and popular Linux distributions. It is user-friendly and recommended for beginners. <a target="_blank" href="https://ubuntu.com/">Learn more about Ubuntu here</a>.</p>
</li>
<li><p><strong>Linux Mint</strong>: Based on Ubuntu, Linux Mint provides a user-friendly experience with a focus on multimedia support. <a target="_blank" href="https://linuxmint.com/">Learn more about Linux Mint here</a>.</p>
</li>
<li><p><strong>Arch Linux</strong>: Popular among experienced users, Arch is a lightweight and flexible distribution aimed at users who prefer a DIY approach. <a target="_blank" href="https://www.archlinux.org/">Learn more about Arch Linux here</a>.</p>
</li>
<li><p><strong>Manjaro</strong>: Based on Arch Linux, Manjaro provides a user-friendly experience with pre-installed software and easy system management tools. <a target="_blank" href="https://manjaro.org/">Learn more about Manjaro here</a>.</p>
</li>
<li><p><strong>Kali Linux</strong>: Kali Linux provides a comprehensive suite of security tools and is mostly focused on cybersecurity and hacking. <a target="_blank" href="https://www.kali.org/">Learn more about Kali Linux here</a>.</p>
</li>
</ol>
<h4 id="heading-how-to-install-and-access-linux">How to install and access Linux</h4>
<p>The best way to learn is to apply the concepts as you go. In this section, we'll learn how to install Linux on your machine so you can follow along. You'll also learn how to access Linux on a Windows machine.</p>
<p>I recommend that you follow any one of the methods mentioned in this section to get access to Linux so you may follow along.</p>
<h5 id="heading-install-linux-as-the-primary-os">Install Linux as the primary OS</h5>
<p>Installing Linux as the primary OS is the most efficient way to use Linux, as you can use the full power of your machine.</p>
<p>In this section, you will learn how to install Ubuntu, which is one of the most popular Linux distributions. I have left out other distributions for now, as I want to keep things simple. You can always explore other distributions once you are comfortable with Ubuntu.</p>
<ul>
<li><p><strong>Step 1 – Download the Ubuntu iso:</strong> Go to the official <a target="_blank" href="https://ubuntu.com/download/desktop">website</a> and download the iso file. Make sure to select a stable release that is labeled "LTS". LTS stands for Long Term Support which means you can get free security and maintenance updates for a long time (usually 5 years).</p>
</li>
<li><p><strong>Step 2 – Create a bootable pendrive:</strong> There are a number of softwares that can create a bootable pendrive. I recommend using Rufus, as it is quite easy to use. You can download it from <a target="_blank" href="https://rufus.ie/">here</a>.</p>
</li>
<li><p><strong>Step 3 – Boot from the pendrive:</strong> Once your bootable pendrive is ready, insert it and boot from the pendrive. The boot menu depends on your laptop. You can google the boot menu for your laptop model.</p>
</li>
<li><p><strong>Step 4 – Follow the prompts.</strong> Once, the boot process starts, select <code>try or install ubuntu</code>.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719304227675/5b706f94-7368-47ca-a4d6-d55a0d92eff9.png" alt="Screen prompt to either try or install Ubuntu" class="image--center mx-auto" width="611" height="329" loading="lazy"></p>
<p>  The process will take some time. Once the GUI appears, you can select the language, and keyboard layout and continue. Enter your login and name. Remember the credentials as you will need them to log in to your system and access full privileges. Wait for the installation to complete.</p>
</li>
<li><p><strong>Step 5 – Restart:</strong> Click on restart now and remove the pen drive.</p>
</li>
<li><p><strong>Step 6 – Login:</strong> Login with the credentials you entered earlier.</p>
</li>
</ul>
<p>And there you go! Now you can install apps and customize your desktop.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719304547967/d150c6eb-d04e-47e0-8473-d1a837df45c4.png" alt="Ubuntu 22.04.4 LTS Desktop screen" class="image--center mx-auto" width="1920" height="1080" loading="lazy"></p>
<p>For advanced installation, you can explore the following topics:</p>
<ul>
<li><p>Disk partitioning.</p>
</li>
<li><p>Setting swap memory for enabling hibernation.</p>
</li>
</ul>
<p><strong>Accessing the terminal</strong></p>
<p>An important part of this handbook is learning about the terminal where you'll run all the commands and see the magic happen. You can search for the terminal by pressing the "windows" key and typing "terminal". You can pin the Terminal in the dock where other apps are located for easy access.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719305113272/4dd30c5e-da73-4cd4-86bb-7dcd8cd2084c.png" alt="Search results for &quot;terminal&quot;" class="image--center mx-auto" width="437" height="255" loading="lazy"></p>
<blockquote>
<p>💡 The shortcut for opening the terminal is <code>ctrl+alt+t</code></p>
</blockquote>
<p>You can also open the terminal from inside a folder. Right click where you are and click on "Open in Terminal". This will open the terminal in the same path.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719305289021/284a4a53-2d1a-4eaa-925a-1002a32c1dce.png" alt="Opening the terminal with right click menu" class="image--center mx-auto" width="640" height="414" loading="lazy"></p>
<h5 id="heading-how-to-use-linux-on-a-windows-machine">How to use Linux on a Windows machine</h5>
<p>Sometimes you might need to run both Linux and Windows side by side. Luckily, there are some ways you can get the best of both worlds without getting different computers for each operating system.</p>
<p>In this section, you'll explore a few ways to use Linux on a Windows machine. Some of them are browser-based or cloud-based and do not need any OS installation before using them.</p>
<p><strong>Option 1: "Dual-boot" Linux + Windows</strong> With dual boot, you can install Linux alongside Windows on your computer, allowing you to choose which operating system to use at startup.</p>
<p>This requires partitioning your hard drive and installing Linux on a separate partition. With this approach, you can only use one operating system at a time.</p>
<p><strong>Option 2: Use Windows Subsystem for Linux (WSL)</strong> Windows Subsystem for Linux provides a compatibility layer that lets you run Linux binary executables natively on Windows.</p>
<p>Using WSL has some advantages. The setup for WSL is simple and not time-consuming. It is lightweight compared to VMs where you have to allocate resources from the host machine. You don't need to install any ISO or virtual disc image for Linux machines which tend to be heavy files. You can use Windows and Linux side by side.</p>
<p><strong>How to install WSL2</strong></p>
<p>First, enable the Windows Subsystem for Linux option in settings.</p>
<ul>
<li><p>Go to Start. Search for "Turn Windows features on or off."</p>
</li>
<li><p>Check the option "Windows Subsystem for Linux" if it isn't already.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306102095/84f23bae-faa5-4ece-a9b6-e40f8789a061.png" alt="Checking the option &quot;Windows Subsystem for Linux&quot; in Windows features" class="image--center mx-auto" width="891" height="550" loading="lazy"></p>
</li>
<li><p>Next, open your command prompt and provide the installation commands.</p>
</li>
<li><p>Open Command Prompt as an administrator:</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720451480640/6052c9b4-cf07-47e0-ae89-18c3a2d3e385.png" alt="Running command prompt as an admin by right clicking the app and choosing &quot;run as admin£" class="image--center mx-auto" width="1032" height="846" loading="lazy"></p>
</li>
<li><p>Run the command below:</p>
</li>
</ul>
<pre><code class="lang-markdown">wsl --install
</code></pre>
<p>This is the output:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306131053/b7272031-ddb7-4e04-8d7b-bafc0911da04.png" alt="Downloading progress of Ubuntu" class="image--center mx-auto" width="1099" height="637" loading="lazy"></p>
<p>Note: By default, Ubuntu will be installed.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306144861/a01f95df-1d95-4b79-bff9-08759be0d3dc.png" alt="Ubuntu installed by default using WSL" class="image--center mx-auto" width="1092" height="626" loading="lazy"></p>
<ul>
<li>Once installation is complete, you'll need to reboot your Windows machine. So, restart your Windows machine.</li>
</ul>
<p>After restarting, you might see a window like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306157704/15620fbe-59d1-40da-9cd6-119a1fab0802.png" alt="Window that shows after a restart" class="image--center mx-auto" width="1111" height="647" loading="lazy"></p>
<p>Once installation of Ubuntu is complete, you'll be prompted to enter your username and password.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306167380/5e3058cd-b7a1-45b1-a16d-c23b5a451504.png" alt="User prompted to enter a username and password" class="image--center mx-auto" width="908" height="611" loading="lazy"></p>
<p>And, that's it! You are ready to use Ubuntu.</p>
<p>Launch Ubuntu by searching from the start menu.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306185110/77c17856-08ac-4ec7-9380-5b06f93be095.png" alt="Launching Ubuntu from the start menu" class="image--center mx-auto" width="966" height="846" loading="lazy"></p>
<p>And here we have your Ubuntu instance launched.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306196320/13be3a71-5b40-440c-a6bf-d742e5b5934b.png" alt="Successful installation of Ubuntu using WSL" class="image--center mx-auto" width="1103" height="639" loading="lazy"></p>
<p><strong>Option 3: Use a Virtual Machine (VM)</strong></p>
<p>A virtual machine (VM) is a software emulation of a physical computer system. It allows you to run multiple operating systems and applications on a single physical machine simultaneously.</p>
<p>You can use virtualization software such as Oracle VirtualBox or VMware to create a virtual machine running Linux within your Windows environment. This allows you to run Linux as a guest operating system alongside Windows.</p>
<p>VM software provides options to allocate and manage hardware resources for each VM, including CPU cores, memory, disk space, and network bandwidth. You can adjust these allocations based on the requirements of the guest operating systems and applications.</p>
<p>Here are some of the common options available for virtualization:</p>
<ul>
<li><p><a target="_blank" href="https://www.virtualbox.org/">Oracle virtual box</a></p>
</li>
<li><p><a target="_blank" href="https://multipass.run/">Multipass</a></p>
</li>
<li><p><a target="_blank" href="https://www.vmware.com/content/vmware/vmware-published-sites/us/products/workstation-player.html.html">VMware workstation player</a></p>
</li>
</ul>
<p><strong>Option 4: Use a Browser-based Solution</strong></p>
<p>Browser-based solutions are particularly useful for quick testing, learning, or accessing Linux environments from devices that don't have Linux installed.</p>
<p>You can either use online code editors or web-based terminals to access Linux. Note that you usually don't have full administration privileges in these cases.</p>
<h4 id="heading-online-code-editors"><strong>Online code editors</strong></h4>
<p>Online code editors offer editors with built-in Linux terminals. While their primary purpose is coding, you can also utilize the Linux terminal to execute commands and perform tasks.</p>
<p><a target="_blank" href="https://replit.com/">Replit</a> is an example of an online code editor, where you can write your code and access the Linux shell at the same time.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306257260/d85d5541-b78f-4c8b-99a8-dbd8c097f661.gif" alt="Running scripts and a bash shell in Replit" class="image--center mx-auto" width="1520" height="721" loading="lazy"></p>
<h4 id="heading-web-based-linux-terminals"><strong>Web-based Linux terminals:</strong></h4>
<p>Online Linux terminals allow you to access a Linux command-line interface directly from your browser. These terminals provide a web-based interface to a Linux shell, enabling you to execute commands and work with Linux utilities.</p>
<p>One such example is <a target="_blank" href="https://jslinux.org/">JSLinux</a>. The screenshot below shows a ready-to-use Linux environment:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306276915/ddaabfc3-9a20-43b2-bedc-0af6875d2008.png" alt="Using JSLinux to access Linux terminal" class="image--center mx-auto" width="826" height="765" loading="lazy"></p>
<p><strong>Option 5: Use a Cloud-based Solution</strong></p>
<p>Instead of running Linux directly on your Windows machine, you can consider using cloud-based Linux environments or virtual private servers (VPS) to access and work with Linux remotely.</p>
<p>Services like Amazon EC2, Microsoft Azure, or DigitalOcean provide Linux instances that you can connect to from your Windows computer. Note that some of these services offer free tiers, but they are not usually free in the long run.</p>
<h2 id="heading-part-2-introduction-to-bash-shell-and-system-commands">Part 2: Introduction to Bash Shell and System Commands</h2>
<h3 id="heading-21-getting-started-with-the-bash-shell">2.1. Getting Started with the Bash shell</h3>
<h4 id="heading-introduction-to-the-bash-shell">Introduction to the bash shell</h4>
<p>The Linux command line is provided by a program called the shell. Over the years, the shell program has evolved to cater to various options.</p>
<p>Different users can be configured to use different shells. But, most users prefer to stick with the current default shell. The default shell for many Linux distros is the GNU Bourne-Again Shell (<code>bash</code>). Bash is succeeded by the Bourne shell (<code>sh</code>).</p>
<p>To find out your current shell, open your terminal and enter the following command:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-variable">$SHELL</span>
</code></pre>
<p>Command breakdown:</p>
<ul>
<li><p>The <code>echo</code> command is used to print on the terminal.</p>
</li>
<li><p>The <code>$SHELL</code> is a special variable that holds the name of the current shell.</p>
</li>
</ul>
<p>In my setup, the output is <code>/bin/bash</code>. This means that I am using the bash shell.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># output</span>
<span class="hljs-built_in">echo</span> <span class="hljs-variable">$SHELL</span>
/bin/bash
</code></pre>
<p>Bash is very powerful as it can simplify certain operations that are hard to accomplish efficiently with a GUI (or Graphical User Interface). Remember that most servers do not have a GUI, and it is best to learn to use the powers of a command line interface (CLI).</p>
<p><strong>Terminal vs Shell</strong></p>
<p>The terms "terminal" and "shell" are often used interchangeably, but they refer to different parts of the command-line interface.</p>
<p>The terminal is the interface you use to interact with the shell. The shell is the command interpreter that processes and executes your commands. You'll learn more about shells in Part 6 of the handbook.</p>
<h4 id="heading-what-is-a-prompt">What is a prompt?</h4>
<p>When a shell is used interactively, it displays a <code>$</code> when it is waiting for a command from the user. This is called the shell prompt.</p>
<p><code>[username@host ~]$</code></p>
<p>If the shell is running as <code>root</code> (you'll learn more about the root user later on), the prompt is changed to <code>#</code>.</p>
<p><code>[root@host ~]#</code></p>
<h3 id="heading-22-command-structure">2.2. Command Structure</h3>
<p>A command is a program that performs a specific operation. Once you have access to the shell, you can enter any command after the <code>$</code> sign and see the output on the terminal.</p>
<p>Generally, Linux commands follow this syntax:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">command</span> [options] [arguments]
</code></pre>
<p>Here is the breakdown of the above syntax:</p>
<ul>
<li><p><code>command</code>: This is the name of the command you want to execute. <code>ls</code> (list), <code>cp</code> (copy), and <code>rm</code> (remove) are common Linux commands.</p>
</li>
<li><p><code>[options]</code>: Options, or flags, often preceded by a hyphen (-) or double hyphen (--), modify the behavior of the command. They can change how the command operates. For example, <code>ls -a</code> uses the <code>-a</code> option to display hidden files in the current directory.</p>
</li>
<li><p><code>[arguments]</code>: Arguments are the inputs for the commands that require one. These could be filenames, user names, or other data that the command will act upon. For example, in the command <code>cat access.log</code>, <code>cat</code> is the command and <code>access.log</code> is the input. As a result, the <code>cat</code> command displays the contents of the <code>access.log</code> file.</p>
</li>
</ul>
<p>Options and arguments are not required for all commands. Some commands can be run without any options or arguments, while others might require one or both to function correctly. You can always refer to the command's manual to check the options and arguments it supports.</p>
<p>💡<strong>Tip:</strong> You can view a command's manual using the <code>man</code> command.</p>
<p>You can access the manual page for <code>ls</code> with <code>man ls</code>, and it'll look like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719312523336/5b1232a6-8c0b-4a97-86f0-9f15f2e14ed7.png" alt="5b1232a6-8c0b-4a97-86f0-9f15f2e14ed7" class="image--center mx-auto" width="1890" height="969" loading="lazy"></p>
<p>Manual pages are a great and quick way to access the documentation. I highly recommend going through man pages for the commands that you use the most.</p>
<h3 id="heading-23-bash-commands-and-keyboard-shortcuts">2.3. Bash Commands and Keyboard Shortcuts</h3>
<p>When you are in the terminal, you can speed up your tasks by using shortcuts.</p>
<p>Here are some of the most common terminal shortcuts:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Operation</td><td>Shortcut</td></tr>
</thead>
<tbody>
<tr>
<td>Look for the previous command</td><td>Up Arrow</td></tr>
<tr>
<td>Jump to the beginning of the previous word</td><td>Ctrl+LeftArrow</td></tr>
<tr>
<td>Clear characters from the cursor to the end of the command line</td><td>Ctrl+K</td></tr>
<tr>
<td>Complete commands, file names, and options</td><td>Pressing Tab</td></tr>
<tr>
<td>Jumps to the beginning of the command line</td><td>Ctrl+A</td></tr>
<tr>
<td>Displays the list of previous commands</td><td>history</td></tr>
</tbody>
</table>
</div><h3 id="heading-24-identifying-yourself-the-whoami-command">2.4. Identifying Yourself: The <code>whoami</code> Command</h3>
<p>You can get the username you are logged in with by using the <code>whoami</code> command. This command is useful when you are switching between different users and want to confirm the current user.</p>
<p>Just after the <code>$</code> sign, type <code>whoami</code> and press enter.</p>
<pre><code class="lang-bash">whoami
</code></pre>
<p>This is the output I got.</p>
<pre><code class="lang-bash">zaira@zaira-ThinkPad:~$ whoami
zaira
</code></pre>
<h2 id="heading-part-3-understanding-your-linux-system">Part 3: Understanding Your Linux System</h2>
<h3 id="heading-31-discovering-your-os-and-specs">3.1. Discovering Your OS and Specs</h3>
<h4 id="heading-print-system-information-using-the-uname-command">Print system information using the <code>uname</code> Command</h4>
<p>You can get detailed system information from the <code>uname</code> command.</p>
<p>When you provide the <code>-a</code> option, it prints all the system information.</p>
<pre><code class="lang-bash">uname -a
<span class="hljs-comment"># output</span>
Linux zaira 6.5.0-21-generic <span class="hljs-comment">#21~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Fri Feb  9 13:32:52 UTC 2 x86_64 x86_64 x86_64 GNU/Linux</span>
</code></pre>
<p>In the output above,</p>
<ul>
<li><p><code>Linux</code>: Indicates the operating system.</p>
</li>
<li><p><code>zaira</code>: Represents the hostname of the machine.</p>
</li>
<li><p><code>6.5.0-21-generic #21~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Fri Feb 9 13:32:52 UTC 2</code>: Provides information about the kernel version, build date, and some additional details.</p>
</li>
<li><p><code>x86_64 x86_64 x86_64</code>: Indicates the architecture of the system.</p>
</li>
<li><p><code>GNU/Linux</code>: Represents the operating system type.</p>
</li>
</ul>
<h4 id="heading-find-details-of-the-cpu-architecture-using-the-lscpu-command">Find details of the CPU architecture using the <code>lscpu</code> Command</h4>
<p>The <code>lscpu</code> command in Linux is used to display information about the CPU architecture. When you run <code>lscpu</code> in the terminal, it provides details such as:</p>
<ul>
<li><p>The architecture of the CPU (for example, x86_64)</p>
</li>
<li><p>CPU op-mode(s) (for example, 32-bit, 64-bit)</p>
</li>
<li><p>Byte Order (for example, Little Endian)</p>
</li>
<li><p>CPU(s) (number of CPUs), and so on</p>
<p>  Let's try it out:</p>
</li>
</ul>
<pre><code class="lang-bash">lscpu
<span class="hljs-comment"># output</span>
Architecture:            x86_64
  CPU op-mode(s):        32-bit, 64-bit
  Address sizes:         48 bits physical, 48 bits virtual
  Byte Order:            Little Endian
CPU(s):                  12
  On-line CPU(s) list:   0-11
Vendor ID:               AuthenticAMD
  Model name:            AMD Ryzen 5 5500U with Radeon Graphics
    Thread(s) per core:  2
    Core(s) per socket:  6
    Socket(s):           1
    Stepping:            1
    CPU max MHz:         4056.0000
    CPU min MHz:         400.0000
</code></pre>
<p>That was a whole lot of information, but useful too! Remember you can always skim the relevant information using specific flags. See the command manual with <code>man lscpu</code>.</p>
<h2 id="heading-part-4-managing-files-from-the-command-line">Part 4: Managing Files From the Command line</h2>
<h3 id="heading-41-the-linux-file-system-hierarchy">4.1. The Linux File-system Hierarchy</h3>
<p>All files in Linux are stored in a file-system. It follows an inverted-tree-like structure because the root is at the topmost part.</p>
<p>The <code>/</code> is the root directory and the starting point of the file system. The root directory contains all other directories and files on the system. The <code>/</code> character also serves as a directory separator between path names. For example, <code>/home/alice</code> forms a complete path.</p>
<p>The image below shows the complete file system hierarchy. Each directory servers a specific purpose.</p>
<p>Note that this is not an exhaustive list and different distributions may have different configurations.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719322457140/02fdbf2c-f4fa-438b-af2f-c23f59f9ddf4.png" alt="Linux file system hierarchy" class="image--center mx-auto" width="1455" height="474" loading="lazy"></p>
<p>Here is a table that shows the purpose of each directory:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Location</td><td>Purpose</td></tr>
</thead>
<tbody>
<tr>
<td>/bin</td><td>Essential command binaries</td></tr>
<tr>
<td>/boot</td><td>Static files of the boot loader, needed in order to start the boot process.</td></tr>
<tr>
<td>/etc</td><td>Host-specific system configuration</td></tr>
<tr>
<td>/home</td><td>User home directories</td></tr>
<tr>
<td>/root</td><td>Home directory for the administrative root user</td></tr>
<tr>
<td>/lib</td><td>Essential shared libraries and kernel modules</td></tr>
<tr>
<td>/mnt</td><td>Mount point for mounting a filesystem temporarily</td></tr>
<tr>
<td>/opt</td><td>Add-on application software packages</td></tr>
<tr>
<td>/usr</td><td>Installed software and shared libraries</td></tr>
<tr>
<td>/var</td><td>Variable data that is also persistent between boots</td></tr>
<tr>
<td>/tmp</td><td>Temporary files that are accessible to all users</td></tr>
</tbody>
</table>
</div><p>💡 <strong>Tip:</strong> You can learn more about the file system using the <code>man hier</code> command.</p>
<p>You can check your file system using the <code>tree -d -L 1</code> command. You can modify the <code>-L</code> flag to change the depth of the tree.</p>
<pre><code class="lang-bash">tree -d -L 1
<span class="hljs-comment"># output</span>
.
├── bin -&gt; usr/bin
├── boot
├── cdrom
├── data
├── dev
├── etc
├── home
├── lib -&gt; usr/lib
├── lib32 -&gt; usr/lib32
├── lib64 -&gt; usr/lib64
├── libx32 -&gt; usr/libx32
├── lost+found
├── media
├── mnt
├── opt
├── proc
├── root
├── run
├── sbin -&gt; usr/sbin
├── snap
├── srv
├── sys
├── tmp
├── usr
└── var

25 directories
</code></pre>
<p>This list is not exhaustive and different distributions and systems may be configured differently.</p>
<h3 id="heading-42-navigating-the-linux-file-system">4.2. Navigating the Linux File-system</h3>
<h4 id="heading-absolute-path-vs-relative-path">Absolute path vs relative path</h4>
<p>The absolute path is the full path from the root directory to the file or directory. It always starts with a <code>/</code>. For example, <code>/home/john/documents</code>.</p>
<p>The relative path, on the other hand, is the path from the current directory to the destination file or directory. It does not start with a <code>/</code>. For example, <code>documents/work/project</code>.</p>
<h4 id="heading-locating-your-current-directory-using-the-pwd-command">Locating your current directory using the <code>pwd</code> command</h4>
<p>It is easy to lose your way in the Linux file system, especially if you are new to the command line. You can locate your current directory using the <code>pwd</code> command.</p>
<p>Here is an example:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">pwd</span>
<span class="hljs-comment"># output</span>
/home/zaira/scripts/python/free-mem.py
</code></pre>
<h4 id="heading-changing-directories-using-the-cd-command">Changing directories using the <code>cd</code> command</h4>
<p>The command to change directories is <code>cd</code> and it stands for "change directory". You can use the <code>cd</code> command to navigate to a different directory.</p>
<p>You can use a relative path or an absolute path.</p>
<p>For example, if you want to navigate the below file structure (following the red lines):</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719389950079/640cce46-6c52-4f38-9787-581747fb9798.png" alt="Example file structure" class="image--center mx-auto" width="327" height="253" loading="lazy"></p>
<p>and you are standing at "home", the command would be like this:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> home/bob/documents/work/project
</code></pre>
<p>Some other commonly used <code>cd</code> shortcuts are:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Command</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>cd ..</code></td><td>Go back one directory</td></tr>
<tr>
<td><code>cd ../..</code></td><td>Go back two directories</td></tr>
<tr>
<td><code>cd</code> or <code>cd ~</code></td><td>Go to the home directory</td></tr>
<tr>
<td><code>cd -</code></td><td>Go to the previous path</td></tr>
</tbody>
</table>
</div><h3 id="heading-43-managing-files-and-directories">4.3. Managing Files and Directories</h3>
<p>When working with files and directories, you might want to copy, move, remove, and create new files and directories. Here are some commands that can help you with that.</p>
<p>💡<strong>Tip:</strong> You can differentiate between a file and folder by looking at the first letter in the output of <code>ls -l</code>. A<code>'-'</code> represents a file and a <code>'d'</code> represents a folder.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719390306244/4f1688cd-ded5-43fe-b13a-9ca44ac7c4ad.png" alt="&quot;d&quot; represents a folder" class="image--center mx-auto" width="766" height="226" loading="lazy"></p>
<h4 id="heading-creating-new-directories-using-the-mkdir-command">Creating new directories using the <code>mkdir</code> command</h4>
<p>You can create an empty directory using the <code>mkdir</code> command.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># creates an empty directory named "foo" in the current folder</span>
mkdir foo
</code></pre>
<p>You can also create directories recursively using the <code>-p</code> option.</p>
<pre><code class="lang-bash">mkdir -p tools/index/helper-scripts
<span class="hljs-comment"># output of tree</span>
.
└── tools
    └── index
        └── helper-scripts

3 directories, 0 files
</code></pre>
<h4 id="heading-creating-new-files-using-the-touch-command">Creating new files using the <code>touch</code> command</h4>
<p>The <code>touch</code> command creates an empty file. You can use it like this:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># creates empty file "file.txt" in the current folder</span>
touch file.txt
</code></pre>
<p>The file names can be chained together if you want to create multiple files in a single command.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># creates empty files "file1.txt", "file2.txt", and "file3.txt" in the current folder</span>

touch file1.txt file2.txt file3.txt
</code></pre>
<h4 id="heading-removing-files-and-directories-using-the-rm-and-rmdir-command">Removing files and directories using the <code>rm</code> and <code>rmdir</code> command</h4>
<p>You can use the <code>rm</code> command to remove both files and non-empty directories.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Command</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>rm file.txt</code></td><td>Removes the file <code>file.txt</code></td></tr>
<tr>
<td><code>rm -r directory</code></td><td>Removes the directory <code>directory</code> and its contents</td></tr>
<tr>
<td><code>rm -f file.txt</code></td><td>Removes the file <code>file.txt</code> without prompting for confirmation</td></tr>
<tr>
<td><code>rmdir</code> directory</td><td>Removes an empty directory</td></tr>
</tbody>
</table>
</div><p>🛑 Note that you should use the <code>-f</code> flag with caution as you won't be asked before deleting a file. Also, be careful when running <code>rm</code> commands in the <code>root</code> folder as it might result in deleting important system files.</p>
<h4 id="heading-copying-files-using-the-cp-command">Copying files using the <code>cp</code> command</h4>
<p>To copy files in Linux, use the <code>cp</code> command.</p>
<ul>
<li><strong>Syntax to copy files:</strong><code>cp source_file destination_of_file</code></li>
</ul>
<p>This command copies a file named <code>file1.txt</code> to a new file location <code>/home/adam/logs</code>.</p>
<pre><code class="lang-bash">cp file1.txt /home/adam/logs
</code></pre>
<p>The <code>cp</code> command also creates a copy of one file with the provided name.</p>
<p>This command copies a file named <code>file1.txt</code> to another file named <code>file2.txt</code> in the same folder.</p>
<pre><code class="lang-bash">cp file1.txt file2.txt
</code></pre>
<h4 id="heading-moving-and-renaming-files-and-folders-using-the-mv-command">Moving and renaming files and folders using the <code>mv</code> command</h4>
<p>The <code>mv</code> command is used to move files and folders from one directory to the other.</p>
<p><strong>Syntax to move files:</strong><code>mv source_file destination_directory</code></p>
<p><strong>Example:</strong> Move a file named <code>file1.txt</code> to a directory named <code>backup</code>:</p>
<pre><code class="lang-bash">mv file1.txt backup/
</code></pre>
<p>To move a directory and its contents:</p>
<pre><code class="lang-bash">mv dir1/ backup/
</code></pre>
<p>Renaming files and folders in Linux is also done with the <code>mv</code> command.</p>
<p><strong>Syntax to rename files:</strong><code>mv old_name new_name</code></p>
<p><strong>Example:</strong> Rename a file from <code>file1.txt</code> to <code>file2.txt</code>:</p>
<pre><code class="lang-bash">mv file1.txt file2.txt
</code></pre>
<p>Rename a directory from <code>dir1</code> to <code>dir2</code>:</p>
<pre><code class="lang-bash">mv dir1 dir2
</code></pre>
<h3 id="heading-44-locating-files-and-folders-using-the-find-command">4.4. Locating Files and Folders Using the <code>find</code> Command</h3>
<p>The <code>find</code> command lets you efficiently search for files, folders, and character and block devices.</p>
<p>Below is the basic syntax of the <code>find</code> command:</p>
<pre><code class="lang-bash">find /path/ -<span class="hljs-built_in">type</span> f -name file-to-search
</code></pre>
<p>Where,</p>
<ul>
<li><p><code>/path</code> is the path where the file is expected to be found. This is the starting point for searching files. The path can also be<code>/</code>or <code>.</code> which represents the root and current directory, respectively.</p>
</li>
<li><p><code>-type</code> represents the file descriptors. They can be any of the below:<br>  <code>f</code> – <strong>Regular file</strong> such as text files, images, and hidden files.<br>  <code>d</code> – <strong>Directory</strong>. These are the folders under consideration.<br>  <code>l</code> – <strong>Symbolic link</strong>. Symbolic links point to files and are similar to shortcuts.<br>  <code>c</code> – <strong>Character devices</strong>. Files that are used to access character devices are called character device files. Drivers communicate with character devices by sending and receiving single characters (bytes, octets). Examples include keyboards, sound cards, and the mouse.<br>  <code>b</code> – <strong>Block devices</strong>. Files that are used to access block devices are called block device files. Drivers communicate with block devices by sending and receiving entire blocks of data. Examples include USB and CD-ROM</p>
</li>
<li><p><code>-name</code> is the name of the file type that you want to search.</p>
</li>
</ul>
<h4 id="heading-how-to-search-files-by-name-or-extension">How to search files by name or extension</h4>
<p>Suppose we need to find files that contain "style" in their name. We'll use this command:</p>
<pre><code class="lang-bash">find . -<span class="hljs-built_in">type</span> f -name <span class="hljs-string">"style*"</span>
<span class="hljs-comment">#output</span>
./style.css
./styles.css
</code></pre>
<p>Now let's say we want to find files with a particular extension like <code>.html</code>. We'll modify the command like this:</p>
<pre><code class="lang-bash">find . -<span class="hljs-built_in">type</span> f -name <span class="hljs-string">"*.html"</span>
<span class="hljs-comment"># output</span>
./services.html
./blob.html
./index.html
</code></pre>
<h4 id="heading-how-to-search-hidden-files">How to search hidden files</h4>
<p>A dot at the beginning of the filename represents hidden files. They are normally hidden but can be viewed with <code>ls -a</code> in the current directory.</p>
<p>We can modify the <code>find</code> command as shown below to search for hidden files:</p>
<pre><code class="lang-bash">find . -<span class="hljs-built_in">type</span> f -name <span class="hljs-string">".*"</span>
</code></pre>
<p><strong>List and find hidden files</strong></p>
<pre><code class="lang-bash">ls -la
<span class="hljs-comment"># folder contents</span>
total 5
drwxrwxr-x  2 zaira zaira 4096 Mar 26 14:17 .
drwxr-x--- 61 zaira zaira 4096 Mar 26 14:12 ..
-rw-rw-r--  1 zaira zaira    0 Mar 26 14:17 .bash_history
-rw-rw-r--  1 zaira zaira    0 Mar 26 14:17 .bash_logout
-rw-rw-r--  1 zaira zaira    0 Mar 26 14:17 .bashrc

find . -<span class="hljs-built_in">type</span> f -name <span class="hljs-string">".*"</span>
<span class="hljs-comment"># find output</span>
./.bash_logout
./.bashrc
./.bash_history
</code></pre>
<p>Above you can see a list of hidden files in my home directory.</p>
<h4 id="heading-how-to-search-log-files-and-configuration-files">How to search log files and configuration files</h4>
<p>Log files usually have the extension <code>.log</code>, and we can find them like this:</p>
<pre><code class="lang-bash"> find . -<span class="hljs-built_in">type</span> f -name <span class="hljs-string">"*.log"</span>
</code></pre>
<p>Similarly, we can search for configuration files like this:</p>
<pre><code class="lang-bash"> find . -<span class="hljs-built_in">type</span> f -name <span class="hljs-string">"*.conf"</span>
</code></pre>
<h4 id="heading-how-to-search-other-files-by-type">How to search other files by type</h4>
<p>We can search for character block files by providing <code>c</code> to <code>-type</code>:</p>
<pre><code class="lang-bash">find / -<span class="hljs-built_in">type</span> c
</code></pre>
<p>Similarly, we can find device block files by using <code>b</code>:</p>
<pre><code class="lang-bash">find / -<span class="hljs-built_in">type</span> b
</code></pre>
<h4 id="heading-how-to-search-directories">How to search directories</h4>
<p>In the example below, we are finding the folders using the <code>-type d</code> flag.</p>
<pre><code class="lang-bash">ls -l
<span class="hljs-comment"># list folder contents</span>
drwxrwxr-x 2 zaira zaira 4096 Mar 26 14:22 hosts
-rw-rw-r-- 1 zaira zaira    0 Mar 26 14:23 hosts.txt
drwxrwxr-x 2 zaira zaira 4096 Mar 26 14:22 images
drwxrwxr-x 2 zaira zaira 4096 Mar 26 14:23 style
drwxrwxr-x 2 zaira zaira 4096 Mar 26 14:22 webp 

find . -<span class="hljs-built_in">type</span> d 
<span class="hljs-comment"># find directory output</span>
.
./webp
./images
./style
./hosts
</code></pre>
<h4 id="heading-how-to-search-files-by-size">How to search files by size</h4>
<p>An incredibly helpful use of the <code>find</code> command is to list files based on a particular size.</p>
<pre><code class="lang-bash">find / -size +250M
</code></pre>
<p>Here, we are listing files whose size exceeds <code>250MB</code>.</p>
<p>Other units include:</p>
<ul>
<li><p><code>G</code>: GigaBytes.</p>
</li>
<li><p><code>M</code>: MegaBytes.</p>
</li>
<li><p><code>K</code>: KiloBytes</p>
</li>
<li><p><code>c</code> : bytes.</p>
</li>
</ul>
<p>Just replace with the relevant unit.</p>
<pre><code class="lang-bash">find &lt;directory&gt; -<span class="hljs-built_in">type</span> f -size +N&lt;Unit Type&gt;
</code></pre>
<h4 id="heading-how-to-search-files-by-modification-time">How to search files by modification time</h4>
<p>By using the <code>-mtime</code> flag, you can filter files and folders based on the modification time.</p>
<pre><code class="lang-bash">find /path -name <span class="hljs-string">"*.txt"</span> -mtime -10
</code></pre>
<p>For example,</p>
<ul>
<li><p><strong>-mtime +10</strong> means you are looking for a file modified 10 days ago.</p>
</li>
<li><p><strong>-mtime -10</strong> means less than 10 days.</p>
</li>
<li><p><strong>-mtime 10</strong> If you skip + or – it means exactly 10 days.</p>
</li>
</ul>
<h3 id="heading-45-basic-commands-for-viewing-files">4.5. Basic Commands for Viewing Files</h3>
<h4 id="heading-concatenate-and-display-files-using-the-cat-command">Concatenate and display files using the <code>cat</code> command</h4>
<p>The <code>cat</code> command in Linux is used to display the contents of a file. It can also be used to concatenate files and create new files.</p>
<p>Here is the basic syntax of the <code>cat</code> command:</p>
<pre><code class="lang-bash">cat [options] [file]
</code></pre>
<p>The simplest way to use <code>cat</code> is without any options or arguments. This will display the contents of the file on the terminal.</p>
<p>For example, if you want to view the contents of a file named <code>file.txt</code>, you can use the following command:</p>
<pre><code class="lang-bash">cat file.txt
</code></pre>
<p>This will display all the contents of the file on the terminal at once.</p>
<h4 id="heading-viewing-text-files-interactively-using-less-and-more">Viewing text files interactively using <code>less</code> and <code>more</code></h4>
<p>While <code>cat</code> displays the entire file at once, <code>less</code> and <code>more</code> allow you to view the contents of a file interactively. This is useful when you want to scroll through a large file or search for specific content.</p>
<p>The syntax of the <code>less</code> command is:</p>
<pre><code class="lang-bash">less [options] [file]
</code></pre>
<p>The <code>more</code> command is similar to <code>less</code> but has fewer features. It is used to display the contents of a file one screen at a time.</p>
<p>The syntax of the <code>more</code> command is:</p>
<pre><code class="lang-bash">more [options] [file]
</code></pre>
<p>For both commands, you can use the <code>spacebar</code> to scroll one page down, the <code>Enter</code> key to scroll one line down, and the <code>q</code> key to exit the viewer.</p>
<p>To move backward you can use the <code>b</code> key, and to move forward you can use the <code>f</code> key.</p>
<h4 id="heading-displaying-the-last-part-of-files-using-tail">Displaying the last part of files using <code>tail</code></h4>
<p>Sometimes you might need to view just the last few lines of a file instead of the entire file. The <code>tail</code> command in Linux is used to display the last part of a file.</p>
<p>For example, <code>tail file.txt</code> will display the last 10 lines of the file <code>file.txt</code> by default.</p>
<p>If you want to display a different number of lines, you can use the <code>-n</code> option followed by the number of lines you want to display.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Display the last 50 lines of the file file.txt</span>
tail -n 50 file.txt
</code></pre>
<p>💡<strong>Tip:</strong> Another usage of the <code>tail</code> is its follow-along (<code>-f</code>) option. This option enables you to view the contents of a file as they are being written. This is a useful utility for viewing and monitoring log files in real-time.</p>
<h4 id="heading-displaying-the-beginning-of-files-using-head">Displaying the beginning of files using <code>head</code></h4>
<p>Just like <code>tail</code> displays the last part of a file, you can use the <code>head</code> command in Linux to display the beginning of a file.</p>
<p>For example, <code>head file.txt</code> will display the first 10 lines of the file <code>file.txt</code> by default.</p>
<p>To change the number of lines displayed, you can use the <code>-n</code> option followed by the number of lines you want to display.</p>
<h4 id="heading-counting-words-lines-and-characters-using-wc">Counting words, lines, and characters using <code>wc</code></h4>
<p>You can count words, lines and characters in a file using the <code>wc</code> command.</p>
<p>For example, running <code>wc syslog.log</code> gave me the following output:</p>
<pre><code class="lang-bash">1669 9623 64367 syslog.log
</code></pre>
<p>In the output above,</p>
<ul>
<li><p><code>1669</code> represents the number of lines in the file <code>syslog.log</code>.</p>
</li>
<li><p><code>9623</code> represents the number of words in the file <code>syslog.log</code>.</p>
</li>
<li><p><code>64367</code> represents the number of characters in the file <code>syslog.log</code>.</p>
</li>
</ul>
<p>So, the command <code>wc syslog.log</code> counted <code>1669</code> lines, <code>9623</code> words, and <code>64367</code> characters in the file <code>syslog.log</code>.</p>
<h4 id="heading-comparing-files-line-by-line-using-diff">Comparing files line by line using <code>diff</code></h4>
<p>Comparing and finding differences between two files is a common task in Linux. You can compare two files right within the command line using the <code>diff</code> command.</p>
<p>The basic syntax of the <code>diff</code> command is:</p>
<pre><code class="lang-bash">diff [options] file1 file2
</code></pre>
<p>Here are two files, <code>hello.py</code> and <code>also-hello.py</code>, that we will compare using the <code>diff</code> command:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># contents of hello.py</span>

def greet(name):
    <span class="hljs-built_in">return</span> f<span class="hljs-string">"Hello, {name}!"</span>

user = input(<span class="hljs-string">"Enter your name: "</span>)
<span class="hljs-built_in">print</span>(greet(user))
</code></pre>
<pre><code class="lang-bash"><span class="hljs-comment"># contents of also-hello.py</span>

more also-hello.py
def greet(name):
    <span class="hljs-built_in">return</span> fHello, {name}!

user = input(Enter your name: )
<span class="hljs-built_in">print</span>(greet(user))
<span class="hljs-built_in">print</span>(<span class="hljs-string">"Nice to meet you"</span>)
</code></pre>
<ol>
<li>Check whether the files are the same or not</li>
</ol>
<pre><code class="lang-bash">diff -q hello.py also-hello.py
<span class="hljs-comment"># Output</span>
Files hello.py and also-hello.py differ
</code></pre>
<ol start="2">
<li>See how the files differ. For that, you can use the <code>-u</code> flag to see a unified output:</li>
</ol>
<pre><code class="lang-bash">diff -u hello.py also-hello.py
--- hello.py    2024-05-24 18:31:29.891690478 +0500
+++ also-hello.py    2024-05-24 18:32:17.207921795 +0500
@@ -3,4 +3,5 @@

 user = input(Enter your name: )
 <span class="hljs-built_in">print</span>(greet(user))
+<span class="hljs-built_in">print</span>(<span class="hljs-string">"Nice to meet you"</span>)
</code></pre>
<p>In the above output:</p>
<ul>
<li><p><code>--- hello.py 2024-05-24 18:31:29.891690478 +0500</code> indicates the file being compared and its timestamp.</p>
</li>
<li><p><code>+++ also-hello.py 2024-05-24 18:32:17.207921795 +0500</code> indicates the other file being compared and its timestamp.</p>
</li>
<li><p><code>@@ -3,4 +3,5 @@</code> shows the line numbers where the changes occur. In this case, it indicates that lines 3 to 4 in the original file have changed to lines 3 to 5 in the modified file.</p>
</li>
<li><p><code>user = input(Enter your name: )</code> is a line from the original file.</p>
</li>
<li><p><code>print(greet(user))</code> is another line from the original file.</p>
</li>
<li><p><code>+print("Nice to meet you")</code> is the additional line in the modified file.</p>
</li>
</ul>
<ol start="3">
<li>To see the diff in a side-by-side format, you can use the <code>-y</code> flag:</li>
</ol>
<pre><code class="lang-bash">diff -y hello.py also-hello.py
<span class="hljs-comment"># Output</span>
def greet(name):                        def greet(name):
    <span class="hljs-built_in">return</span> fHello, {name}!                        <span class="hljs-built_in">return</span> fHello, {name}!

user = input(Enter your name: )                    user = input(Enter your name: )
<span class="hljs-built_in">print</span>(greet(user))                        <span class="hljs-built_in">print</span>(greet(user))
                                        &gt;    <span class="hljs-built_in">print</span>(<span class="hljs-string">"Nice to meet you"</span>)
</code></pre>
<p>In the output:</p>
<ul>
<li><p>The lines that are the same in both files are displayed side by side.</p>
</li>
<li><p>Lines that are different are shown with a <code>&gt;</code> symbol indicating the line is only present in one of the files.</p>
</li>
</ul>
<h2 id="heading-part-5-the-essentials-of-text-editing-in-linux">Part 5: The Essentials of Text Editing in Linux</h2>
<p>Text editing skills using the command line are one of the most crucial skills in Linux. In this section, you will learn how to use two popular text editors in Linux: Vim and Nano.</p>
<p>I suggest that you master any one text editor of your choice and stick to it. It will save you time and make you more productive. Vim and nano are safe choices as they are present on most Linux distributions.</p>
<h3 id="heading-51-mastering-vim-the-complete-guide">5.1. Mastering Vim: The Complete Guide</h3>
<h4 id="heading-introduction-to-vim">Introduction to Vim</h4>
<p>Vim is a popular text editing tool for the command line. Vim comes with its advantages: it is powerful, customizable, and fast. Here are some reasons why you should consider learning Vim:</p>
<ul>
<li><p>Most servers are accessed via a CLI, so in system administration, you don't necessarily have the luxury of a GUI. But Vim has got your back – it'll always be there.</p>
</li>
<li><p>Vim uses a keyboard-centric approach, as it is designed to be used without a mouse, which can significantly speed up editing tasks once you have learned the keyboard shortcuts. This also makes it faster than GUI tools.</p>
</li>
<li><p>Some Linux utilities, for example editing cron jobs, work in the same editing format as Vim.</p>
</li>
<li><p>Vim is suitable for all – beginners and advanced users. Vim supports complex string searches, highlighting searches, and much more. Through plugins, Vim provides extended capabilities to developers and system admins that includes code completion, syntax highlighting, file management, version control, and more.</p>
</li>
</ul>
<p>Vim has two variations: Vim (<code>vim</code>) and Vim tiny (<code>vi</code>). Vim tiny is a smaller version of Vim that lacks some features of Vim.</p>
<h4 id="heading-how-to-start-using-vim">How to start using <code>vim</code></h4>
<p>Start using Vim with this command:</p>
<pre><code class="lang-bash">vim your-file.txt
</code></pre>
<p><code>your-file.txt</code> can either be a new file or an existing file that you want to edit.</p>
<h4 id="heading-navigating-vim-mastering-movement-and-command-modes">Navigating Vim: Mastering movement and command modes</h4>
<p>In the early days of the CLI, the keyboards didn't have arrow keys. Hence, navigation was done using the set of available keys, <code>hjkl</code> being one of them.</p>
<p>Being keyboard-centric, using <code>hjkl</code> keys can greatly speed up text editing tasks.</p>
<p>Note: Although arrow keys would work totally fine, you can still experiment with <code>hjkl</code> keys to navigate. Some people find this this way of navigation efficient.</p>
<p>💡<strong>Tip:</strong> To remember the <code>hjkl</code> sequence, use this: <strong>h</strong>ang back, <strong>j</strong>ump down, <strong>k</strong>ick up, <strong>l</strong>eap forward.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719392462442/1a667ede-5f03-4acb-b40f-b10cefc64de3.png" alt="hjkl navigation guide" class="image--center mx-auto" width="471" height="274" loading="lazy"></p>
<h4 id="heading-the-three-vim-modes">The three Vim modes</h4>
<p>You need to know the 3 operating modes of Vim and how to switch between them. Keystrokes behave differently in each command mode. The three modes are as follows:</p>
<ol>
<li><p>Command mode.</p>
</li>
<li><p>Edit mode.</p>
</li>
<li><p>Visual mode.</p>
</li>
</ol>
<p><strong>Command Mode.</strong> When you start Vim, you land in the command mode by default. This mode allows you to access other modes.</p>
<p>⚠ To switch to other modes, you need to be present in the command mode first</p>
<p><strong>Edit Mode</strong></p>
<p>This mode allows you to make changes to the file. To enter edit mode, press <code>I</code> while in command mode. Note the <code>'-- INSERT'</code> switch at the end of the screen.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719392526710/d44cecd7-64be-4c89-9a31-dbf395b77fcb.png" alt="Insert mode in Vim" class="image--center mx-auto" width="433" height="345" loading="lazy"></p>
<p><strong>Visual mode</strong></p>
<p>This mode allows you to work on a single character, a block of text, or lines of text. Let's break it down into simple steps. Remember, use the below combinations when in command mode.</p>
<ul>
<li><p><code>Shift + V</code> → Select multiple lines.</p>
</li>
<li><p><code>Ctrl + V</code> → Block mode</p>
</li>
<li><p><code>V</code> → Character mode</p>
</li>
</ul>
<p>The visual mode comes in handy when you need to copy and paste or edit lines in bulk.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719392557097/b61a1515-cac0-4470-856b-b2c15de581e8.gif" alt="Selectind text using visual mode" class="image--center mx-auto" width="673" height="422" loading="lazy"></p>
<p><strong>Extended command mode.</strong></p>
<p>The extended command mode allows you to perform advanced operations like searching, setting line numbers, and highlighting text. We'll cover extended mode in the next section.</p>
<p>How to stay on track? If you forget your current mode, just press <code>ESC</code> twice and you will be back in Command Mode.</p>
<h4 id="heading-editing-efficiently-in-vim-copypasting-and-searching">Editing Efficiently in Vim: Copy/pasting and searching</h4>
<p><strong>1. How to copy and paste in Vim</strong></p>
<p>Copy-paste is known as 'yank' and 'put' in Linux terms. To copy-paste, follow these steps:</p>
<ul>
<li><p>Select text in visual mode.</p>
</li>
<li><p>Press <code>'y'</code> to copy/ yank.</p>
</li>
<li><p>Move your cursor to the required position and press <code>'p'</code>.</p>
</li>
</ul>
<p><strong>2. How to search for text in Vim</strong></p>
<p>Any series of strings can be searched with Vim using the <code>/</code> in command mode. To search, use <code>/string-to-match</code>.</p>
<p>In the command mode, type <code>:set hls</code> and press <code>enter</code>. Search using <code>/string-to-match</code>. This will highlight the searches.</p>
<p>Let's search a few strings:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719392684097/11c4a45e-0698-4fb7-bef7-f193684ea21a.gif" alt="Highlighting searches in Vim" class="image--center mx-auto" width="800" height="409" loading="lazy"></p>
<p><strong>3. How to exit Vim</strong></p>
<p>First, move to command mode (by pressing escape twice) and then use these flags:</p>
<ul>
<li><p>Exit without saving → <code>:q!</code></p>
</li>
<li><p>Exit and save → <code>:wq!</code></p>
</li>
</ul>
<h4 id="heading-shortcuts-in-vim-making-editing-faster">Shortcuts in Vim: Making Editing Faster</h4>
<p>Note: All these shortcuts work in the command mode only.</p>
<ul>
<li><p><strong>Basic Navigation</strong></p>
<ul>
<li><p><code>h</code>: Move left</p>
</li>
<li><p><code>j</code>: Move down</p>
</li>
<li><p><code>k</code>: Move up</p>
</li>
<li><p><code>l</code>: Move right</p>
</li>
<li><p><code>0</code>: Move to the beginning of the line</p>
</li>
<li><p><code>$</code>: Move to the end of the line</p>
</li>
<li><p><code>gg</code>: Move to the beginning of the file</p>
</li>
<li><p><code>G</code>: Move to the end of the file</p>
</li>
<li><p><code>Ctrl+d</code>: Move half-page down</p>
</li>
<li><p><code>Ctrl+u</code>: Move half-page up</p>
</li>
</ul>
</li>
<li><p><strong>Editing</strong></p>
<ul>
<li><p><code>i</code>: Enter insert mode before the cursor</p>
</li>
<li><p><code>I</code>: Enter insert mode at the beginning of the line</p>
</li>
<li><p><code>a</code>: Enter insert mode after the cursor</p>
</li>
<li><p><code>A</code>: Enter insert mode at the end of the line</p>
</li>
<li><p><code>o</code>: Open a new line below the current line and enter insert mode</p>
</li>
<li><p><code>O</code>: Open a new line above the current line and enter insert mode</p>
</li>
<li><p><code>x</code>: Delete the character under the cursor</p>
</li>
<li><p><code>dd</code>: Delete the current line</p>
</li>
<li><p><code>yy</code>: Yank (copy) the current line (use this in visual mode)</p>
</li>
<li><p><code>p</code>: Paste below the cursor</p>
</li>
<li><p><code>P</code>: Paste above the cursor</p>
</li>
</ul>
</li>
<li><p><strong>Searching and Replacing</strong></p>
<ul>
<li><p><code>/</code>: Search for a pattern which will take you to its next occurrence</p>
</li>
<li><p><code>?</code>: Search for a pattern that will take you to its previous occurrence</p>
</li>
<li><p><code>n</code>: Repeat the last search in the same direction</p>
</li>
<li><p><code>N</code>: Repeat the last search in the opposite direction</p>
</li>
<li><p><code>:%s/old/new/g</code>: Replace all occurrences of <code>old</code> with <code>new</code> in the file</p>
</li>
</ul>
</li>
<li><p><strong>Exiting</strong></p>
<ul>
<li><p><code>:w</code>: Save the file but don't exit</p>
</li>
<li><p><code>:q</code>: Quit Vim (fails if there are unsaved changes)</p>
</li>
<li><p><code>:wq</code> or <code>:x</code>: Save and quit</p>
</li>
<li><p><code>:q!</code>: Quit without saving</p>
</li>
</ul>
</li>
<li><p><strong>Multiple Windows</strong></p>
<ul>
<li><p><code>:split</code> or <code>:sp</code>: Split the window horizontally</p>
</li>
<li><p><code>:vsplit</code> or <code>:vsp</code>: Split the window vertically</p>
</li>
<li><p><code>Ctrl+w followed by h/j/k/l</code>: Navigate between split windows</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-52-mastering-nano">5.2. Mastering Nano</h3>
<h4 id="heading-getting-started-with-nano-the-user-friendly-text-editor">Getting started with Nano: The user-friendly text editor</h4>
<p>Nano is a user-friendly text editor that is easy to use and is perfect for beginners. It is pre-installed on most Linux distributions.</p>
<p>To create a new file using Nano, use the following command:</p>
<pre><code class="lang-bash">nano
</code></pre>
<p>To start editing an existing file with Nano, use the following command:</p>
<pre><code class="lang-bash">nano filename
</code></pre>
<h4 id="heading-list-of-key-bindings-in-nano">List of key bindings in Nano</h4>
<p>Let's study the most important key bindings in Nano. You'll use the key bindings to perform various operations like saving, exiting, copying, pasting, and more.</p>
<p><strong>Write to a file and save</strong></p>
<p>Once you open Nano using the <code>nano</code> command, you can start writing text. To save the file, press <code>Ctrl+O</code>. You'll be prompted to enter the file name. Press <code>Enter</code> to save the file.</p>
<p><strong>Exit nano</strong></p>
<p>You can exit Nano by pressing <code>Ctrl+X</code>. If you have unsaved changes, Nano will prompt you to save the changes before exiting.</p>
<p><strong>Copying and pasting</strong></p>
<p>To select a region, use <code>ALT+A</code>. A marker will show. Use arrows to select the text. Once selected, exit the marker with with <code>ALT+^</code>.</p>
<p>To copy the selected text, press <code>Ctrl+K</code>. To paste the copied text, press <code>Ctrl+U</code>.</p>
<p><strong>Cutting and pasting</strong></p>
<p>Select the region with <code>ALT+A</code>. Once selected, cut the text with <code>Ctrl+K</code>. To paste the cut text, press <code>Ctrl+U</code>.</p>
<p><strong>Navigation</strong></p>
<p>Use <code>Alt \</code> to move to the beginning of the file.</p>
<p>Use <code>Alt /</code> to move to the end of the file.</p>
<p><strong>Viewing line numbers</strong></p>
<p>When you open a file with <code>nano -l filename</code>, you can view line numbers on the left side of the file.</p>
<p><strong>Searching</strong></p>
<p>You can search for a specific line number with <code>ALt + G</code>. Enter the line number to the prompt and press <code>Enter</code>.</p>
<p>You can also initiate search for a string with <code>CTRL + W</code> and press Enter. If you want to search backwards, you can press <code>Alt+W</code> after initiating the search with <code>Ctrl+W</code>.</p>
<h4 id="heading-summary-of-keybindings-in-nano">Summary of keybindings in Nano</h4>
<ul>
<li><p><strong>General</strong></p>
<ul>
<li><p><code>Ctrl+X</code>: Exit Nano (prompting to save if changes are made)</p>
</li>
<li><p><code>Ctrl+O</code>: Save the file</p>
</li>
<li><p><code>Ctrl+R</code>: Read a file into the current file</p>
</li>
<li><p><code>Ctrl+G</code>: Display the help text</p>
</li>
</ul>
</li>
<li><p><strong>Editing</strong></p>
<ul>
<li><p><code>Ctrl+K</code>: Cut the current line and store it in the cutbuffer</p>
</li>
<li><p><code>Ctrl+U</code>: Paste the contents of the cutbuffer into the current line</p>
</li>
<li><p><code>Alt+6</code>: Copy the current line and store it in the cutbuffer</p>
</li>
<li><p><code>Ctrl+J</code>: Justify the current paragraph</p>
</li>
</ul>
</li>
<li><p><strong>Navigation</strong></p>
<ul>
<li><p><code>Ctrl+A</code>: Move to the beginning of the line</p>
</li>
<li><p><code>Ctrl+E</code>: Move to the end of the line</p>
</li>
<li><p><code>Ctrl+C</code>: Display the current line number and file information</p>
</li>
<li><p><code>Ctrl+_</code> (<code>Ctrl+Shift+-</code>): Go to a specific line (and optionally, column) number</p>
</li>
<li><p><code>Ctrl+Y</code>: Scroll up one page</p>
</li>
<li><p><code>Ctrl+V</code>: Scroll down one page</p>
</li>
</ul>
</li>
<li><p><strong>Search and Replace</strong></p>
<ul>
<li><p><code>Ctrl+W</code>: Search for a string (then <code>Enter</code> to search again)</p>
</li>
<li><p><code>Alt+W</code>: Repeat the last search but in the opposite direction</p>
</li>
<li><p><code>Ctrl+\</code>: Search and replace</p>
</li>
</ul>
</li>
<li><p><strong>Miscellaneous</strong></p>
<ul>
<li><p><code>Ctrl+T</code>: Invoke the spell checker, if available</p>
</li>
<li><p><code>Ctrl+D</code>: Delete the character under the cursor (does not cut it)</p>
</li>
<li><p><code>Ctrl+L</code>: Refresh (redraw) the current screen</p>
</li>
<li><p><code>Alt+U</code>: Undo the last operation</p>
</li>
<li><p><code>Alt+E</code>: Redo the last undone operation</p>
</li>
</ul>
</li>
</ul>
<h2 id="heading-part-6-bash-scripting">Part 6: Bash Scripting</h2>
<h3 id="heading-61-definition-of-bash-scripting">6.1. Definition of Bash scripting</h3>
<p>A bash script is a file containing a sequence of commands that are executed by the bash program line by line. It allows you to perform a series of actions, such as navigating to a specific directory, creating a folder, and launching a process using the command line.</p>
<p>By saving commands in a script, you can repeat the same sequence of steps multiple times and execute them by running the script.</p>
<h3 id="heading-62-advantages-of-bash-scripting">6.2. Advantages of Bash Scripting</h3>
<p>Bash scripting is a powerful and versatile tool for automating system administration tasks, managing system resources, and performing other routine tasks in Unix/Linux systems.</p>
<p>Some advantages of shell scripting are:</p>
<ul>
<li><p><strong>Automation</strong>: Shell scripts allow you to automate repetitive tasks and processes, saving time and reducing the risk of errors that can occur with manual execution.</p>
</li>
<li><p><strong>Portability</strong>: Shell scripts can be run on various platforms and operating systems, including Unix, Linux, macOS, and even Windows through the use of emulators or virtual machines.</p>
</li>
<li><p><strong>Flexibility</strong>: Shell scripts are highly customizable and can be easily modified to suit specific requirements. They can also be combined with other programming languages or utilities to create more powerful scripts.</p>
</li>
<li><p><strong>Accessibility</strong>: Shell scripts are easy to write and don't require any special tools or software. They can be edited using any text editor, and most operating systems have a built-in shell interpreter.</p>
</li>
<li><p><strong>Integration</strong>: Shell scripts can be integrated with other tools and applications, such as databases, web servers, and cloud services, allowing for more complex automation and system management tasks.</p>
</li>
<li><p><strong>Debugging</strong>: Shell scripts are easy to debug, and most shells have built-in debugging and error-reporting tools that can help identify and fix issues quickly.</p>
</li>
</ul>
<h3 id="heading-63-overview-of-bash-shell-and-command-line-interface">6.3. Overview of Bash Shell and Command Line Interface</h3>
<p>The terms "shell" and "bash" are often used interchangeably. But there is a subtle difference between the two.</p>
<p>The term "shell" refers to a program that provides a command-line interface for interacting with an operating system. Bash (Bourne-Again SHell) is one of the most commonly used Unix/Linux shells and is the default shell in many Linux distributions.</p>
<p>Till now, the commands that you have been entering were basically being entered in a "shell".</p>
<p>Although Bash is a type of shell, there are other shells available as well, such as Korn shell (ksh), C shell (csh), and Z shell (zsh). Each shell has its own syntax and set of features, but they all share the common purpose of providing a command-line interface for interacting with the operating system.</p>
<p>You can determine your shell type using the <code>ps</code> command:</p>
<pre><code class="lang-markdown">ps
<span class="hljs-section"># output:</span>

<span class="hljs-code">    PID TTY          TIME CMD
  20506 pts/0    00:00:00 bash &lt;--- the shell type
  20931 pts/0    00:00:00 ps</span>
</code></pre>
<p>In summary, while "shell" is a broad term that refers to any program that provides a command-line interface, "Bash" is a specific type of shell that is widely used in Unix/Linux systems.</p>
<p>Note: In this section, we will be using the "bash" shell.</p>
<h3 id="heading-64-how-to-create-and-execute-bash-scripts">6.4. How to Create and Execute Bash scripts</h3>
<p><strong>Script naming conventions</strong></p>
<p>By naming convention, bash scripts end with <code>.sh</code>. However, bash scripts can run perfectly fine without the <code>sh</code> extension.</p>
<p><strong>Adding the Shebang</strong></p>
<p>Bash scripts start with a <code>shebang</code>. Shebang is a combination of <code>bash #</code> and <code>bang !</code> followed by the bash shell path. This is the first line of the script. Shebang tells the shell to execute it via bash shell. Shebang is simply an absolute path to the bash interpreter.</p>
<p>Below is an example of the shebang statement.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>
</code></pre>
<p>You can find your bash shell path (which may vary from the above) using the command:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">which</span> bash
</code></pre>
<p><strong>Creating your first bash script</strong></p>
<p>Our first script prompts the user to enter a path. In return, its contents will be listed.</p>
<p>Create a file named <code>run_all.sh</code> using any editor of your choice.</p>
<pre><code class="lang-bash">vim run_all.sh
</code></pre>
<p>Add the following commands in your file and save it:</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>
<span class="hljs-built_in">echo</span> <span class="hljs-string">"Today is "</span> `date`

<span class="hljs-built_in">echo</span> -e <span class="hljs-string">"\nenter the path to directory"</span>
<span class="hljs-built_in">read</span> the_path

<span class="hljs-built_in">echo</span> -e <span class="hljs-string">"\n you path has the following files and folders: "</span>
ls <span class="hljs-variable">$the_path</span>
</code></pre>
<p>Let's take a deeper look at the script line by line. I am displaying the same script again, but this time with line numbers.</p>
<pre><code class="lang-bash">  1 <span class="hljs-comment">#!/bin/bash</span>
  2 <span class="hljs-built_in">echo</span> <span class="hljs-string">"Today is "</span> `date`
  3
  4 <span class="hljs-built_in">echo</span> -e <span class="hljs-string">"\nenter the path to directory"</span>
  5 <span class="hljs-built_in">read</span> the_path
  6
  7 <span class="hljs-built_in">echo</span> -e <span class="hljs-string">"\n you path has the following files and folders: "</span>
  8 ls <span class="hljs-variable">$the_path</span>
</code></pre>
<ul>
<li><p>Line #1: The shebang (<code>#!/bin/bash</code>) points toward the bash shell path.</p>
</li>
<li><p>Line #2: The <code>echo</code> command displays the current date and time on the terminal. Note that the <code>date</code> is in backticks.</p>
</li>
<li><p>Line #4: We want the user to enter a valid path.</p>
</li>
<li><p>Line #5: The <code>read</code> command reads the input and stores it in the variable <code>the_path</code>.</p>
</li>
<li><p>line #8: The <code>ls</code> command takes the variable with the stored path and displays the current files and folders.</p>
</li>
</ul>
<p><strong>Executing the bash script</strong></p>
<p>To make the script executable, assign execution rights to your user using this command:</p>
<pre><code class="lang-bash">chmod u+x run_all.sh
</code></pre>
<p>Here,</p>
<ul>
<li><p><code>chmod</code> modifies the ownership of a file for the current user :<code>u</code>.</p>
</li>
<li><p><code>+x</code> adds the execution rights to the current user. This means that the user who is the owner can now run the script.</p>
</li>
<li><p><code>run_all.sh</code> is the file we wish to run.</p>
</li>
</ul>
<p>You can run the script using any of the mentioned methods:</p>
<ul>
<li><p><code>sh run_all.sh</code></p>
</li>
<li><p><code>bash run_all.sh</code></p>
</li>
<li><p><code>./run_all.sh</code></p>
</li>
</ul>
<p>Let's see it running in action 🚀</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/run-script-bash-2.gif" alt="Running a bash script" width="600" height="400" loading="lazy"></p>
<h3 id="heading-65-bash-scripting-basics">6.5. Bash Scripting Basics</h3>
<h4 id="heading-comments-in-bash-scripting">Comments in bash scripting</h4>
<p>Comments start with a <code>#</code> in bash scripting. This means that any line that begins with a <code>#</code> is a comment and will be ignored by the interpreter.</p>
<p>Comments are very helpful in documenting the code, and it is a good practice to add them to help others understand the code.</p>
<p>These are examples of comments:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># This is an example comment</span>
<span class="hljs-comment"># Both of these lines will be ignored by the interpreter</span>
</code></pre>
<h4 id="heading-variables-and-data-types-in-bash">Variables and data types in Bash</h4>
<p>Variables let you store data. You can use variables to read, access, and manipulate data throughout your script.</p>
<p>There are no data types in Bash. In Bash, a variable is capable of storing numeric values, individual characters, or strings of characters.</p>
<p>In Bash, you can use and set the variable values in the following ways:</p>
<ol>
<li>Assign the value directly:</li>
</ol>
<pre><code class="lang-bash">country=Netherlands
</code></pre>
<p>2.  Assign the value based on the output obtained from a program or command, using command substitution. Note that <code>$</code> is required to access an existing variable's value.</p>
<pre><code class="lang-bash">same_country=<span class="hljs-variable">$country</span>
</code></pre>
<p>This assigns the value of <code>country</code> to the new variable <code>same_country</code>.</p>
<p>To access the variable value, append <code>$</code> to the variable name.</p>
<pre><code class="lang-bash">country=Netherlands
<span class="hljs-built_in">echo</span> <span class="hljs-variable">$country</span>
<span class="hljs-comment"># output</span>
Netherlands
new_country=<span class="hljs-variable">$country</span>
<span class="hljs-built_in">echo</span> <span class="hljs-variable">$new_country</span>
<span class="hljs-comment"># output</span>
Netherlands
</code></pre>
<p>Above, you can see an example of assigning and printing variable values.</p>
<h4 id="heading-variable-naming-conventions">Variable naming conventions</h4>
<p>In Bash scripting, the following are the variable naming conventions:</p>
<ol>
<li><p>Variable names should start with a letter or an underscore (<code>_</code>).</p>
</li>
<li><p>Variable names can contain letters, numbers, and underscores (<code>_</code>).</p>
</li>
<li><p>Variable names are case-sensitive.</p>
</li>
<li><p>Variable names should not contain spaces or special characters.</p>
</li>
<li><p>Use descriptive names that reflect the purpose of the variable.</p>
</li>
<li><p>Avoid using reserved keywords, such as <code>if</code>, <code>then</code>, <code>else</code>, <code>fi</code>, and so on as variable names.</p>
</li>
</ol>
<p>Here are some examples of valid variable names in Bash:</p>
<pre><code class="lang-bash">name
count
_var
myVar
MY_VAR
</code></pre>
<p>And here are some examples of invalid variable names:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># invalid variable names</span>

2ndvar (variable name starts with a number)
my var (variable name contains a space)
my-var (variable name contains a hyphen)
</code></pre>
<p>Following these naming conventions helps make Bash scripts more readable and easier to maintain.</p>
<h4 id="heading-input-and-output-in-bash-scripts">Input and output in Bash scripts</h4>
<h4 id="heading-gathering-input">Gathering input</h4>
<p>In this section, we'll discuss some methods to provide input to our scripts.</p>
<ol>
<li>Reading the user input and storing it in a variable</li>
</ol>
<p>We can read the user input using the <code>read</code> command.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>
<span class="hljs-built_in">echo</span> <span class="hljs-string">"What's your name?"</span>
<span class="hljs-built_in">read</span> entered_name
<span class="hljs-built_in">echo</span> -e <span class="hljs-string">"\nWelcome to bash tutorial"</span> <span class="hljs-variable">$entered_name</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/name-sh.gif" alt="Reading the name from a script" width="600" height="400" loading="lazy"></p>
<p>2.  Reading from a file</p>
<p>This code reads each line from a file named <code>input.txt</code> and prints it to the terminal. We'll study while loops later in this section.</p>
<pre><code class="lang-bash"><span class="hljs-keyword">while</span> <span class="hljs-built_in">read</span> line
<span class="hljs-keyword">do</span>
  <span class="hljs-built_in">echo</span> <span class="hljs-variable">$line</span>
<span class="hljs-keyword">done</span> &lt; input.txt
</code></pre>
<p>3.  Command line arguments</p>
<p>In a bash script or function, <code>$1</code> denotes the initial argument passed, <code>$2</code> denotes the second argument passed, and so forth.</p>
<p>This script takes a name as a command-line argument and prints a personalized greeting.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>
<span class="hljs-built_in">echo</span> <span class="hljs-string">"Hello, <span class="hljs-variable">$1</span>!"</span>
</code></pre>
<p>We have supplied <code>Zaira</code> as our argument to the script.</p>
<p><strong>Output:</strong></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/name-sh-1.gif" alt="Providing arguments to the bash script" width="600" height="400" loading="lazy"></p>
<h4 id="heading-displaying-output">Displaying output</h4>
<p>Here we'll discuss some methods to receive output from the scripts.</p>
<ol>
<li>Printing to the terminal:</li>
</ol>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"Hello, World!"</span>
</code></pre>
<p>This prints the text "Hello, World!" to the terminal.</p>
<p>2.  Writing to a file:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"This is some text."</span> &gt; output.txt
</code></pre>
<p>This writes the text "This is some text." to a file named <code>output.txt</code>. Note that the <code>&gt;</code> operator overwrites a file if it already has some content.</p>
<p>3.  Appending to a file:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"More text."</span> &gt;&gt; output.txt
</code></pre>
<p>This appends the text "More text." to the end of the file <code>output.txt</code>.</p>
<p>4.  Redirecting output:</p>
<pre><code class="lang-bash">ls &gt; files.txt
</code></pre>
<p>This lists the files in the current directory and writes the output to a file named <code>files.txt</code>. You can redirect output of any command to a file this way.</p>
<p>You'll learn about output redirection in detail in section 8.5.</p>
<h4 id="heading-conditional-statements-ifelse">Conditional statements (if/else)</h4>
<p>Expressions that produce a boolean result, either true or false, are called conditions. There are several ways to evaluate conditions, including <code>if</code>, <code>if-else</code>, <code>if-elif-else</code>, and nested conditionals.</p>
<p><strong>Syntax</strong>:</p>
<pre><code class="lang-bash"><span class="hljs-keyword">if</span> [[ condition ]];
<span class="hljs-keyword">then</span>
    statement
<span class="hljs-keyword">elif</span> [[ condition ]]; <span class="hljs-keyword">then</span>
    statement 
<span class="hljs-keyword">else</span>
    <span class="hljs-keyword">do</span> this by default
<span class="hljs-keyword">fi</span>
</code></pre>
<h4 id="heading-syntax-of-bash-conditional-statements">Syntax of bash conditional statements</h4>
<p>We can use logical operators such as AND <code>-a</code> and OR <code>-o</code> to make comparisons that have more significance.</p>
<pre><code class="lang-bash"><span class="hljs-keyword">if</span> [ <span class="hljs-variable">$a</span> -gt 60 -a <span class="hljs-variable">$b</span> -lt 100 ]
</code></pre>
<p>This statement checks if both conditions are <code>true</code>: <code>a</code> is greater than <code>60</code> AND <code>b</code> is less than <code>100</code>.</p>
<p>Let's see an example of a Bash script that uses <code>if</code>, <code>if-else</code>, and <code>if-elif-else</code> statements to determine if a user-inputted number is positive, negative, or zero:</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>

<span class="hljs-comment"># Script to determine if a number is positive, negative, or zero</span>

<span class="hljs-built_in">echo</span> <span class="hljs-string">"Please enter a number: "</span>
<span class="hljs-built_in">read</span> num

<span class="hljs-keyword">if</span> [ <span class="hljs-variable">$num</span> -gt 0 ]; <span class="hljs-keyword">then</span>
  <span class="hljs-built_in">echo</span> <span class="hljs-string">"<span class="hljs-variable">$num</span> is positive"</span>
<span class="hljs-keyword">elif</span> [ <span class="hljs-variable">$num</span> -lt 0 ]; <span class="hljs-keyword">then</span>
  <span class="hljs-built_in">echo</span> <span class="hljs-string">"<span class="hljs-variable">$num</span> is negative"</span>
<span class="hljs-keyword">else</span>
  <span class="hljs-built_in">echo</span> <span class="hljs-string">"<span class="hljs-variable">$num</span> is zero"</span>
<span class="hljs-keyword">fi</span>
</code></pre>
<p>The script first prompts the user to enter a number. Then, it uses an <code>if</code> statement to check if the number is greater than <code>0</code>. If it is, the script outputs that the number is positive. If the number is not greater than <code>0</code>, the script moves on to the next statement, which is an <code>if-elif</code> statement.</p>
<p>Here, the script checks if the number is less than <code>0</code>. If it is, the script outputs that the number is negative.</p>
<p>Finally, if the number is neither greater than <code>0</code> nor less than <code>0</code>, the script uses an <code>else</code> statement to output that the number is zero.</p>
<p>Seeing it in action 🚀</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/test-odd.gif" alt="Checking if a number is even or odd" width="600" height="400" loading="lazy"></p>
<h4 id="heading-looping-and-branching-in-bash">Looping and branching in Bash</h4>
<p><strong>While loop</strong></p>
<p>While loops check for a condition and loop until the condition remains <code>true</code>. We need to provide a counter statement that increments the counter to control loop execution.</p>
<p>In the example below, <code>(( i += 1 ))</code> is the counter statement that increments the value of <code>i</code>. The loop will run exactly 10 times.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>
i=1
<span class="hljs-keyword">while</span> [[ <span class="hljs-variable">$i</span> -le 10 ]] ; <span class="hljs-keyword">do</span>
   <span class="hljs-built_in">echo</span> <span class="hljs-string">"<span class="hljs-variable">$i</span>"</span>
  (( i += 1 ))
<span class="hljs-keyword">done</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-187.png" alt="Looping from 1 to 10 using " width="600" height="400" loading="lazy"></p>
<p><strong>For loop</strong></p>
<p>The <code>for</code> loop, just like the <code>while</code> loop, allows you to execute statements a specific number of times. Each loop differs in its syntax and usage.</p>
<p>In the example below, the loop will iterate 5 times.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>

<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> {1..5}
<span class="hljs-keyword">do</span>
    <span class="hljs-built_in">echo</span> <span class="hljs-variable">$i</span>
<span class="hljs-keyword">done</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-186.png" alt="Looping from 1 to 10 using " width="600" height="400" loading="lazy"></p>
<p><strong>Case statements</strong></p>
<p>In Bash, case statements are used to compare a given value against a list of patterns and execute a block of code based on the first pattern that matches. The syntax for a case statement in Bash is as follows:</p>
<pre><code class="lang-bash"><span class="hljs-keyword">case</span> expression <span class="hljs-keyword">in</span>
    pattern1)
        <span class="hljs-comment"># code to execute if expression matches pattern1</span>
        ;;
    pattern2)
        <span class="hljs-comment"># code to execute if expression matches pattern2</span>
        ;;
    pattern3)
        <span class="hljs-comment"># code to execute if expression matches pattern3</span>
        ;;
    *)
        <span class="hljs-comment"># code to execute if none of the above patterns match expression</span>
        ;;
<span class="hljs-keyword">esac</span>
</code></pre>
<p>Here, "expression" is the value that we want to compare, and "pattern1", "pattern2", "pattern3", and so on are the patterns that we want to compare it against.</p>
<p>The double semicolon ";;" separates each block of code to execute for each pattern. The asterisk "*" represents the default case, which executes if none of the specified patterns match the expression.</p>
<p>Let's see an example:</p>
<pre><code class="lang-bash">fruit=<span class="hljs-string">"apple"</span>

<span class="hljs-keyword">case</span> <span class="hljs-variable">$fruit</span> <span class="hljs-keyword">in</span>
    <span class="hljs-string">"apple"</span>)
        <span class="hljs-built_in">echo</span> <span class="hljs-string">"This is a red fruit."</span>
        ;;
    <span class="hljs-string">"banana"</span>)
        <span class="hljs-built_in">echo</span> <span class="hljs-string">"This is a yellow fruit."</span>
        ;;
    <span class="hljs-string">"orange"</span>)
        <span class="hljs-built_in">echo</span> <span class="hljs-string">"This is an orange fruit."</span>
        ;;
    *)
        <span class="hljs-built_in">echo</span> <span class="hljs-string">"Unknown fruit."</span>
        ;;
<span class="hljs-keyword">esac</span>
</code></pre>
<p>In this example, since the value of <code>fruit</code> is <code>apple</code>, the first pattern matches, and the block of code that echoes <code>This is a red fruit.</code> is executed. If the value of <code>fruit</code> were instead <code>banana</code>, the second pattern would match and the block of code that echoes <code>This is a yellow fruit.</code> would execute, and so on.</p>
<p>If the value of <code>fruit</code> does not match any of the specified patterns, the default case is executed, which echoes <code>Unknown fruit.</code></p>
<h2 id="heading-part-7-managing-software-packages-in-linux">Part 7: Managing Software Packages in Linux</h2>
<p>Linux comes with several built-in programs. But you might need to install new programs based on your needs. You might also need to upgrade the existing applications.</p>
<h3 id="heading-71-packages-and-package-management">7.1. Packages and Package Management</h3>
<h4 id="heading-what-is-a-package">What is a package?</h4>
<p>A package is a collection of files that are bundled together. These files are essential for a particular program to run. These files contain the program's executable files, libraries, and other resources.</p>
<p>In addition to the files required for the program to run, packages also contain installation scripts, which copy the files to where they are needed. A program may contain many files and dependencies. With packages, it is easier to manage all the files and dependencies at once.</p>
<h4 id="heading-what-is-the-difference-between-source-and-binary">What is the difference between source and binary?</h4>
<p>Programmers write source code in a programming language. This source code is then compiled into machine code that the computer can understand. The compiled code is called binary code.</p>
<p>When you download a package, you can either get the <em>source code</em> or the <em>binary code.</em> The source code is the human-readable code that can be compiled into binary code. The binary code is the compiled code that the computer can understand.</p>
<p>Source packages can be used with any type of machine if the source code is compiled properly. Binary, on the other hand, is compiled code that is specific to a particular type of machine or architecture.</p>
<p>You can find the architecture of your machine using the <code>uname -m</code> command.</p>
<pre><code class="lang-bash">uname -m
<span class="hljs-comment"># output</span>
x86_64
</code></pre>
<h4 id="heading-package-dependencies">Package dependencies</h4>
<p>Programs often share files. Instead of including these files in each package, a separate package can provide them for all programs.</p>
<p>To install a program that needs these files, you must also install the package containing them. This is called a package dependency. Specifying dependencies makes packages smaller and simpler by reducing duplicates.</p>
<p>When you install a program, its dependencies must also be installed. Most required dependencies are usually already installed, but a few extra ones might be needed. So, don't be surprised if several other packages are installed along with your chosen package. These are the necessary dependencies.</p>
<h4 id="heading-package-managers">Package managers</h4>
<p>Linux offers a comprehensive package management system for installing, upgrading, configuring, and removing software.</p>
<p>With package management, you can get access to an organized base of thousands of software packages along with having the ability to resolve dependencies and check for software updates.</p>
<p>Packages can be managed using either command-line utilities that can be easily automated by system administrators, or through a graphical interface.</p>
<h4 id="heading-software-channelsrepositories">Software channels/repositories</h4>
<p>⚠️ Package management is different for different distros. Here, we are using Ubuntu.</p>
<p>Installing software is a bit different in Linux as compared to Windows and Mac.</p>
<p>Linux uses repositories to store software packages. A repository is a collection of software packages that are available for installation via a package manager.</p>
<p>A package manager also stores an index of all of the packages available from a repo. Sometimes the index is rebuilt to ensure that it is up to date and to know which packages have been upgraded or added to the channel since it last checked.</p>
<p>The generic process of downloading software from a repo looks something like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719313472889/f4961606-b9c4-4ed7-8edc-61e0fc6908e4.png" alt="Rrocess of downloading software from a remote repo" class="image--center mx-auto" width="1080" height="1080" loading="lazy"></p>
<p>If we talk specifically about Ubuntu,</p>
<ol>
<li><p>Index is fetched using <code>apt update.</code> (<code>apt</code> is explained in next section).</p>
</li>
<li><p>Required files/ dependencies requested according to index using <code>apt install</code></p>
</li>
<li><p>Packages and dependencies installed locally.</p>
</li>
<li><p>Update dependencies and packages when required using <code>apt update</code> and <code>apt upgrade</code></p>
</li>
</ol>
<p>On Debian-based distros, you can file the list of repos (repositories) in <code>/etc/apt/sources.list</code>.</p>
<h3 id="heading-72-installing-a-package-via-command-line">7.2. Installing a Package via Command Line</h3>
<p>The <code>apt</code> command is a powerful command-line tool, which works with Ubuntu’s "Advanced Packaging Tool (APT)".</p>
<p><code>apt</code>, along with the commands bundled with it, provides the means to install new software packages, upgrade existing software packages, update the package list index, and even upgrade the entire Ubuntu system.</p>
<p>To view the logs of the installation using <code>apt</code>, you can view the <code>/var/log/dpkg.log</code> file.</p>
<p>Following are the uses of the <code>apt</code> command:</p>
<h4 id="heading-installing-packages">Installing packages</h4>
<p>For example, to install the <code>htop</code> package, you can use the following command:</p>
<pre><code class="lang-bash">sudo apt install htop
</code></pre>
<h4 id="heading-updating-the-package-list-index">Updating the package list index</h4>
<p>The package list index is a list of all the packages available in the repositories. To update the local package list index, you can use the following command:</p>
<pre><code class="lang-bash">sudo apt update
</code></pre>
<h4 id="heading-upgrading-the-packages">Upgrading the packages</h4>
<p>Installed packages on your system can get updates containing bug fixes, security patches, and new features.</p>
<p>To upgrade the packages, you can use the following command:</p>
<pre><code class="lang-bash">sudo apt upgrade
</code></pre>
<h4 id="heading-removing-packages">Removing packages</h4>
<p>To remove a package, like <code>htop</code>, you can use the following command:</p>
<pre><code class="lang-bash">sudo apt remove htop
</code></pre>
<h3 id="heading-73-installing-a-package-via-an-advanced-graphical-method-synaptic">7.3. Installing a Package via an Advanced Graphical Method – Synaptic</h3>
<p>If you are not comfortable with the command line, you can use a GUI application to install packages. You can achieve the same results as the command line, but with a graphical interface.</p>
<p>Synaptic is a GUI package management application that helps in listing the installed packages, their status, pending updates, and so on. It offers custom filters to help you narrow down the search results.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719313599636/0f362ed7-c371-4a58-96c2-c359178cdbd9.png" alt="0f362ed7-c371-4a58-96c2-c359178cdbd9" class="image--center mx-auto" width="1356" height="868" loading="lazy"></p>
<p>You can also right-click on a package and view further details like the dependencies, maintainer, size, and the installed files.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719313607397/33b7ad76-2492-4805-8133-35c8cd3c4a0a.png" alt="View a package's detail" class="image--center mx-auto" width="560" height="634" loading="lazy"></p>
<h3 id="heading-74-installing-downloaded-packages-from-a-website">7.4. Installing downloaded packages from a website</h3>
<p>You may want to install a package you have downloaded from a website, rather than from a software repository. These packages are called <code>.deb</code> files.</p>
<p><strong>Using</strong><code>dpkg</code><strong>to install packages:</strong><code>dpkg</code> is a command-line tool used to install packages. To install a package with <strong>dpkg</strong>, open the Terminal and type the following:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> directory
sudo dpkg -i package_name.deb
</code></pre>
<p>Note: Replace "directory" with the directory where the package is stored and "package_name" with the filename of the package.</p>
<p>Alternatively, you can right-click, select "Open With Other Application," and choose a GUI app of your choice.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719322161581/f16d83ac-ca9a-4502-a80c-e6a25dee5c68.png" alt="Installing a software using an app" class="image--center mx-auto" width="534" height="505" loading="lazy"></p>
<p>💡 <strong>Tip:</strong> In Ubuntu, you can see a list of installed packages with <code>dpkg --list</code>.</p>
<h2 id="heading-part-8-advanced-linux-topics">Part 8: Advanced Linux Topics</h2>
<h3 id="heading-81-user-management">8.1. User Management</h3>
<p>There can be multiple users with varying levels of access in a system. In Linux, the root user has the highest level of access and can perform any operation on the system. Regular users have limited access and can only perform operations they have been granted permission to do.</p>
<h4 id="heading-what-is-a-user">What is a user?</h4>
<p>A user account provides separation between different people and programs that can run commands.</p>
<p>Humans identify users by a name, as names are easy to work with. But the system identifies users by a unique number called the user ID (UID).</p>
<p>When human users log in using the provided username, they have to use a password to authorize themselves.</p>
<p>User accounts form the foundations of system security. File ownership is also associated with user accounts and it enforces access control to the files. Every process has an associated user account that provides a layer of control for the admins.</p>
<p>There are three main types of user accounts:</p>
<ol>
<li><p><strong>Superuser</strong>: The superuser has complete access to the system. The name of the superuser is <code>root</code>. It has a <code>UID</code> of 0.</p>
</li>
<li><p><strong>System user</strong>: The system user has user accounts that are used to run system services. These accounts are used to run system services and are not meant for human interaction.</p>
</li>
<li><p><strong>Regular user</strong>: Regular users are human users who have access to the system.</p>
</li>
</ol>
<p>The <code>id</code> command displays the user ID and group ID of the current user.</p>
<pre><code class="lang-bash">id
uid=1000(john) gid=1000(john) groups=1000(john),4(adm),24(cdrom),27(sudo),30(dip)... output truncated
</code></pre>
<p>To view the basic information of another user, pass the username as an argument to the <code>id</code> command.</p>
<pre><code class="lang-bash">id username
</code></pre>
<p>To view user-related information for processes, use the <code>ps</code> command with the <code>-u</code> flag.</p>
<pre><code class="lang-bash">ps -u
<span class="hljs-comment"># Output</span>
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.1  16968  3920 ?        Ss   18:45   0:00 /sbin/init splash
root         2  0.0  0.0      0     0 ?        S    18:45   0:00 [kthreadd]
</code></pre>
<p>By default, systems use the <code>/etc/passwd</code> file to store user information.</p>
<p>Here is a line from the <code>/etc/passwd</code> file:</p>
<pre><code class="lang-bash">root:x:0:0:root:/root:/bin/bash
</code></pre>
<p>The <code>/etc/passwd</code> file contains the following information about each user:</p>
<ol>
<li><p>Username: <code>root</code> – The username of the user account.</p>
</li>
<li><p>Password: <code>x</code> – The password in encrypted format for the user account that is stored in the <code>/etc/shadow</code> file for security reasons.</p>
</li>
<li><p>User ID (UID): <code>0</code> – The unique numerical identifier for the user account.</p>
</li>
<li><p>Group ID (GID): <code>0</code> – The primary group identifier for the user account.</p>
</li>
<li><p>User Info: <code>root</code> – The real name for the user account.</p>
</li>
<li><p>Home directory: <code>/root</code> – The home directory for the user account.</p>
</li>
<li><p>Shell: <code>/bin/bash</code> – The default shell for the user account. A system user might use <code>/sbin/nologin</code> if interactive logins are not allowed for that user.</p>
</li>
</ol>
<h4 id="heading-what-is-a-group">What is a group?</h4>
<p>A group is a collection of user accounts that share access and resources. Groups have group names to identify them. The system identifies groups by a unique number called the group ID (GID).</p>
<p>By default, the information about groups is stored in the <code>/etc/group</code> file.</p>
<p>Here is an entry from the <code>/etc/group</code> file:</p>
<pre><code class="lang-bash">adm:x:4:syslog,john
</code></pre>
<p>Here is the breakdown of the fields in the given entry:</p>
<ol>
<li><p>Group name: <code>adm</code> – The name of the group.</p>
</li>
<li><p>Password: <code>x</code> – The password for the group is stored in the <code>/etc/gshadow</code> file for security reasons. The password is optional and appears empty if not set.</p>
</li>
<li><p>Group ID (GID): <code>4</code> – The unique numerical identifier for the group.</p>
</li>
<li><p>Group members: <code>syslog,john</code> – The list of usernames that are members of the group. In this case, the group <code>adm</code> has two members: <code>syslog</code> and <code>john</code>.</p>
</li>
</ol>
<p>In this specific entry, the group name is <code>adm</code>, the group ID is <code>4</code>, and the group has two members: <code>syslog</code> and <code>john</code>. The password field is typically set to <code>x</code> to indicate that the group password is stored in the <code>/etc/gshadow</code> file.</p>
<p>The groups are further divided into '<em>primary'</em> and '<em>supplementary'</em> groups.</p>
<ul>
<li><p>Primary Group: Each user is assigned one primary group by default. This group usually has the same name as the user and is created when the user account is made. Files and directories created by the user are typically owned by this primary group.</p>
</li>
<li><p>Supplementary Groups: These are extra groups a user can belong to in addition to their primary group. Users can be members of multiple supplementary groups. These groups let a user have permissions for resources shared among those groups. They help provide access to shared resources without affecting the system’s file permissions and keeping the security intact. While a user must belong to one primary group, belonging to supplementary groups is optional.</p>
</li>
</ul>
<h4 id="heading-access-control-finding-and-understanding-file-permission">Access control: finding and understanding file permission</h4>
<p>File ownership can be viewed using the <code>ls -l</code> command. The first column in the output of the <code>ls -l</code> command shows the permissions of the file. Other columns show the owner of the file and the group that the file belongs to.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-146.png" alt="Detailed output of ls -l" width="600" height="400" loading="lazy"></p>
<p>Let's have a closer look into the <code>mode</code> column:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-147.png" alt="Permission classes and file types" width="600" height="400" loading="lazy"></p>
<p><strong>Mode</strong> defines two things:</p>
<ul>
<li><p><strong>File type:</strong> File type defines the type of the file. For regular files that contain simple data it is blank <code>-</code>. For other special file types the symbol is different. For a directory which is a special file, it is <code>d</code>. Special files are treated differently by the OS.</p>
</li>
<li><p><strong>Permission classes:</strong> The next set of characters define the permissions for user, group, and others respectively.<br>  – <strong>User</strong>: This is the owner of a file and owner of the file belongs to this class.<br>  – <strong>Group</strong>: The members of the file’s group belong to this class<br>  – <strong>Other</strong>: Any users that are not part of the user or group classes belong to this class.</p>
</li>
</ul>
<p>💡<strong>Tip:</strong> Directory ownership can be viewed using the <code>ls -ld</code> command.</p>
<h5 id="heading-how-to-read-symbolic-permissions-or-the-rwx-permissions">How to Read Symbolic Permissions or the <code>rwx</code> permissions</h5>
<p>The <code>rwx</code> representation is known as the Symbolic representation of permissions. In the set of permissions,</p>
<ul>
<li><p><code>r</code> stands for <strong>read</strong>. It is indicated in the first character of the triad.</p>
</li>
<li><p><code>w</code> stands for <strong>write</strong>. It is indicated in the second character of the triad.</p>
</li>
<li><p><code>x</code> stands for <strong>execution</strong>. It is indicated in the third character of the triad.</p>
</li>
</ul>
<p><strong>Read:</strong></p>
<p>For regular files, read permissions allow the file to be opened and read only. Users can't modify the file.</p>
<p>Similarly for directories, read permissions allow the listing of directory content without any modification in the directory.</p>
<p><strong>Write:</strong></p>
<p>When files have write permissions, the user can modify (edit, delete) the file and save it.</p>
<p>For folders, write permissions enable a user to modify its contents (create, delete, and rename the files inside it), and modify the contents of files that the user has write permissions to.</p>
<p><strong>Examples of permissions in Linux</strong></p>
<p>Now that we know how to read permissions, let's see some examples.</p>
<ul>
<li><p><code>-rwx------</code>: A file that is only accessible and executable by its owner.</p>
<p>  <code>-rw-rw-r--</code>: A file that is open to modification by its owner and group but not by others.</p>
</li>
<li><p><code>drwxrwx---</code>: A directory that can be modified by its owner and group.</p>
</li>
</ul>
<p><strong>Execute:</strong></p>
<p>For files, execute permissions allows the user to run an executable script. For directories, the user can access them, and access details about files in the directory.</p>
<h5 id="heading-how-to-change-file-permissions-and-ownership-in-linux-using-chmod-and-chown">How to Change File Permissions and Ownership in Linux using <code>chmod</code> and <code>chown</code></h5>
<p>Now that we know the basics of ownerships and permissions, let's see how we can modify permissions using the <code>chmod</code> command.</p>
<p><strong>Syntax of</strong><code>chmod</code>:</p>
<pre><code class="lang-bash">chmod permissions filename
</code></pre>
<p>Where,</p>
<ul>
<li><p><code>permissions</code> can be read, write, execute or a combination of them.</p>
</li>
<li><p><code>filename</code> is the name of the file for which the permissions need to change. This parameter can also be a list if files to change permissions in bulk.</p>
</li>
</ul>
<p>We can change permissions using two modes:</p>
<ol>
<li><p><strong>Symbolic mode</strong>: this method uses symbols like <code>u</code>, <code>g</code>, <code>o</code> to represent users, groups, and others. Permissions are represented as  <code>r, w, x</code> for read, write, and execute, respectively. You can modify permissions using +, - and =.</p>
</li>
<li><p><strong>Absolute mode</strong>: this method represents permissions as 3-digit octal numbers ranging from 0-7.</p>
</li>
</ol>
<p>Now, let's see them in detail.</p>
<h5 id="heading-how-to-change-permissions-using-symbolic-mode">How to Change Permissions using Symbolic Mode</h5>
<p>The table below summarize the user representation:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>USER REPRESENTATION</strong></td><td><strong>DESCRIPTION</strong></td></tr>
</thead>
<tbody>
<tr>
<td>u</td><td>user/owner</td></tr>
<tr>
<td>g</td><td>group</td></tr>
<tr>
<td>o</td><td>other</td></tr>
</tbody>
</table>
</div><p>We can use mathematical operators to add, remove, and assign permissions. The table below shows the summary:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>OPERATOR</strong></td><td><strong>DESCRIPTION</strong></td></tr>
</thead>
<tbody>
<tr>
<td>+</td><td>Adds a permission to a file or directory</td></tr>
<tr>
<td>–</td><td>Removes the permission</td></tr>
<tr>
<td>\=</td><td>Sets the permission if not present before. Also overrides the permissions if set earlier.</td></tr>
</tbody>
</table>
</div><p><strong>Example:</strong></p>
<p>Suppose I have a script and I want to make it executable for the owner of the file <code>zaira</code>.</p>
<p>Current file permissions are as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-161.png" alt="image-161" width="600" height="400" loading="lazy"></p>
<p>Let's split the permissions like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-160.png" alt="Splitting file permissions" width="600" height="400" loading="lazy"></p>
<p>To add execution rights (<code>x</code>) to owner (<code>u</code>) using symbolic mode, we can use the command below:</p>
<pre><code class="lang-bash">chmod u+x mymotd.sh
</code></pre>
<p><strong>Output:</strong></p>
<p>Now, we can see that the execution permissions have been added for owner <code>zaira</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-162.png" alt="Permission updated" width="600" height="400" loading="lazy"></p>
<p><strong>Additional examples for changing permissions via symbolic method:</strong></p>
<ul>
<li><p>Removing <code>read</code> and <code>write</code> permission for <code>group</code> and <code>others</code>: <code>chmod go-rw</code>.</p>
</li>
<li><p>Removing <code>read</code> permissions for <code>others</code>: <code>chmod o-r</code>.</p>
</li>
<li><p>Assigning <code>write</code> permission to <code>group</code> and overriding existing permission: <code>chmod g=w</code>.</p>
</li>
</ul>
<h5 id="heading-how-to-change-permissions-using-absolute-mode">How to Change Permissions using Absolute Mode</h5>
<p>Absolute mode uses numbers to represent permissions and mathematical operators to modify them.</p>
<p>The below table shows how we can assign relevant permissions:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>PERMISSION</strong></td><td><strong>PROVIDE PERMISSION</strong></td></tr>
</thead>
<tbody>
<tr>
<td>read</td><td>add 4</td></tr>
<tr>
<td>write</td><td>add 2</td></tr>
<tr>
<td>execute</td><td>add 1</td></tr>
</tbody>
</table>
</div><p>Permissions can be revoked using subtraction. The below table shows how you can remove relevant permissions.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>PERMISSION</strong></td><td><strong>REVOKE PERMISSION</strong></td></tr>
</thead>
<tbody>
<tr>
<td>read</td><td>subtract 4</td></tr>
<tr>
<td>write</td><td>subtract 2</td></tr>
<tr>
<td>execute</td><td>subtract 1</td></tr>
</tbody>
</table>
</div><p><strong>Example</strong>:</p>
<ul>
<li>Set <code>read</code> (add 4) for <code>user</code>, <code>read</code> (add 4) and <code>execute</code> (add 1) for group, and only <code>execute</code> (add 1) for others.</li>
</ul>
<p><code>chmod 451 file-name</code></p>
<p>This is how we performed the calculation:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-163.png" alt="Calculation breakdown for adding permissions" width="600" height="400" loading="lazy"></p>
<p>Note that this is the same as <code>r--r-x--x</code>.</p>
<ul>
<li>Remove <code>execution</code> rights from <code>other</code> and <code>group</code>.</li>
</ul>
<p>To remove execution from <code>other</code> and <code>group</code>, subtract 1 from the execute part of last 2 octets.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-164.png" alt="Calculation breakdown for removing permissions" width="600" height="400" loading="lazy"></p>
<ul>
<li>Assign <code>read</code>, <code>write</code> and <code>execute</code> to <code>user</code>, <code>read</code> and <code>execute</code> to <code>group</code> and only <code>read</code> to others.</li>
</ul>
<p>This would be the same as <code>rwxr-xr--</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-165.png" alt="Calculation breakdown for adding permissions" width="600" height="400" loading="lazy"></p>
<h5 id="heading-how-to-change-ownership-using-the-chown-command">How to Change Ownership using the <code>chown</code> Command</h5>
<p>Next, we will learn how to change the ownership of a file. You can change the ownership of a file or folder using the <code>chown</code> command. In some cases, changing ownership requires <code>sudo</code> permissions.</p>
<p>Syntax of <code>chown</code>:</p>
<pre><code class="lang-bash">chown user filename
</code></pre>
<h5 id="heading-how-to-change-user-ownership-with-chown">How to change user ownership with <code>chown</code></h5>
<p>Let's transfer the ownership from user <code>zaira</code> to user <code>news</code>.</p>
<p><code>chown news mymotd.sh</code></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-167.png" alt="view current owner" width="600" height="400" loading="lazy"></p>
<p>Command to change ownership: <code>sudo chown news mymotd.sh</code>.</p>
<p><strong>Output:</strong></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-168.png" alt="Ownership changed" width="600" height="400" loading="lazy"></p>
<h5 id="heading-how-to-change-user-and-group-ownership-simultaneously">How to change user and group ownership simultaneously</h5>
<p>We can also use <code>chown</code> to change user and group simultaneously.</p>
<pre><code class="lang-bash">chown user:group filename
</code></pre>
<h5 id="heading-how-to-change-directory-ownership">How to change directory ownership</h5>
<p>You can change ownership recursively for contents in a directory. The example below changes the ownership of the <code>/opt/script</code> folder to allow user <code>admin</code>.</p>
<pre><code class="lang-bash">chown -R admin /opt/script
</code></pre>
<h5 id="heading-how-to-change-group-ownership">How to change group ownership</h5>
<p>In case we only need to change the group owner, we can use <code>chown</code> by preceding the group name by a colon <code>:</code></p>
<pre><code class="lang-bash">chown :admins /opt/script
</code></pre>
<h5 id="heading-how-to-switch-between-users">How to switch between users</h5>
<p>You can switch between users using the <code>su</code> command.</p>
<pre><code class="lang-bash">[user01@host ~]$ su user02
Password:
[user02@host ~]$
</code></pre>
<h5 id="heading-how-to-gain-superuser-access">How to gain superuser access</h5>
<p>The superuser or the root user has the highest level of access on a Linux system. The root user can perform any operation on the system. The root user can access all files and directories, install and remove software, and modify or override system configurations.</p>
<p>With great power comes great responsibility. If the root user is compromised, someone can gain complete control over the system. It is advised to use the root user account only when necessary.</p>
<p>If you omit the username, the <code>su</code> command switches to the root user account by default.</p>
<pre><code class="lang-bash">[user01@host ~]$ su
Password:
[root@host ~]<span class="hljs-comment">#</span>
</code></pre>
<p>Another variation of the <code>su</code> command is <code>su -</code>. The <code>su</code> command switches to the root user account but does not change the environment variables. The <code>su -</code> command switches to the root user account and changes the environment variables to those of the target user.</p>
<h5 id="heading-running-commands-with-sudo">Running commands with sudo</h5>
<p>To run commands as the <code>root</code> user without switching to the <code>root</code> user account, you can use the <code>sudo</code> command. The <code>sudo</code> command allows you to run commands with elevated privileges.</p>
<p>Running commands with <code>sudo</code> is a safer option rather than running the commands as the <code>root</code> user. This is because, only a specific set of users can be granted permission to run commands with <code>sudo</code>. This is defined in the <code>/etc/sudoers</code> file.</p>
<p>Also, <code>sudo</code> logs all commands that are run with it, providing an audit trail of who ran which commands and when.</p>
<p>In Ubuntu, you can find the audit logs here:</p>
<pre><code class="lang-bash">cat /var/<span class="hljs-built_in">log</span>/auth.log | grep sudo
</code></pre>
<p>For a user that does not have access to <code>sudo</code>, it gets flagged in logs and prompts a message like this:</p>
<pre><code class="lang-bash">user01 is not <span class="hljs-keyword">in</span> the sudoers file.  This incident will be reported.
</code></pre>
<h4 id="heading-managing-local-user-accounts">Managing local user accounts</h4>
<h5 id="heading-creating-users-from-the-command-line">Creating users from the command line</h5>
<p>The command used to add a new user is:</p>
<pre><code class="lang-bash">sudo useradd username
</code></pre>
<p>This command sets up a user's home directory and creates a private group designated by the user's username. Currently, the account lacks a valid password, preventing the user from logging in until a password is created.</p>
<h5 id="heading-modifying-existing-users">Modifying existing users</h5>
<p>The <code>usermod</code> command is used to modify existing users. Here are some of the common options used with the <code>usermod</code> command:</p>
<p>Here are some examples of the <code>usermod</code> command in Linux:</p>
<ol>
<li><p><strong>Change a user's login name:</strong></p>
<pre><code class="lang-bash"> sudo usermod -l newusername oldusername
</code></pre>
</li>
<li><p><strong>Change a user's home directory:</strong></p>
<pre><code class="lang-bash"> sudo usermod -d /new/home/directory -m username
</code></pre>
</li>
<li><p><strong>Add a user to a supplementary group:</strong></p>
<pre><code class="lang-bash"> sudo usermod -aG groupname username
</code></pre>
</li>
<li><p><strong>Change a user's shell:</strong></p>
<pre><code class="lang-bash"> sudo usermod -s /bin/bash username
</code></pre>
</li>
<li><p><strong>Lock a user's account:</strong></p>
<pre><code class="lang-bash"> sudo usermod -L username
</code></pre>
</li>
<li><p><strong>Unlock a user's account:</strong></p>
<pre><code class="lang-bash"> sudo usermod -U username
</code></pre>
</li>
<li><p><strong>Set an expiration date for a user account:</strong></p>
<pre><code class="lang-bash"> sudo usermod -e YYYY-MM-DD username
</code></pre>
</li>
<li><p><strong>Change a user's user ID (UID):</strong></p>
<pre><code class="lang-bash"> sudo usermod -u newUID username
</code></pre>
</li>
<li><p><strong>Change a user's primary group:</strong></p>
<pre><code class="lang-bash"> sudo usermod -g newgroup username
</code></pre>
</li>
<li><p><strong>Remove a user from a supplementary group:</strong></p>
<pre><code class="lang-bash">sudo gpasswd -d username groupname
</code></pre>
</li>
</ol>
<h5 id="heading-deleting-users">Deleting users</h5>
<p>The <code>userdel</code> command is used to delete a user account and related files from the system.</p>
<ul>
<li><p><code>sudo userdel username</code>: removes the user's details from <code>/etc/passwd</code> but keeps the user's home directory.</p>
</li>
<li><p>The <code>sudo userdel -r username</code> command removes the user's details from <code>/etc/passwd</code> and also deletes the user's home directory.</p>
</li>
</ul>
<h5 id="heading-changing-user-passwords">Changing user passwords</h5>
<p>The <code>passwd</code> command is used to change a user's password.</p>
<ul>
<li><code>sudo passwd username</code>: sets the initial password or changes the existing password of username. It is also used to change the password of the currently logged in user.</li>
</ul>
<h3 id="heading-82-connecting-to-remote-servers-via-ssh">8.2 Connecting to Remote Servers via SSH</h3>
<p>Accessing remote servers is one of the essential tasks for system administrators. You can connect to different servers or access databases through your local machine and execute commands, all using SSH.</p>
<p><strong>What is the SSH protocol?</strong></p>
<p>SSH stands for Secure Shell. It is a cryptographic network protocol that allows secure communication between two systems.</p>
<p>The default port for SSH is <code>22</code>.</p>
<p>The two participants while communicating via SSH are:</p>
<ul>
<li><p>The server: the machine that you want access to.</p>
</li>
<li><p>The client: The system that you are accessing the server from.</p>
</li>
</ul>
<p>Connection to a server follows these steps:</p>
<ol>
<li><p>Initiate Connection: The client sends a connection request to the server.</p>
</li>
<li><p>Exchange of Keys: The server sends its public key to the client. Both agree on the encryption methods to use.</p>
</li>
<li><p>Session Key Generation: The client and server use the Diffie-Hellman key exchange to create a shared session key.</p>
</li>
<li><p>Client Authentication: The client logs in to the server using a password, private key, or another method.</p>
</li>
<li><p>Secure Communication: After authentication, the client and server communicate securely with encryption.</p>
</li>
</ol>
<p><strong>How to connect to a remote server using SSH?</strong></p>
<p>The <code>ssh</code> command is a built-in utility in Linux and also the default one. It makes accessing servers quite easy and secure.</p>
<p>Here, we are talking about how the client would make a connection to the server.</p>
<p>Prior to connecting to a server, you need to have the following information:</p>
<ul>
<li><p>The IP address or the domain name of the server.</p>
</li>
<li><p>The username and password of the server.</p>
</li>
<li><p>The port number that you have access to in the server.</p>
</li>
</ul>
<p>The basic syntax of the <code>ssh</code> command is:</p>
<pre><code class="lang-bash">ssh username@server_ip
</code></pre>
<p>For example, if your username is <code>john</code> and the server IP is <code>192.168.1.10</code>, the command would be:</p>
<pre><code class="lang-bash">ssh john@192.168.1.10
</code></pre>
<p>After that, you'll be prompted to enter the secret password. Your screen will look similar to this:</p>
<pre><code class="lang-bash">john@192.168.1.10<span class="hljs-string">'s password: 
Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 5.4.0-70-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Fri Jun  5 10:17:32 UTC 2024

  System load:  0.08               Processes:           122
  Usage of /:   12.3% of 19.56GB   Users logged in:     1
  Memory usage: 53%                IP address for eth0: 192.168.1.10
  Swap usage:   0%

Last login: Fri Jun  5 09:34:56 2024 from 192.168.1.2
john@hostname:~$ # start entering commands</span>
</code></pre>
<p>Now you can execute the relevant commands on the server <code>192.168.1.10</code>.</p>
<p>⚠️ The default port for ssh is <code>22</code> but it is also vulnerable, as hackers will likely attempt here first. Your server can expose another port and share the access with you. To connect to a different port, use the <code>-p</code> flag.</p>
<pre><code class="lang-bash">ssh -p port_number username@server_ip
</code></pre>
<h3 id="heading-83-advanced-log-parsing-and-analysis">8.3. Advanced Log Parsing and Analysis</h3>
<p>Log files, when configured, are generated by your system for a variety of useful reasons. They can be used to track system events, monitor system performance, and troubleshoot issues. They are specifically useful for system administrators where they can track application errors, network events, and user activity.</p>
<p>Here is an example of a log file:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># sample log file</span>
2024-04-25 09:00:00 INFO Startup: Application starting
2024-04-25 09:01:00 INFO Config: Configuration loaded successfully
2024-04-25 09:02:00 DEBUG Database: Database connection established
2024-04-25 09:03:00 INFO User: New user registered (UserID: 1001)
2024-04-25 09:04:00 WARN Security: Attempted login with incorrect credentials (UserID: 1001)
2024-04-25 09:05:00 ERROR Network: Network timeout on request (ReqID: 456)
2024-04-25 09:06:00 INFO Email: Notification email sent (UserID: 1001)
2024-04-25 09:07:00 DEBUG API: API call with response time over threshold (Duration: 350ms)
2024-04-25 09:08:00 INFO Session: User session ended (UserID: 1001)
2024-04-25 09:09:00 INFO Shutdown: Application shutdown initiated
</code></pre>
<p>A log file usually contains the following columns:</p>
<ul>
<li><p>Timestamp: The date and time when the event occurred.</p>
</li>
<li><p>Log Level: The severity of the event (INFO, DEBUG, WARN, ERROR).</p>
</li>
<li><p>Component: The component of the system that generated the event (Startup, Config, Database, User, Security, Network, Email, API, Session, Shutdown).</p>
</li>
<li><p>Message: A description of the event that occurred.</p>
</li>
<li><p>Additional Information: Additional information related to the event.</p>
</li>
</ul>
<p>In real-time systems, log files tend to be thousands of lines long and are generated every second. They can be very wordy depending on the configuration. Every column in a log file is a piece of information that can be used to track down issues. This makes log files difficult to read and understand manually.</p>
<p>This is where log parsing comes in. Log parsing is the process of extracting useful information from log files. It involves breaking down the log files into smaller, more manageable pieces, and extracting the relevant information.</p>
<p>The filtered information can also be useful for creating alerts, reports, and dashboards.</p>
<p>In this section, you will explore some techniques for parsing log files in Linux.</p>
<h4 id="heading-text-extraction-using-grep">Text extraction using <code>grep</code></h4>
<p>Grep is a built-in bash utility. It stands for "global regular expression print". Grep is used to match strings in files.</p>
<p>Here are some common uses of <code>grep</code>:</p>
<ol>
<li><p><strong>Search for a specific string in a file:</strong></p>
<pre><code class="lang-bash"> grep <span class="hljs-string">"search_string"</span> filename
</code></pre>
<p> This command searches for "search_string" in the file named <code>filename</code>.</p>
</li>
<li><p><strong>Search recursively in directories:</strong></p>
<pre><code class="lang-bash"> grep -r <span class="hljs-string">"search_string"</span> /path/to/directory
</code></pre>
<p> This command searches for "<code>search_string"</code> in all files within the specified directory and its subdirectories.</p>
</li>
<li><p><strong>Ignore case while searching:</strong></p>
<pre><code class="lang-bash"> grep -i <span class="hljs-string">"search_string"</span> filename
</code></pre>
<p> This command performs a case-insensitive search for "search_string" in the file named <code>filename</code>.</p>
</li>
<li><p><strong>Display line numbers with matching lines:</strong></p>
<pre><code class="lang-bash"> grep -n <span class="hljs-string">"search_string"</span> filename
</code></pre>
<p> This command shows the line numbers along with the matching lines in the file named <code>filename</code>.</p>
</li>
<li><p><strong>Count the number of matching lines:</strong></p>
<pre><code class="lang-bash"> grep -c <span class="hljs-string">"search_string"</span> filename
</code></pre>
<p> This command counts the number of lines that contain "search_string" in the file named <code>filename</code>.</p>
</li>
<li><p><strong>Invert match to display lines that do not match:</strong></p>
<pre><code class="lang-bash"> grep -v <span class="hljs-string">"search_string"</span> filename
</code></pre>
<p> This command displays all lines that do not contain "search_string" in the file named <code>filename</code>.</p>
</li>
<li><p><strong>Search for a whole word:</strong></p>
<pre><code class="lang-bash"> grep -w <span class="hljs-string">"word"</span> filename
</code></pre>
<p> This command searches for the whole word "word" in the file named <code>filename</code>.</p>
</li>
<li><p><strong>Use extended regular expressions:</strong></p>
<pre><code class="lang-bash"> grep -E <span class="hljs-string">"pattern"</span> filename
</code></pre>
<p> This command allows the use of extended regular expressions for more complex pattern matching in the file named <code>filename</code>.</p>
</li>
</ol>
<p><strong>💡 Tip:</strong> If there are multiple files in a folder, you can use the below command to find the list of files containing the desired strings.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># find the list of files containing the desired strings</span>
grep -l <span class="hljs-string">"String to Match"</span> /path/to/directory
</code></pre>
<h4 id="heading-text-extraction-using-sed">Text extraction using <code>sed</code></h4>
<p><code>sed</code> stands for "stream editor". It processes data stream-wise, meaning it reads data one line at a time. <code>sed</code> allows you to search for patterns and perform actions on the lines that match those patterns.</p>
<p><strong>Basic syntax of</strong><code>sed</code>:</p>
<p>The basic syntax of <code>sed</code> is as follows:</p>
<pre><code class="lang-bash">sed [options] <span class="hljs-string">'command'</span> file_name
</code></pre>
<p>Here, <code>command</code> is used to perform operations like substitution, deletion, insertion, and so on, on the text data. The filename is the name of the file you want to process.</p>
<p><code>sed</code><strong>usage:</strong></p>
<p><strong>1. Substitution:</strong></p>
<p>The <code>s</code> flag is used to replace text. The <code>old-text</code> is replaced with <code>new-text</code>:</p>
<pre><code class="lang-bash">sed <span class="hljs-string">'s/old-text/new-text/'</span> filename
</code></pre>
<p>For example, to change all instances of "error" to "warning" in the log file <code>system.log</code>:</p>
<pre><code class="lang-bash">sed <span class="hljs-string">'s/error/warning/'</span> system.log
</code></pre>
<p><strong>2. Printing lines containing a specific pattern:</strong></p>
<p>Using <code>sed</code> to filter and display lines that match a specific pattern:</p>
<pre><code class="lang-bash">sed -n <span class="hljs-string">'/pattern/p'</span> filename
</code></pre>
<p>For instance, to find all lines containing "ERROR":</p>
<pre><code class="lang-bash">sed -n <span class="hljs-string">'/ERROR/p'</span> system.log
</code></pre>
<p><strong>3. Deleting lines containing a specific pattern:</strong></p>
<p>You can delete lines from the output that match a specific pattern:</p>
<pre><code class="lang-bash">sed <span class="hljs-string">'/pattern/d'</span> filename
</code></pre>
<p>For example, to remove all lines containing "DEBUG":</p>
<pre><code class="lang-bash">sed <span class="hljs-string">'/DEBUG/d'</span> system.log
</code></pre>
<p><strong>4. Extracting specific fields from a log line:</strong></p>
<p>You can use regular expressions to extract parts of lines. Suppose each log line starts with a date in the format "YYYY-MM-DD". You could extract just the date from each line:</p>
<pre><code class="lang-bash">sed -n <span class="hljs-string">'s/^\([0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}\).*/\1/p'</span> system.log
</code></pre>
<h4 id="heading-text-parsing-with-awk">Text parsing with <code>awk</code></h4>
<p><code>awk</code> has the ability to easily split each line into fields. It's well-suited for processing structured text like log files.</p>
<p><strong>Basic syntax of</strong><code>awk</code></p>
<p>The basic syntax of <code>awk</code> is:</p>
<pre><code class="lang-bash">awk <span class="hljs-string">'pattern { action }'</span> file_name
</code></pre>
<p>Here, <code>pattern</code> is a condition that must be met for the <code>action</code> to be performed. If the pattern is omitted, the action is performed on every line.</p>
<p>In the coming examples, you'll use this log file as an example:</p>
<pre><code class="lang-bash">2024-04-25 09:00:00 INFO Startup: Application starting
2024-04-25 09:01:00 INFO Config: Configuration loaded successfully
2024-04-25 09:02:00 INFO Database: Database connection established
2024-04-25 09:03:00 INFO User: New user registered (UserID: 1001)
2024-04-25 09:04:00 INFO Security: Attempted login with incorrect credentials (UserID: 1001)
2024-04-25 09:05:00 INFO Network: Network timeout on request (ReqID: 456)
2024-04-25 09:06:00 INFO Email: Notification email sent (UserID: 1001)
2024-04-25 09:07:00 INFO API: API call with response time over threshold (Duration: 350ms)
2024-04-25 09:08:00 INFO Session: User session ended (UserID: 1001)
2024-04-25 09:09:00 INFO Shutdown: Application shutdown initiated
  INFO
</code></pre>
<ul>
<li><strong>Accessing columns using</strong><code>awk</code></li>
</ul>
<p>The fields in <code>awk</code> (separated by spaces by default) can be accessed using <code>$1</code>, <code>$2</code>, <code>$3</code>, and so on.</p>
<pre><code class="lang-bash">zaira@zaira-ThinkPad:~$ awk <span class="hljs-string">'{ print $1 }'</span> sample.log
<span class="hljs-comment"># output</span>
2024-04-25
2024-04-25
2024-04-25
2024-04-25
2024-04-25
2024-04-25
2024-04-25
2024-04-25
2024-04-25
2024-04-25

zaira@zaira-ThinkPad:~$ awk <span class="hljs-string">'{ print $2 }'</span> sample.log
<span class="hljs-comment"># output</span>
09:00:00
09:01:00
09:02:00
09:03:00
09:04:00
09:05:00
09:06:00
09:07:00
09:08:00
09:09:00
</code></pre>
<ul>
<li><strong>Print lines containing a specific pattern (for example, ERROR)</strong></li>
</ul>
<pre><code class="lang-bash">awk <span class="hljs-string">'/ERROR/ { print $0 }'</span> logfile.log

<span class="hljs-comment"># output</span>
2024-04-25 09:05:00 ERROR Network: Network timeout on request (ReqID: 456)
</code></pre>
<p>This prints all lines that contain "ERROR".</p>
<ul>
<li><strong>Extract the first field (Date and Time)</strong></li>
</ul>
<pre><code class="lang-bash">awk <span class="hljs-string">'{ print $1, $2 }'</span> logfile.log
<span class="hljs-comment"># output</span>
2024-04-25 09:00:00
2024-04-25 09:01:00
2024-04-25 09:02:00
2024-04-25 09:03:00
2024-04-25 09:04:00
2024-04-25 09:05:00
2024-04-25 09:06:00
2024-04-25 09:07:00
2024-04-25 09:08:007
2024-04-25 09:09:00
</code></pre>
<p>This will extract the first two fields from each line, which in this case would be the date and time.</p>
<ul>
<li><strong>Summarize occurrences of each log level</strong></li>
</ul>
<pre><code class="lang-bash">awk <span class="hljs-string">'{ count[$3]++ } END { for (level in count) print level, count[level] }'</span> logfile.log

<span class="hljs-comment"># output</span>
 1
WARN 1
ERROR 1
DEBUG 2
INFO 6
</code></pre>
<p>The output will be a summary of the number of occurrences of each log level.</p>
<ul>
<li><strong>Filter out specific fields (for example, where the 3rd field is INFO)</strong></li>
</ul>
<pre><code class="lang-bash">awk <span class="hljs-string">'{ $3="INFO"; print }'</span> sample.log

<span class="hljs-comment"># output</span>
2024-04-25 09:00:00 INFO Startup: Application starting
2024-04-25 09:01:00 INFO Config: Configuration loaded successfully
2024-04-25 09:02:00 INFO Database: Database connection established
2024-04-25 09:03:00 INFO User: New user registered (UserID: 1001)
2024-04-25 09:04:00 INFO Security: Attempted login with incorrect credentials (UserID: 1001)
2024-04-25 09:05:00 INFO Network: Network timeout on request (ReqID: 456)
2024-04-25 09:06:00 INFO Email: Notification email sent (UserID: 1001)
2024-04-25 09:07:00 INFO API: API call with response time over threshold (Duration: 350ms)
2024-04-25 09:08:00 INFO Session: User session ended (UserID: 1001)
2024-04-25 09:09:00 INFO Shutdown: Application shutdown initiated
  INFO
</code></pre>
<p>This command will extract all lines where the 3rd field is "INFO".</p>
<p>💡 <strong>Tip:</strong> The default separator in <code>awk</code> is a space. If your log file uses a different separator, you can specify it using the <code>-F</code> option. For example, if your log file uses a colon as a separator, you can use <code>awk -F: '{ print $1 }' logfile.log</code> to extract the first field.</p>
<h4 id="heading-parsing-log-files-with-cut">Parsing log files with <code>cut</code></h4>
<p>The <code>cut</code> command is a simple yet powerful command used to extract sections of text from each line of input. As log files are structured and each field is delimited by a specific character, such as a space, tab, or a custom delimiter, <code>cut</code> does a very good job of extracting those specific fields.</p>
<p>The basic syntax of the cut command is:</p>
<pre><code class="lang-bash">cut [options] [file]
</code></pre>
<p>Some commonly used options for the cut command:</p>
<ul>
<li><p><code>-d</code> : Specifies a delimiter used as the field separator.</p>
</li>
<li><p><code>-f</code> : Selects the fields to be displayed.</p>
</li>
<li><p><code>-c</code> : Specifies character positions.</p>
</li>
</ul>
<p>For example, the command below would extract the first field (separated by a space) from each line of the log file:</p>
<pre><code class="lang-bash">cut -d <span class="hljs-string">' '</span> -f 1 logfile.log
</code></pre>
<p><strong>Examples of using</strong><code>cut</code><strong>for log parsing</strong></p>
<p>Assume you have a log file structured as follows, where fields are space-separated:</p>
<pre><code class="lang-bash">2024-04-25 08:23:01 INFO 192.168.1.10 User logged <span class="hljs-keyword">in</span> successfully.
2024-04-25 08:24:15 WARNING 192.168.1.10 Disk usage exceeds 90%.
2024-04-25 08:25:02 ERROR 10.0.0.5 Connection timed out.
...
</code></pre>
<p><code>cut</code> can be used in the following ways:</p>
<ol>
<li><strong>Extracting the time from each log entry</strong>:</li>
</ol>
<pre><code class="lang-bash">cut -d <span class="hljs-string">' '</span> -f 2 system.log

<span class="hljs-comment"># Output</span>
08:23:01
08:24:15
08:25:02
...
</code></pre>
<p>This command uses a space as a delimiter and selects the second field, which is the time component of each log entry.</p>
<ol start="2">
<li><strong>Extracting the IP addresses from the logs</strong>:</li>
</ol>
<pre><code class="lang-bash">cut -d <span class="hljs-string">' '</span> -f 4 system.log

<span class="hljs-comment"># Output</span>
192.168.1.10
192.168.1.10
10.0.0.5
</code></pre>
<p>This command extracts the fourth field, which is the IP address from each log entry.</p>
<ol start="3">
<li><strong>Extracting log levels (INFO, WARNING, ERROR)</strong>:</li>
</ol>
<pre><code class="lang-bash">cut -d <span class="hljs-string">' '</span> -f 3 system.log

<span class="hljs-comment"># Output</span>
INFO
WARNING
ERROR
</code></pre>
<p>This extracts the third field which contains the log level.</p>
<ol start="4">
<li><strong>Combining</strong><code>cut</code><strong>with other commands:</strong></li>
</ol>
<p>The output of other commands can be piped to the <code>cut</code> command. Let's say you want to filter logs before cutting. You can use <code>grep</code> to extract lines containing "ERROR" and then use <code>cut</code> to get specific information from those lines:</p>
<pre><code class="lang-bash">grep <span class="hljs-string">"ERROR"</span> system.log | cut -d <span class="hljs-string">' '</span> -f 1,2 

<span class="hljs-comment"># Output</span>
2024-04-25 08:25:02
</code></pre>
<p>This command first filters lines that include "ERROR", then extracts the date and time from these lines.</p>
<ol start="5">
<li><strong>Extracting multiple fields</strong>:</li>
</ol>
<p>It is possible to extract multiple fields at once by specifying a range or a comma-separated list of fields:</p>
<pre><code class="lang-bash">cut -d <span class="hljs-string">' '</span> -f 1,2,3 system.log` 

<span class="hljs-comment"># Output</span>
2024-04-25 08:23:01 INFO
2024-04-25 08:24:15 WARNING
2024-04-25 08:25:02 ERROR
...
</code></pre>
<p>The above command extracts the first three fields from each log entry that are date, time, and log level.</p>
<h4 id="heading-parsing-log-files-with-sort-and-uniq">Parsing log files with <code>sort</code> and <code>uniq</code></h4>
<p>Sorting and removing duplicates are common operations when working with log files. The <code>sort</code> and <code>uniq</code> commands are powerful commands used to sort and remove duplicates from the input, respectively.</p>
<p><strong>Basic syntax of sort</strong></p>
<p>The <code>sort</code> command organizes lines of text alphabetically or numerically.</p>
<pre><code class="lang-bash">sort [options] [file]
</code></pre>
<p>Some key options for the sort command:</p>
<ul>
<li><p><code>-n</code>: Sorts the file assuming the contents are numerical.</p>
</li>
<li><p><code>-r</code>: Reverses the order of sort.</p>
</li>
<li><p><code>-k</code>: Specifies a key or column number to sort on.</p>
</li>
<li><p><code>-u</code>: Sorts and removes duplicate lines.</p>
</li>
</ul>
<p>The <code>uniq</code> command is used to filter or count and report repeated lines in a file.</p>
<p>The syntax of <code>uniq</code> is:</p>
<pre><code class="lang-bash">uniq [options] [input_file] [output_file]
</code></pre>
<p>Some key options for the <code>uniq</code> command are:</p>
<ul>
<li><p><code>-c</code>: Prefixes lines by the number of occurrences.</p>
</li>
<li><p><code>-d</code>: Only prints duplicate lines.</p>
</li>
<li><p><code>-u</code>: Only prints unique lines.</p>
</li>
</ul>
<h4 id="heading-examples-of-using-sort-and-uniq-together-for-log-parsing">Examples of using <code>sort</code> and <code>uniq</code> together for log parsing</h4>
<p>Let's assume the following example log entries for these demonstrations:</p>
<pre><code class="lang-bash">2024-04-25 INFO User logged <span class="hljs-keyword">in</span> successfully.
2024-04-25 WARNING Disk usage exceeds 90%.
2024-04-26 ERROR Connection timed out.
2024-04-25 INFO User logged <span class="hljs-keyword">in</span> successfully.
2024-04-26 INFO Scheduled maintenance.
2024-04-26 ERROR Connection timed out.
</code></pre>
<ol>
<li><strong>Sorting log entries by date</strong>:</li>
</ol>
<pre><code class="lang-bash">sort system.log

<span class="hljs-comment"># Output</span>
2024-04-25 INFO User logged <span class="hljs-keyword">in</span> successfully.
2024-04-25 INFO User logged <span class="hljs-keyword">in</span> successfully.
2024-04-25 WARNING Disk usage exceeds 90%.
2024-04-26 ERROR Connection timed out.
2024-04-26 ERROR Connection timed out.
2024-04-26 INFO Scheduled maintenance.
</code></pre>
<p>This sorts the log entries alphabetically, which effectively sorts them by date if the date is the first field.</p>
<ol>
<li><strong>Sorting and removing duplicates</strong>:</li>
</ol>
<pre><code class="lang-bash">sort system.log | uniq

<span class="hljs-comment"># Output</span>
2024-04-25 INFO User logged <span class="hljs-keyword">in</span> successfully.
2024-04-25 WARNING Disk usage exceeds 90%.
2024-04-26 ERROR Connection timed out.
2024-04-26 INFO Scheduled maintenance.
</code></pre>
<p>This command sorts the log file and pipes it to <code>uniq</code>, removing duplicate lines.</p>
<ol>
<li><strong>Counting occurrences of each line</strong>:</li>
</ol>
<pre><code class="lang-bash">sort system.log | uniq -c

<span class="hljs-comment"># Output</span>
2 2024-04-25 INFO User logged <span class="hljs-keyword">in</span> successfully.
1 2024-04-25 WARNING Disk usage exceeds 90%.
2 2024-04-26 ERROR Connection timed out.
1 2024-04-26 INFO Scheduled maintenance.
</code></pre>
<p>Sorts the log entries and then counts each unique line. According to the output, the line <code>'2024-04-25 INFO User logged in successfully.'</code> appeared 2 times in the file.</p>
<ol>
<li><strong>Identifying unique log entries</strong>:</li>
</ol>
<pre><code class="lang-bash">sort system.log | uniq -u

<span class="hljs-comment"># Output</span>

2024-04-25 WARNING Disk usage exceeds 90%.
2024-04-26 INFO Scheduled maintenance.
</code></pre>
<p>This command shows lines that are unique.</p>
<ol start="2">
<li><strong>Sorting by log level</strong>:</li>
</ol>
<pre><code class="lang-bash">sort -k2 system.log

<span class="hljs-comment"># Output</span>
2024-04-26 ERROR Connection timed out.
2024-04-26 ERROR Connection timed out.
2024-04-25 INFO User logged <span class="hljs-keyword">in</span> successfully.
2024-04-25 INFO User logged <span class="hljs-keyword">in</span> successfully.
2024-04-26 INFO Scheduled maintenance.
2024-04-25 WARNING Disk usage exceeds 90%.
</code></pre>
<p>Sorts the entries based on the second field, which is the log level.</p>
<h3 id="heading-84-managing-linux-processes-via-command-line">8.4. Managing Linux Processes via Command Line</h3>
<p>A process is a running instance of a program. A process consists of:</p>
<ul>
<li><p>An address space of the allocated memory.</p>
</li>
<li><p>Process states.</p>
</li>
<li><p>Properties such as ownership, security attributes, and resource usage.</p>
</li>
</ul>
<p>A process also has an environment that consists of:</p>
<ul>
<li><p>Local and global variables</p>
</li>
<li><p>The current scheduling context</p>
</li>
<li><p>Allocated system resources, such as network ports or file descriptors.</p>
</li>
</ul>
<p>When you run the <code>ls -l</code> command, the operating system creates a new process to execute the command. The process has an ID, a state, and runs until the command completes.</p>
<h4 id="heading-understanding-process-creation-and-lifecycle">Understanding process creation and lifecycle</h4>
<p>In Ubuntu, all processes originate from the initial system process called <code>systemd</code>, which is the first process started by the kernel during boot.</p>
<p>The <code>systemd</code> process has a process ID (PID) of <code>1</code> and is responsible for initializing the system, starting and managing other processes, and handling system services. All other processes on the system are descendants of <code>systemd</code>.</p>
<p>A parent process duplicates its own address space (fork) to create a new (child) process structure. Each new process is assigned a unique process ID (PID) for tracking and security purposes. The PID and the parent's process ID (PPID) are part of the new process environment. Any process can create a child process.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719584071059/f24fac4b-18f3-4a39-8659-93d32c533256.png" alt="Process and its initialization to parent and child" class="image--center mx-auto" width="473" height="649" loading="lazy"></p>
<p>Through the fork routine, a child process inherits security identities, previous and current file descriptors, port and resource privileges, environment variables, and program code. A child process may then execute its own program code.</p>
<p>Typically, a parent process sleeps while the child process runs, setting a request (wait) to be notified when the child completes.</p>
<p>Upon exiting, the child process has already closed or discarded its resources and environment. The only remaining resource, known as a zombie, is an entry in the process table. The parent, signaled awake when the child exits, cleans the process table of the child's entry, thus freeing the last resource of the child process. The parent process then continues executing its own program code.</p>
<h4 id="heading-understanding-process-states">Understanding process states</h4>
<p>Processes in Linux assume different states during their lifecycle. The state of a process indicates what the process is currently doing and how it is interacting with the system. The processes transition between states based on their execution status and the system's scheduling algorithm.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719584116150/3054dfe2-c42c-4d62-9e12-e3aec479d53a.png" alt="Linux process states and transitions" class="image--center mx-auto" width="1079" height="742" loading="lazy"></p>
<p>The processes in a Linux system can be in one of the following states:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>State</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><strong>(new)</strong></td><td>Initial state when a process is created via a fork system call.</td></tr>
<tr>
<td><strong>Runnable (ready) (R)</strong></td><td>Process is ready to run and waiting to be scheduled on a CPU.</td></tr>
<tr>
<td><strong>Running (user) (R)</strong></td><td>Process is executing in user mode, running user applications.</td></tr>
<tr>
<td><strong>Running (kernel) (R)</strong></td><td>Process is executing in kernel mode, handling system calls or hardware interrupts.</td></tr>
<tr>
<td><strong>Sleeping (S)</strong></td><td>Process is waiting for an event (for example, I/O operation) to complete and can be easily awakened.</td></tr>
<tr>
<td><strong>Sleeping (uninterruptible) (D)</strong></td><td>Process is in an uninterruptible sleep state, waiting for a specific condition (usually I/O) to complete, and cannot be interrupted by signals.</td></tr>
<tr>
<td><strong>Sleeping (disk sleep) (K)</strong></td><td>Process is waiting for disk I/O operations to complete.</td></tr>
<tr>
<td><strong>Sleeping (idle) (I)</strong></td><td>Process is idle, not doing any work, and waiting for an event to occur.</td></tr>
<tr>
<td><strong>Stopped (T)</strong></td><td>Process execution has been stopped, typically by a signal, and can be resumed later.</td></tr>
<tr>
<td><strong>Zombie (Z)</strong></td><td>Process has completed execution but still has an entry in the process table, waiting for its parent to read its exit status.</td></tr>
</tbody>
</table>
</div><p>The processes transition between these states in the following ways:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Transition</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><strong>Fork</strong></td><td>Creates a new process from a parent process, transitioning from (new) to Runnable (ready) (R).</td></tr>
<tr>
<td><strong>Schedule</strong></td><td>Scheduler selects a runnable process, transitioning it to Running (user) or Running (kernel) state.</td></tr>
<tr>
<td><strong>Run</strong></td><td>Process transitions from Runnable (ready) (R) to Running (kernel) (R) when scheduled for execution.</td></tr>
<tr>
<td><strong>Preempt or Reschedule</strong></td><td>Process can be preempted or rescheduled, moving it back to Runnable (ready) (R) state.</td></tr>
<tr>
<td><strong>Syscall</strong></td><td>Process makes a system call, transitioning from Running (user) (R) to Running (kernel) (R).</td></tr>
<tr>
<td><strong>Return</strong></td><td>Process completes a system call and returns to Running (user) (R).</td></tr>
<tr>
<td><strong>Wait</strong></td><td>Process waits for an event, transitioning from Running (kernel) (R) to one of the Sleeping states (S, D, K, or I).</td></tr>
<tr>
<td><strong>Event or Signal</strong></td><td>Process is awakened by an event or signal, moving it from a Sleeping state back to Runnable (ready) (R).</td></tr>
<tr>
<td><strong>Suspend</strong></td><td>Process is suspended, transitioning from Running (kernel) or Runnable (ready) to Stopped (T).</td></tr>
<tr>
<td><strong>Resume</strong></td><td>Process is resumed, moving from Stopped (T) back to Runnable (ready) (R).</td></tr>
<tr>
<td><strong>Exit</strong></td><td>Process terminates, transitioning from Running (user) or Running (kernel) to Zombie (Z).</td></tr>
<tr>
<td><strong>Reap</strong></td><td>Parent process reads the exit status of the zombie process, removing it from the process table.</td></tr>
</tbody>
</table>
</div><h4 id="heading-how-to-view-processes">How to view processes</h4>
<p>You can use the <code>ps</code> command along with a combination of options to view processes on a Linux system. The <code>ps</code> command is used to display information about a selection of active processes. For example, <code>ps aux</code> displays all processes running on the system.</p>
<pre><code class="lang-bash">zaira@zaira:~$ ps aux
<span class="hljs-comment"># Output</span>
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root           1  0.0  0.0 168140 11352 ?        Ss   May21   0:18 /sbin/init splash
root           2  0.0  0.0      0     0 ?        S    May21   0:00 [kthreadd]
root           3  0.0  0.0      0     0 ?        I&lt;   May21   0:00 [rcu_gp]
root           4  0.0  0.0      0     0 ?        I&lt;   May21   0:00 [rcu_par_gp]
root           5  0.0  0.0      0     0 ?        I&lt;   May21   0:00 [slub_flushwq]
root           6  0.0  0.0      0     0 ?        I&lt;   May21   0:00 [netns]
root          11  0.0  0.0      0     0 ?        I&lt;   May21   0:00 [mm_percpu_wq]
root          12  0.0  0.0      0     0 ?        I    May21   0:00 [rcu_tasks_kthread]
root          13  0.0  0.0      0     0 ?        I    May21   0:00 [rcu_tasks_rude_kthread]
*... output truncated ....*
</code></pre>
<p>The output above shows a snapshot of the currently running processes on the system. Each row represents a process with the following columns:</p>
<ol>
<li><p><code>USER</code>: The user who owns the process.</p>
</li>
<li><p><code>PID</code>: The process ID.</p>
</li>
<li><p><code>%CPU</code>: The CPU usage of the process.</p>
</li>
<li><p><code>%MEM</code>: The memory usage of the process.</p>
</li>
<li><p><code>VSZ</code>: The virtual memory size of the process.</p>
</li>
<li><p><code>RSS</code>: The resident set size, that is the non-swapped physical memory that a task has used.</p>
</li>
<li><p><code>TTY</code>: The controlling terminal of the process. A <code>?</code> indicates no controlling terminal.</p>
</li>
<li><p><code>STAT</code>: The process state.</p>
<ul>
<li><p><code>R</code>: Running</p>
</li>
<li><p><code>I</code> or <code>S</code>: Interruptible sleep (waiting for an event to complete)</p>
</li>
<li><p><code>D</code>: Uninterruptible sleep (usually IO)</p>
</li>
<li><p><code>T</code>: Stopped (either by a job control signal or because it is being traced)</p>
</li>
<li><p><code>Z</code>: Zombie (terminated but not reaped by its parent)</p>
</li>
<li><p><code>Ss</code>: Session leader. This is a process that has started a session, and it is a leader of a group of processes and can control terminal signals. The first <code>S</code> indicates the sleeping state, and the second <code>s</code> indicates it is a session leader.</p>
</li>
</ul>
</li>
<li><p><code>START</code>: The starting time or date of the process.</p>
</li>
<li><p><code>TIME</code>: The cumulative CPU time.</p>
</li>
<li><p><code>COMMAND</code>: The command that started the process.</p>
</li>
</ol>
<h4 id="heading-background-and-foreground-processes">Background and foreground processes</h4>
<p>In this section, you'll learn how you can control jobs by running them in the background or foreground.</p>
<p>A job is a process that is started by a shell. When you run a command in the terminal, it is considered a job. A job can run in the foreground or the background.</p>
<p>To demonstrate control, you'll first create 3 processes and then run them in the background. After that, you'll list the processes and alternate them between the foreground and background. You'll see how to put them to sleep or exit completely.</p>
<ol>
<li>Create Three Processes</li>
</ol>
<p>Open a terminal and start three long-running processes. Use the <code>sleep</code> command, that keeps the process running for a specified number of seconds.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># run sleep command for 300, 400, and 500 seconds</span>
sleep 300 &amp;
sleep 400 &amp;
sleep 500 &amp;
</code></pre>
<p>The <code>&amp;</code> at the end of each command moves the process to the background.</p>
<ol start="2">
<li>Display Background Jobs</li>
</ol>
<p>Use the <code>jobs</code> command to display the list of background jobs.</p>
<pre><code class="lang-bash"><span class="hljs-built_in">jobs</span>
</code></pre>
<p>The output should look something like this:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">jobs</span>
[1]   Running                 sleep 300 &amp;
[2]-  Running                 sleep 400 &amp;
[3]+  Running                 sleep 500 &amp;
</code></pre>
<ol start="3">
<li>Bring a Background Job to the Foreground</li>
</ol>
<p>To bring a background job to the foreground, use the <code>fg</code> command followed by the job number. For example, to bring the first job (<code>sleep 300</code>) to the foreground:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">fg</span> %1
</code></pre>
<p>This will bring job <code>1</code> to the foreground.</p>
<ol start="4">
<li>Move the Foreground Job Back to the Background</li>
</ol>
<p>While the job is running in the foreground, you can suspend it and move it back to the background by pressing <code>Ctrl+Z</code> to suspend the job.</p>
<p>A suspended job will look like this:</p>
<pre><code class="lang-bash">zaira@zaira:~$ <span class="hljs-built_in">fg</span> %1
sleep 300

^Z
[1]+  Stopped                 sleep 300

zaira@zaira:~$ <span class="hljs-built_in">jobs</span>
<span class="hljs-comment"># suspended job </span>
[1]+  Stopped                 sleep 300
[2]   Running                 sleep 400 &amp;
[3]-  Running                 sleep 500 &amp;
</code></pre>
<p>Now use the <code>bg</code> command to resume the job with ID 1 in the background.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Press Ctrl+Z to suspend the foreground job</span>
<span class="hljs-comment"># Then, resume it in the background</span>
<span class="hljs-built_in">bg</span> %1
</code></pre>
<ol start="5">
<li>Display the jobs again</li>
</ol>
<pre><code class="lang-bash"><span class="hljs-built_in">jobs</span>
[1]   Running                 sleep 300 &amp;
[2]-  Running                 sleep 400 &amp;
[3]+  Running                 sleep 500 &amp;
</code></pre>
<p>In this exercise, you:</p>
<ul>
<li><p>Started three background processes using sleep commands.</p>
</li>
<li><p>Used jobs to display the list of background jobs.</p>
</li>
<li><p>Brought a job to the foreground with <code>fg %job_number</code>.</p>
</li>
<li><p>Suspended the job with <code>Ctrl+Z</code> and moved it back to the background with <code>bg %job_number</code>.</p>
</li>
<li><p>Used jobs again to verify the status of the background jobs.</p>
</li>
</ul>
<p>Now you know how to control jobs.</p>
<h4 id="heading-killing-processes">Killing processes</h4>
<p>It is possible to terminate an unresponsive or unwanted process using the <code>kill</code> command. The <code>kill</code> command sends a signal to a process ID, asking it to terminate.</p>
<p>A number of options are available with the <code>kill</code> command.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Options available with kill</span>

<span class="hljs-built_in">kill</span> -l
 1) SIGHUP     2) SIGINT     3) SIGQUIT     4) SIGILL     5) SIGTRAP
 6) SIGABRT     7) SIGBUS     8) SIGFPE     9) SIGKILL    10) SIGUSR1
11) SIGSEGV    12) SIGUSR2    13) SIGPIPE    14) SIGALRM    15) SIGTERM
16) SIGSTKFLT    17) SIGCHLD    18) SIGCONT    19) SIGSTOP    20) SIGTSTP
21) SIGTTIN    22) SIGTTOU    23) SIGURG    24) 
...terminated
</code></pre>
<p>Here are some examples of the <code>kill</code> command in Linux:</p>
<ol>
<li><p><strong>Kill a process by PID (Process ID):</strong></p>
<pre><code class="lang-bash"> <span class="hljs-built_in">kill</span> 1234
</code></pre>
<p> This command sends the default <code>SIGTERM</code> signal to the process with PID 1234, requesting it to terminate.</p>
</li>
<li><p><strong>Kill a process by name:</strong></p>
<pre><code class="lang-bash"> pkill process_name
</code></pre>
<p> This command sends the default <code>SIGTERM</code> signal to all processes with the specified name.</p>
</li>
<li><p><strong>Forcefully kill a process:</strong></p>
<pre><code class="lang-bash"> <span class="hljs-built_in">kill</span> -9 1234
</code></pre>
<p> This command sends the <code>SIGKILL</code> signal to the process with PID 1234, forcefully terminating it.</p>
</li>
<li><p><strong>Send a specific signal to a process:</strong></p>
<pre><code class="lang-bash"> <span class="hljs-built_in">kill</span> -s SIGSTOP 1234
</code></pre>
<p> This command sends the <code>SIGSTOP</code> signal to the process with PID 1234, stopping it.</p>
</li>
<li><p><strong>Kill all processes owned by a specific user:</strong></p>
<pre><code class="lang-bash"> pkill -u username
</code></pre>
<p> This command sends the default <code>SIGTERM</code> signal to all processes owned by the specified user.</p>
</li>
</ol>
<p>These examples demonstrate various ways to use the <code>kill</code> command to manage processes in a Linux environment.</p>
<p>Here is the information about the <code>kill</code> command options and signals in a tabular form: This table summarizes the most common <code>kill</code> command options and signals used in Linux for managing processes.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Command / Option</td><td>Signal</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>kill &lt;pid&gt;</code></td><td><code>SIGTERM</code></td><td>Requests the process to terminate gracefully (default signal).</td></tr>
<tr>
<td><code>kill -9 &lt;pid&gt;</code></td><td><code>SIGKILL</code></td><td>Forces the process to terminate immediately without cleanup.</td></tr>
<tr>
<td><code>kill -SIGKILL &lt;pid&gt;</code></td><td><code>SIGKILL</code></td><td>Forces the process to terminate immediately without cleanup.</td></tr>
<tr>
<td><code>kill -15 &lt;pid&gt;</code></td><td><code>SIGTERM</code></td><td>Explicitly sends the <code>SIGTERM</code> signal to request graceful termination.</td></tr>
<tr>
<td><code>kill -SIGTERM &lt;pid&gt;</code></td><td><code>SIGTERM</code></td><td>Explicitly sends the <code>SIGTERM</code> signal to request graceful termination.</td></tr>
<tr>
<td><code>kill -1 &lt;pid&gt;</code></td><td><code>SIGHUP</code></td><td>Traditionally means "hang up"; can be used to reload configuration files.</td></tr>
<tr>
<td><code>kill -SIGHUP &lt;pid&gt;</code></td><td><code>SIGHUP</code></td><td>Traditionally means "hang up"; can be used to reload configuration files.</td></tr>
<tr>
<td><code>kill -2 &lt;pid&gt;</code></td><td><code>SIGINT</code></td><td>Requests the process to terminate (same as pressing <code>Ctrl+C</code> in terminal).</td></tr>
<tr>
<td><code>kill -SIGINT &lt;pid&gt;</code></td><td><code>SIGINT</code></td><td>Requests the process to terminate (same as pressing <code>Ctrl+C</code> in terminal).</td></tr>
<tr>
<td><code>kill -3 &lt;pid&gt;</code></td><td><code>SIGQUIT</code></td><td>Causes the process to terminate and produce a core dump for debugging.</td></tr>
<tr>
<td><code>kill -SIGQUIT &lt;pid&gt;</code></td><td><code>SIGQUIT</code></td><td>Causes the process to terminate and produce a core dump for debugging.</td></tr>
<tr>
<td><code>kill -19 &lt;pid&gt;</code></td><td><code>SIGSTOP</code></td><td>Pauses the process.</td></tr>
<tr>
<td><code>kill -SIGSTOP &lt;pid&gt;</code></td><td><code>SIGSTOP</code></td><td>Pauses the process.</td></tr>
<tr>
<td><code>kill -18 &lt;pid&gt;</code></td><td><code>SIGCONT</code></td><td>Resumes a paused process.</td></tr>
<tr>
<td><code>kill -SIGCONT &lt;pid&gt;</code></td><td><code>SIGCONT</code></td><td>Resumes a paused process.</td></tr>
<tr>
<td><code>killall &lt;name&gt;</code></td><td>Varies</td><td>Sends a signal to all processes with the given name.</td></tr>
<tr>
<td><code>killall -9 &lt;name&gt;</code></td><td><code>SIGKILL</code></td><td>Force kills all processes with the given name.</td></tr>
<tr>
<td><code>pkill &lt;pattern&gt;</code></td><td>Varies</td><td>Sends a signal to processes based on a pattern match.</td></tr>
<tr>
<td><code>pkill -9 &lt;pattern&gt;</code></td><td><code>SIGKILL</code></td><td>Force kills all processes matching the pattern.</td></tr>
<tr>
<td><code>xkill</code></td><td><code>SIGKILL</code></td><td>Graphical utility that allows clicking on a window to kill the corresponding process.</td></tr>
</tbody>
</table>
</div><h3 id="heading-85-standard-input-and-output-streams-in-linux">8.5. Standard Input and Output Streams in Linux</h3>
<p>Reading an input and writing an output is an essential part of understanding the command line and shell scripting. In Linux, every process has three default streams:</p>
<ol>
<li><p>Standard Input (<code>stdin</code>): This stream is used for input, typically from the keyboard. When a program reads from <code>stdin</code>, it receives data entered by the user or redirected from a file. A file descriptor is a unique identifier that the operating system assigns to an open file in order to keep track of open files.</p>
<p> The file descriptor for <code>stdin</code> is <code>0</code>.</p>
</li>
<li><p>Standard Output (<code>stdout</code>): This is the default output stream where a process writes its output. By default, the standard output is the terminal. The output can also be redirected to a file or another program. The file descriptor for <code>stdout</code> is <code>1</code>.</p>
</li>
<li><p>Standard Error (<code>stderr</code>): This is the default error stream where a process writes its error messages. By default, the standard error is the terminal, allowing error messages to be seen even if <code>stdout</code> is redirected. The file descriptor for <code>stderr</code> is <code>2</code>.</p>
</li>
</ol>
<h4 id="heading-redirection-and-pipelines">Redirection and Pipelines</h4>
<p><strong>Redirection:</strong> You can redirect the error and output streams to files or other commands. For example:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Redirecting stdout to a file</span>
ls &gt; output.txt

<span class="hljs-comment"># Redirecting stderr to a file</span>
ls non_existent_directory 2&gt; error.txt

<span class="hljs-comment"># Redirecting both stdout and stderr to a file</span>
ls non_existent_directory &gt; all_output.txt 2&gt;&amp;1
</code></pre>
<p>In the last command,</p>
<ul>
<li><p><code>ls non_existent_directory</code>: lists the contents of a directory named non_existent_directory. Since this directory does not exist, <code>ls</code> will generate an error message.</p>
</li>
<li><p><code>&gt; all_output.txt</code>: The <code>&gt;</code> operator redirects the standard output (<code>stdout</code>) of the <code>ls</code> command to the file <code>all_output.txt</code>. If the file does not exist, it will be created. If it does exist, its contents will be overwritten.</p>
</li>
<li><p><code>2&gt;&amp;1:</code>: Here, <code>2</code> represents the file descriptor for standard error (<code>stderr</code>). <code>&amp;1</code> represents the file descriptor for standard output (<code>stdout</code>). The <code>&amp;</code> character is used to specify that <code>1</code> is not the file name but a file descriptor.</p>
</li>
</ul>
<p>So, <code>2&gt;&amp;1</code> means "redirect stderr (2) to wherever stdout (1) is currently going," which in this case is the file <code>all_output.txt</code>. Therefore, both the output (if there were any) and the error message from <code>ls</code> will be written to <code>all_output.txt</code>.</p>
<p><strong>Pipelines:</strong></p>
<p>You can use pipes (<code>|</code>) to pass the output of one command as the input to another:</p>
<pre><code class="lang-bash">ls | grep image
<span class="hljs-comment"># Output</span>
image-10.png
image-11.png
image-12.png
image-13.png
... Output truncated ...
</code></pre>
<h3 id="heading-86-automation-in-linux-automate-tasks-with-cron-jobs">8.6 Automation in Linux – Automate Tasks with Cron Jobs</h3>
<p>Cron is a powerful utility for job scheduling that is available in Unix-like operating systems. By configuring cron, you can set up automated jobs to run on a daily, weekly, monthly, or other specific time basis. The automation capabilities provided by cron play a crucial role in Linux system administration.</p>
<p>The <code>crond</code> daemon (a type of computer program that runs in the background) enables cron functionality. The cron reads the <strong>crontab</strong> (cron tables) for running predefined scripts.</p>
<p>By using a specific syntax, you can configure a cron job to schedule scripts or other commands to run automatically.</p>
<p><strong>What are cron jobs in Linux?</strong></p>
<p>Any task that you schedule through crons is called a cron job.</p>
<p>Now, let's see how cron jobs work.</p>
<h4 id="heading-how-to-control-access-to-crons">How to control access to crons</h4>
<p>In order to use cron jobs, an admin needs to allow cron jobs to be added for users in the <code>/etc/cron.allow</code> file.</p>
<p>If you get a prompt like this, it means you don't have permission to use cron.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/11/image-51.png" alt="Cron job addition denied for user John." width="600" height="400" loading="lazy"></p>
<p>To allow John to use crons, include his name in <code>/etc/cron.allow</code>. Create the file if it doesn't exist. This will allow John to create and edit cron jobs.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/11/image-52.png" alt="Allowing John in file cron.allow" width="600" height="400" loading="lazy"></p>
<p>Users can also be denied access to cron job access by entering their usernames in the file <code>/etc/cron.d/cron.deny</code>.</p>
<h4 id="heading-how-to-add-cron-jobs-in-linux">How to add cron jobs in Linux</h4>
<p>First, to use cron jobs, you'll need to check the status of the cron service. If cron is not installed, you can easily download it through the package manager. Just use this to check:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Check cron service on Linux system</span>
sudo systemctl status cron.service
</code></pre>
<h4 id="heading-cron-job-syntax">Cron job syntax</h4>
<p>Crontabs use the following flags for adding and listing cron jobs:</p>
<ul>
<li><p><code>crontab -e</code>: edits crontab entries to add, delete, or edit cron jobs.</p>
</li>
<li><p><code>crontab -l</code>: list all the cron jobs for the current user.</p>
</li>
<li><p><code>crontab -u username -l</code>: list another user's crons.</p>
</li>
<li><p><code>crontab -u username -e</code>: edit another user's crons.</p>
</li>
</ul>
<p>When you list crons and they exist, you'll see something like this:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Cron job example</span>
* * * * * sh /path/to/script.sh
</code></pre>
<p>In the above example,</p>
<ul>
<li><code>*</code> represents minute(s) hour(s) day(s) month(s) weekday(s), respectively. See details of these values below:</li>
</ul>
<div class="hn-table">
<table>
<thead>
<tr>
<td></td><td><strong>VALUE</strong></td><td><strong>DESCRIPTION</strong></td></tr>
</thead>
<tbody>
<tr>
<td>Minutes</td><td>0-59</td><td>Command will be executed at the specific minute.</td></tr>
<tr>
<td>Hours</td><td>0-23</td><td>Command will be executed at the specific hour.</td></tr>
<tr>
<td>Days</td><td>1-31</td><td>Commands will be executed in these days of the months.</td></tr>
<tr>
<td>Months</td><td>1-12</td><td>The month in which tasks need to be executed.</td></tr>
<tr>
<td>Weekdays</td><td>0-6</td><td>Days of the week where commands will run. Here, 0 is Sunday.</td></tr>
</tbody>
</table>
</div><ul>
<li><p><code>sh</code> represents that the script is a bash script and should be run from <code>/bin/bash</code>.</p>
</li>
<li><p><code>/path/to/script.sh</code> specifies the path to the script.</p>
</li>
</ul>
<p>Below is a summary of the cron job syntax:</p>
<pre><code class="lang-markdown"><span class="hljs-bullet">*</span>   <span class="hljs-emphasis">*   *</span>   <span class="hljs-emphasis">*   *</span>  sh /path/to/script/script.sh
|   |   |   |   |              |
|   |   |   |   |      Command or Script to Execute        
|   |   |   |   |
|   |   |   |   |
|   |   |   |   |
|   |   |   | Day of the Week(0-6)
|   |   |   |
|   |   | Month of the Year(1-12)
|   |   |
|   | Day of the Month(1-31)  
|   |
| Hour(0-23)  
|
Min(0-59)
</code></pre>
<h4 id="heading-cron-job-examples">Cron job examples</h4>
<p>Below are some examples of scheduling cron jobs.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>SCHEDULE</strong></td><td><strong>SCHEDULED VALUE</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>5 0 * 8 *</code></td><td>At 00:05 in August.</td></tr>
<tr>
<td><code>5 4 * * 6</code></td><td>At 04:05 on Saturday.</td></tr>
<tr>
<td><code>0 22 * * 1-5</code></td><td>At 22:00 on every day-of-week from Monday through Friday.</td></tr>
</tbody>
</table>
</div><p>It's okay if you are unable to grasp this all at once. You can practice and generate cron schedules with the <a target="_blank" href="https://crontab.guru/">crontab guru</a> website.</p>
<h4 id="heading-how-to-set-up-a-cron-job">How to set up a cron job</h4>
<p>In this section, we will look at an example of how to schedule a simple script with a cron job.</p>
<ol>
<li>Create a script called <code>date-script.sh</code> which prints the system date and time and appends it to a file. The script is shown below:</li>
</ol>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>

<span class="hljs-built_in">echo</span> `date` &gt;&gt; date-out.txt
</code></pre>
<p>2.  Make the script executable by giving it execution rights.</p>
<pre><code class="lang-bash">chmod 775 date-script.sh
</code></pre>
<p>3.  Add the script in the crontab using <code>crontab -e</code>.</p>
<p>Here, we have scheduled it to run per minute.</p>
<pre><code class="lang-bash">*/1 * * * * /bin/sh /root/date-script.sh
</code></pre>
<p>4.  Check the output of the file <code>date-out.txt</code>. According to the script, the system date should be printed to this file every minute.</p>
<pre><code class="lang-bash">cat date-out.txt
<span class="hljs-comment"># output</span>
Wed 26 Jun 16:59:33 PKT 2024
Wed 26 Jun 17:00:01 PKT 2024
Wed 26 Jun 17:01:01 PKT 2024
Wed 26 Jun 17:02:01 PKT 2024
Wed 26 Jun 17:03:01 PKT 2024
Wed 26 Jun 17:04:01 PKT 2024
Wed 26 Jun 17:05:01 PKT 2024
Wed 26 Jun 17:06:01 PKT 2024
Wed 26 Jun 17:07:01 PKT 2024
</code></pre>
<p><strong>How to troubleshoot crons</strong></p>
<p>Crons are really helpful, but they might not always work as intended. Fortunately, there are some effective methods you can use to troubleshoot them.</p>
<p><strong>1. Check the schedule.</strong></p>
<p>First, you can try verifying the schedule that's set for the cron. You can do that with the syntax you saw in the above sections.</p>
<p><strong>2</strong>. <strong>Check cron logs.</strong></p>
<p>First, you need to check if the cron has run at the intended time or not. In Ubuntu, you can verify this from the cron logs located at <code>/var/log/syslog</code>.</p>
<p>If there is an entry in these logs at the correct time, it means the cron has run according to the schedule you set.</p>
<p>Below are the logs of our cron job example. Note the first column which shows the timestamp. The path of the script is also mentioned at the end of the line. Line #1, 3, and 5 show that the script ran as intended.</p>
<pre><code class="lang-bash">1 Jun 26 17:02:01 zaira-ThinkPad CRON[27834]: (zaira) CMD (/bin/sh /home/zaira/date-script.sh)
2 Jun 26 17:02:02 zaira-ThinkPad systemd[2094]: Started Tracker metadata extractor.
3 Jun 26 17:03:01 zaira-ThinkPad CRON[28255]: (zaira) CMD (/bin/sh /home/zaira/date-script.sh)
4 Jun 26 17:03:02 zaira-ThinkPad systemd[2094]: Started Tracker metadata extractor.
5 Jun 26 17:04:01 zaira-ThinkPad CRON[28538]: (zaira) CMD (/bin/sh /home/zaira/date-script.sh)
</code></pre>
<p><strong>3. Redirect cron output to a file.</strong></p>
<p>You can redirect a cron's output to a file and check the file for any possible errors.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Redirect cron output to a file</span>
* * * * * sh /path/to/script.sh &amp;&gt; log_file.log
</code></pre>
<h3 id="heading-87-linux-networking-basics">8.7. Linux Networking Basics</h3>
<p>Linux offers a number of commands to view network related information. In this section we will briefly discuss some of the commands.</p>
<h4 id="heading-view-network-interfaces-with-ifconfig">View network interfaces with <code>ifconfig</code></h4>
<p>The <code>ifconfig</code> command gives information about network interfaces. Here is an example output:</p>
<pre><code class="lang-bash">ifconfig

<span class="hljs-comment"># Output</span>
eth0: flags=4163&lt;UP,BROADCAST,RUNNING,MULTICAST&gt;  mtu 1500
        inet 192.168.1.100  netmask 255.255.255.0  broadcast 192.168.1.255
        inet6 fe80::a00:27ff:fe4e:66a1  prefixlen 64  scopeid 0x20&lt;link&gt;
        ether 08:00:27:4e:66:a1  txqueuelen 1000  (Ethernet)
        RX packets 1024  bytes 654321 (654.3 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 512  bytes 123456 (123.4 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73&lt;UP,LOOPBACK,RUNNING&gt;  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10&lt;host&gt;
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 256  bytes 20480 (20.4 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 256  bytes 20480 (20.4 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
</code></pre>
<p>The output of the <code>ifconfig</code> command shows the network interfaces configured on the system, along with details such as IP addresses, MAC addresses, packet statistics, and more.</p>
<p>These interfaces can be physical or virtual devices.</p>
<p>To extract IPv4 and IPv6 addresses, you can use <code>ip -4 addr</code> and <code>ip -6 addr</code>, respectively.</p>
<p><strong>View network activity with</strong><code>netstat</code></p>
<p>The <code>netstat</code> command shows network activity and stats by giving the following information:</p>
<p>Here are some examples of using the <code>netstat</code> command in the command line:</p>
<ol>
<li><p><strong>Display all listening and non-listening sockets:</strong></p>
<pre><code class="lang-bash"> netstat -a
</code></pre>
</li>
<li><p><strong>Show only listening ports:</strong></p>
<pre><code class="lang-bash"> netstat -l
</code></pre>
</li>
<li><p><strong>Display network statistics:</strong></p>
<pre><code class="lang-bash"> netstat -s
</code></pre>
</li>
<li><p><strong>Show routing table:</strong></p>
<pre><code class="lang-bash"> netstat -r
</code></pre>
</li>
<li><p><strong>Display TCP connections:</strong></p>
<pre><code class="lang-bash"> netstat -t
</code></pre>
</li>
<li><p><strong>Display UDP connections:</strong></p>
<pre><code class="lang-bash"> netstat -u
</code></pre>
</li>
<li><p><strong>Show network interfaces:</strong></p>
<pre><code class="lang-bash"> netstat -i
</code></pre>
</li>
<li><p><strong>Display PID and program names for connections:</strong></p>
<pre><code class="lang-bash"> netstat -p
</code></pre>
</li>
<li><p><strong>Show statistics for a specific protocol (for example, TCP):</strong></p>
<pre><code class="lang-bash"> netstat -st
</code></pre>
</li>
<li><p><strong>Display extended information:</strong></p>
<pre><code class="lang-bash">netstat -e
</code></pre>
</li>
</ol>
<h4 id="heading-check-network-connectivity-between-two-devices-using-ping">Check network connectivity between two devices using <code>ping</code></h4>
<p><code>ping</code> is used to test network connectivity between two devices. It sends ICMP packets to the target device and waits for a response.</p>
<pre><code class="lang-bash">ping google.com
</code></pre>
<p><code>ping</code> tests if you get a response back without getting a timeout.</p>
<pre><code class="lang-bash">ping google.com
PING google.com (142.250.181.46) 56(84) bytes of data.
64 bytes from fjr04s06-in-f14.1e100.net (142.250.181.46): icmp_seq=1 ttl=60 time=78.3 ms
64 bytes from fjr04s06-in-f14.1e100.net (142.250.181.46): icmp_seq=2 ttl=60 time=141 ms
64 bytes from fjr04s06-in-f14.1e100.net (142.250.181.46): icmp_seq=3 ttl=60 time=205 ms
64 bytes from fjr04s06-in-f14.1e100.net (142.250.181.46): icmp_seq=4 ttl=60 time=100 ms
^C
--- google.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3001ms
rtt min/avg/max/mdev = 78.308/131.053/204.783/48.152 ms
</code></pre>
<p>You can stop the response with <code>Ctrl + C</code>.</p>
<h4 id="heading-testing-endpoints-with-the-curl-command">Testing endpoints with the <code>curl</code> command</h4>
<p>The <code>curl</code> command stands for "client URL". It is used to transfer data to or from a server. It can also be used to test API endpoints that helps in troubleshooting system and application errors.</p>
<p>As an example, you can use <a target="_blank" href="http://www.official-joke-api.appspot.com/"><code>http://www.official-joke-api.appspot.com/</code></a> to experiment with the <code>curl</code> command.</p>
<ul>
<li>The <code>curl</code> command without any options uses the GET method by default.</li>
</ul>
<pre><code class="lang-bash">curl http://www.official-joke-api.appspot.com/random_joke
{<span class="hljs-string">"type"</span>:<span class="hljs-string">"general"</span>,
<span class="hljs-string">"setup"</span>:<span class="hljs-string">"What did the fish say when it hit the wall?"</span>,<span class="hljs-string">"punchline"</span>:<span class="hljs-string">"Dam."</span>,<span class="hljs-string">"id"</span>:1}
</code></pre>
<ul>
<li><code>curl -o</code> saves the output to the mentioned file.</li>
</ul>
<pre><code class="lang-bash">curl -o random_joke.json http://www.official-joke-api.appspot.com/random_joke
<span class="hljs-comment"># saves the output to random_joke.json</span>
</code></pre>
<ul>
<li><code>curl -I</code> fetches only the headers.</li>
</ul>
<pre><code class="lang-bash">curl -I http://www.official-joke-api.appspot.com/random_joke
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Vary: Accept-Encoding
X-Powered-By: Express
Access-Control-Allow-Origin: *
ETag: W/<span class="hljs-string">"71-NaOSpKuq8ChoxdHD24M0lrA+JXA"</span>
X-Cloud-Trace-Context: 2653a86b36b8b131df37716f8b2dd44f
Content-Length: 113
Date: Thu, 06 Jun 2024 10:11:50 GMT
Server: Google Frontend
</code></pre>
<h3 id="heading-88-linux-troubleshooting-tools-and-techniques">8.8. Linux Troubleshooting: Tools and Techniques</h3>
<h4 id="heading-system-activity-report-with-sar">System activity report with <code>sar</code></h4>
<p>The <code>sar</code> command in Linux is a powerful tool for collecting, reporting, and saving system activity information. It's part of the <code>sysstat</code> package and is widely used for monitoring system performance over time.</p>
<p>To use <code>sar</code> you first need to install <code>syssstat</code> using <code>sudo apt install sysstat</code>.</p>
<p>Once installed, start the service with <code>sudo systemctl start sysstat</code>.</p>
<p>Verify the status with <code>sudo systemctl status sysstat</code>.</p>
<p>Once the status is active, the system will start collecting various stats that you can use to access and analyze historical data. We'll see that in detail soon.</p>
<p>The syntax of the <code>sar</code> command is as follows:</p>
<pre><code class="lang-bash">sar [options] [interval] [count]
</code></pre>
<p>For example, <code>sar -u 1 3</code> will display CPU utilization statistics every second for three times.</p>
<pre><code class="lang-bash">sar -u 1 3
<span class="hljs-comment"># Output</span>
Linux 6.5.0-28-generic (zaira-ThinkPad)     04/06/24     _x86_64_    (12 CPU)

19:09:26        CPU     %user     %nice   %system   %iowait    %steal     %idle
19:09:27        all      3.78      0.00      2.18      0.08      0.00     93.96
19:09:28        all      4.02      0.00      2.01      0.08      0.00     93.89
19:09:29        all      6.89      0.00      2.10      0.00      0.00     91.01
Average:        all      4.89      0.00      2.10      0.06      0.00     92.95
</code></pre>
<p>Here are some common use cases and examples of how to use the <code>sar</code> command.</p>
<p><code>sar</code> can be used for a variety of purposes:</p>
<h5 id="heading-1-memory-usage">1. Memory usage</h5>
<p>To check memory usage (free and used), use:</p>
<pre><code class="lang-bash">sar -r 1 3

Linux 6.5.0-28-generic (zaira-ThinkPad)     04/06/24     _x86_64_    (12 CPU)

19:10:46    kbmemfree   kbavail kbmemused  %memused kbbuffers  kbcached  kbcommit   %commit  kbactive   kbinact   kbdirty
19:10:47      4600104   8934352   5502124     36.32    375844   4158352  15532012     65.99   6830564   2481260       264
19:10:48      4644668   8978940   5450252     35.98    375852   4165648  15549184     66.06   6776388   2481284        36
19:10:49      4646548   8980860   5448328     35.97    375860   4165648  15549224     66.06   6774368   2481292       116
Average:      4630440   8964717   5466901     36.09    375852   4163216  15543473     66.04   6793773   2481279       139
</code></pre>
<p>This command displays memory statistics every second three times.</p>
<h5 id="heading-2-swap-space-utilization">2. Swap space utilization</h5>
<p>To view swap space utilization statistics, use:</p>
<pre><code class="lang-bash">sar -S 1 3

sar -S 1 3
Linux 6.5.0-28-generic (zaira-ThinkPad)     04/06/24     _x86_64_    (12 CPU)

19:11:20    kbswpfree kbswpused  %swpused  kbswpcad   %swpcad
19:11:21      8388604         0      0.00         0      0.00
19:11:22      8388604         0      0.00         0      0.00
19:11:23      8388604         0      0.00         0      0.00
Average:      8388604         0      0.00         0      0.00
</code></pre>
<p>This command helps monitor the swap usage, which is crucial for systems running out of physical memory.</p>
<h5 id="heading-3-io-devices-load">3. I/O devices load</h5>
<p>To report activity for block devices and block device partitions:</p>
<pre><code class="lang-bash">sar -d 1 3
</code></pre>
<p>This command provides detailed stats about data transfers to and from block devices, and is useful for diagnosing I/O bottlenecks.</p>
<h5 id="heading-5-network-statistics">5. Network statistics</h5>
<p>To view network statistics, like number of packets received (transmitted) by the network interface:</p>
<pre><code class="lang-bash">sar -n DEV 1 3
<span class="hljs-comment"># -n DEV tells sar to report network device interfaces</span>
sar -n DEV 1 3
Linux 6.5.0-28-generic (zaira-ThinkPad)     04/06/24     _x86_64_    (12 CPU)

19:12:47        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
19:12:48           lo      0.00      0.00      0.00      0.00      0.00      0.00      0.00      0.00
19:12:48       enp2s0      0.00      0.00      0.00      0.00      0.00      0.00      0.00      0.00
19:12:48       wlp3s0     10.00      3.00      1.83      0.37      0.00      0.00      0.00      0.00
19:12:48    br-5129d04f972f      0.00      0.00      0.00      0.00      0.00      0.00      0.00      0.00
.
.
.

Average:        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
Average:           lo      0.00      0.00      0.00      0.00      0.00      0.00      0.00      0.00
Average:       enp2s0      0.00      0.00      0.00      0.00      0.00      0.00      0.00      0.00
...output truncated...
</code></pre>
<p>This displays network statistics every second for three seconds, helping in monitoring network traffic.</p>
<h5 id="heading-6-historical-data">6. Historical data</h5>
<p>Recall that previously we installed the <code>sysstat</code> package and ran the service. Follow the steps below to enable and access historical data.</p>
<ol>
<li><p><strong>Enable data collection:</strong> Edit the <code>sysstat</code> configuration file to enable data collection.</p>
<pre><code class="lang-bash"> sudo nano /etc/default/sysstat
</code></pre>
<p> Change <code>ENABLED="false"</code> to <code>ENABLED="true"</code>.</p>
<pre><code class="lang-bash"> vim /etc/default/sysstat
 <span class="hljs-comment">#</span>
 <span class="hljs-comment"># Default settings for /etc/init.d/sysstat, /etc/cron.d/sysstat</span>
 <span class="hljs-comment"># and /etc/cron.daily/sysstat files</span>
 <span class="hljs-comment">#</span>

 <span class="hljs-comment"># Should sadc collect system activity informations? Valid values</span>
 <span class="hljs-comment"># are "true" and "false". Please do not put other values, they</span>
 <span class="hljs-comment"># will be overwritten by debconf!</span>
 ENABLED=<span class="hljs-string">"true"</span>
</code></pre>
</li>
<li><p><strong>Configure data collection interval:</strong> Edit the cron job configuration to set the data collection interval.</p>
<pre><code class="lang-bash"> sudo nano /etc/cron.d/sysstat
</code></pre>
<p> By default, it collects data every 10 minutes. You can adjust the interval by modifying the cron job schedule. The relevant files will go to the <code>/var/log/sysstat</code> folder.</p>
</li>
<li><p><strong>View historical data:</strong> Use the <code>sar</code> command to view historical data. For example, to view CPU usage for the current day:</p>
<pre><code class="lang-bash"> sar -u
</code></pre>
<p> To view data from a specific date:</p>
<pre><code class="lang-bash"> sar -u -f /var/<span class="hljs-built_in">log</span>/sysstat/sa&lt;DD&gt;
</code></pre>
<p> Replace <code>&lt;DD&gt;</code> with the day of the month for which you want to view the data.</p>
<p> In the below command, <code>/var/log/sysstat/sa04</code> gives stats for the 4th day of the current month.</p>
</li>
</ol>
<pre><code class="lang-bash">sar -u -f /var/<span class="hljs-built_in">log</span>/sysstat/sa04
Linux 6.5.0-28-generic (zaira-ThinkPad)     04/06/24     _x86_64_    (12 CPU)

15:20:49     LINUX RESTART    (12 CPU)

16:13:30     LINUX RESTART    (12 CPU)

18:16:00        CPU     %user     %nice   %system   %iowait    %steal     %idle
18:16:01        all      0.25      0.00      0.67      0.08      0.00     99.00
Average:        all      0.25      0.00      0.67      0.08      0.00     99.00
</code></pre>
<h5 id="heading-7-real-time-cpu-interruptions">7. Real-Time CPU Interruptions</h5>
<p>To observe real-time interrupts per second served by the CPU, use this command:</p>
<pre><code class="lang-bash">sar -I SUM 1 3

<span class="hljs-comment"># Output</span>
Linux 6.5.0-28-generic (zaira-ThinkPad)     04/06/24     _x86_64_    (12 CPU)

19:14:22         INTR    intr/s
19:14:23          sum   5784.00
19:14:24          sum   5694.00
19:14:25          sum   5795.00
Average:          sum   5757.67
</code></pre>
<p>This command helps in monitoring how frequently the CPU is handling interrupts, which can be crucial for real-time performance tuning.</p>
<p>These examples illustrate how you can use <code>sar</code> to monitor various aspects of system performance. Regular use of <code>sar</code> can help in identifying system bottlenecks and ensuring that applications keep running efficiently.</p>
<h3 id="heading-89-general-troubleshooting-strategy-for-servers">8.9. General Troubleshooting Strategy for Servers</h3>
<p><strong>Why do we need to understand monitoring?</strong></p>
<p>System monitoring is an important aspect of system administration. Critical applications demand a high level of proactiveness to prevent failure and reduce the outage impact.</p>
<p>Linux offers very powerful tools to gauge system health. In this section, you'll learn about the various methods available to check your system's health and identify the bottlenecks.</p>
<h4 id="heading-find-load-average-and-system-uptime">Find load average and system uptime</h4>
<p>System reboots may occur which can sometimes mess up some configurations. To check how long the machine has been up, use the command: <code>uptime</code>. In addition to the uptime, the command also displays load average.</p>
<pre><code class="lang-bash">[user@host ~]$ uptime 19:15:00 up 1:04, 0 users, load average: 2.92, 4.48, 5.20
</code></pre>
<p>Load average is the system load over the last 1, 5, and 15 minutes. A quick glance indicates whether the system load appears to be increasing or decreasing over time.</p>
<p>Note: Ideal CPU queue is <code>0</code>. This is only possible when there are no waiting queues for the CPU.</p>
<p>Per-CPU load can be calculated by dividing load average with the total number of CPUs available.</p>
<p>To find the number of CPUs, use the command <code>lscpu.</code></p>
<pre><code class="lang-bash">lscpu
<span class="hljs-comment"># output</span>
Architecture:            x86_64
  CPU op-mode(s):        32-bit, 64-bit
  Address sizes:         48 bits physical, 48 bits virtual
  Byte Order:            Little Endian
CPU(s):                  12
  On-line CPU(s) list:   0-11
.
.
.
output omitted
</code></pre>
<p>If the load average seems to increase and does not come down, the CPUs are overloaded. There is some process that is stuck or there is a memory leakage.</p>
<h4 id="heading-calculating-free-memory">Calculating free memory</h4>
<p>Sometimes, high memory utilization might be causing problems. To check the available memory and the memory in use, use the <code>free</code> command.</p>
<pre><code class="lang-bash">free -mh
<span class="hljs-comment"># output</span>
               total        used        free      shared  buff/cache   available
Mem:            14Gi       3.5Gi       7.7Gi       109Mi       3.2Gi        10Gi
Swap:          8.0Gi          0B       8.0Gi
</code></pre>
<h4 id="heading-calculating-disk-space">Calculating disk space</h4>
<p>To ensure the system is healthy, don't forget about the disk space. To list all the available mount points and their respective used percentage, use the below command. Ideally, utilized disk spaces should not exceed 80%.</p>
<p>The <code>df</code> command provides detailed disk spaces.</p>
<pre><code class="lang-bash">df -h
Filesystem      Size  Used Avail Use% Mounted on
tmpfs           1.5G  2.4M  1.5G   1% /run
/dev/nvme0n1p2  103G   34G   65G  35% /
tmpfs           7.3G   42M  7.2G   1% /dev/shm
tmpfs           5.0M  4.0K  5.0M   1% /run/lock
efivarfs        246K   93K  149K  39% /sys/firmware/efi/efivars
/dev/nvme0n1p3  130G   47G   77G  39% /home
/dev/nvme0n1p1  511M  6.1M  505M   2% /boot/efi
tmpfs           1.5G  140K  1.5G   1% /run/user/1000
</code></pre>
<h4 id="heading-determining-process-states">Determining process states</h4>
<p>Process states can be monitored to see any stuck process with a high memory or CPU usage.</p>
<p>We saw previously that the <code>ps</code> command gives useful information about a process. Have a look at the <code>CPU</code> and <code>MEM</code> columns.</p>
<pre><code class="lang-bash">[user@host ~]$ ps aux
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
 runner         1  0.1  0.0 1535464 15576 ?       S  19:18   0:00 /inject/init
 runner        14  0.0  0.0  21484  3836 pts/0    S   19:21   0:00 bash --norc
 runner        22  0.0  0.0  37380  3176 pts/0    R+   19:23   0:00 ps aux
</code></pre>
<h4 id="heading-real-time-system-monitoring">Real-time system monitoring</h4>
<p>Real time monitoring gives a window into the realtime system state.</p>
<p>One utility you can use to do this is the <code>top</code> command.</p>
<p>The top command displays a dynamic view of the system's processes, displaying a summary header followed by a process or thread list. Unlike its static counterpart <code>ps</code>, <code>top</code> continuously refreshes the system stats.</p>
<p>With <code>top</code>, you can see well-organised details in a compact window. There a number of flags, shortcuts, and highlighting methods that come along with <code>top</code>.</p>
<p>You can also kill processes using <code>top</code>. For that, press <code>k</code> and then enter the process id.</p>
<h4 id="heading-interpreting-logs">Interpreting logs</h4>
<p>System and application logs carry tons of information about what the system is going through. They contain useful information and error codes that point towards errors. If you search for error codes in logs, issue identification and rectification time can be greatly reduced.</p>
<h4 id="heading-network-ports-analysis">Network ports analysis</h4>
<p>The network aspect should not be ignored as network glitches are common and may impact the system and traffic flows. Common network issues include port exhaustion, port choking, unreleased resources, and so on.</p>
<p>To identify such issues, we need to understand port states.</p>
<p>Some of the port states are explained briefly here:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>State</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td>LISTEN</td><td>Represents ports that are waiting for a connection request from any remote TCP and port.</td></tr>
<tr>
<td>ESTABLISHED</td><td>Represents connections that are open and data received can be delivered to the destination.</td></tr>
<tr>
<td>TIME WAIT</td><td>Represents waiting time to ensure acknowledgment of its connection termination request.</td></tr>
<tr>
<td>FIN WAIT2</td><td>Represents waiting for a connection termination request from the remote TCP.</td></tr>
</tbody>
</table>
</div><p>Let's explore how we can analyze port-related information in Linux.</p>
<p><strong>Port ranges:</strong> Port ranges are defined in the system, and range can be increased/decreased accordingly. In the below snippet, the range is from <code>15000</code> to <code>65000</code>, which makes a total of <code>50000</code> (65000 - 15000) available ports. If utilized ports are reaching or exceeding this limit, then there is an issue.</p>
<pre><code class="lang-bash">[user@host ~]$ /sbin/sysctl net.ipv4.ip_local_port_range
net.ipv4.ip_local_port_range = 15000    65000
</code></pre>
<p>The error reported in logs in such cases can be <code>Failed to bind to port</code> or <code>Too many connections</code>.</p>
<h4 id="heading-identifying-packet-loss">Identifying packet loss</h4>
<p>In system monitoring, we need to ensure that the outgoing and incoming communication is intact.</p>
<p>One helpful command is <code>ping</code>. <code>ping</code> hits the destination system and brings the response back. Note the last few lines of statistics that show packet loss percentage and time.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># ping destination IP</span>
[user@host ~]$ ping 10.13.6.113
 PING 10.13.6.141 (10.13.6.141) 56(84) bytes of data.
 64 bytes from 10.13.6.113: icmp_seq=1 ttl=128 time=0.652 ms
 64 bytes from 10.13.6.113: icmp_seq=2 ttl=128 time=0.593 ms
 64 bytes from 10.13.6.113: icmp_seq=3 ttl=128 time=0.478 ms
 64 bytes from 10.13.6.113: icmp_seq=4 ttl=128 time=0.384 ms
 64 bytes from 10.13.6.113: icmp_seq=5 ttl=128 time=0.432 ms
 64 bytes from 10.13.6.113: icmp_seq=6 ttl=128 time=0.747 ms
 64 bytes from 10.13.6.113: icmp_seq=7 ttl=128 time=0.379 ms
 ^C
 --- 10.13.6.113 ping statistics ---
 7 packets transmitted, 7 received,0% packet loss, time 6001ms
 rtt min/avg/max/mdev = 0.379/0.523/0.747/0.134 ms
</code></pre>
<p>Packets can also be captured at runtime using <code>tcpdump</code>. We'll look into it later.</p>
<h4 id="heading-gathering-stats-for-issue-post-mortem">Gathering stats for issue post mortem</h4>
<p>It is always a good practice to gather certain stats that would be useful for identifying the root cause later. Usually, after system reboot or services restart, we loose the earlier system snapshot and logs.</p>
<p>Below are some of the methods to capture system snapshot.</p>
<ul>
<li><strong>Logs Backup</strong></li>
</ul>
<p>Before making any changes, copy log files to another location. This is crucial for understanding what condition the system was in during time of issue. Sometimes log files are the only window to look into past system states as other runtime stats are lost.</p>
<ul>
<li><strong>TCP Dump</strong></li>
</ul>
<p>Tcpdump is a command-line utility that allows you to capture and analyze incoming and outgoing network traffic. It is mostly used to help troubleshoot network issues. If you feel that system traffic is being impacted, take <code>tcpdump</code> as follows:</p>
<pre><code class="lang-bash">sudo tcpdump -i any -w

<span class="hljs-comment"># Where,</span>
<span class="hljs-comment"># -i any captures traffic from all interfaces</span>
<span class="hljs-comment"># -w specifies the output filename</span>

<span class="hljs-comment"># Stop the command after a few mins as the file size may increase</span>
<span class="hljs-comment"># use file extension as .pcap</span>
</code></pre>
<p>Once <code>tcpdump</code> is captured, you can use tools like Wireshark to visually analyze the traffic.</p>
<h2 id="heading-810-diagnosing-hardware-problems">8.10 <strong>Diagnosing Hardware Problems</strong></h2>
<p>Troubleshooting unexpected issues is a part of the learning process. Sometimes, you may notice frequent segmentation faults (<code>SIGSEGV</code>), overheating, or random crashes across unrelated applications. The issue could either be software or hardware related. While software-related issues depend on the specific application itself, hardware issues can be diagnosed with some standard steps.</p>
<p>In this section, we will discuss how to diagnose and rule out hardware issues related to memory, CPU, system sensors, power supply, and more.</p>
<h3 id="heading-8101-analyzing-memory-performance"><strong>8.10.1 Analyzing Memory Performance</strong></h3>
<p><strong>Determine Available RAM</strong></p>
<p>If you feel your system is getting slow and taking longer to finish tasks, check your system's available memory. This will ensure there is enough available memory including the swap memory.</p>
<p>The command to check available memory is <code>free -mh</code>, where <code>-h</code> is for human-readable output and <code>-m</code> is for displaying memory in MB.</p>
<pre><code class="lang-bash">free -mh
               total        used        free      shared  buff/cache   available
Mem:            14Gi       5.1Gi       2.4Gi        77Mi       7.3Gi       9.3Gi
Swap:          4.0Gi          0B       4.0Gi
</code></pre>
<p>In the above output, look at the "available" column in the "Mem" row. This shows how much RAM is free for use.</p>
<p>Another way to check the memory in real time is to use the <code>top</code> command. There are 2 ways to do this:</p>
<ul>
<li><p>When you are in <code>top</code>, press <code>Shift + M</code> to sort the processes by memory usage.</p>
</li>
<li><p>Alternately, press <code>m</code> to see the memory usage in a progress bar like format:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739275886121/f1695a67-13d6-4222-b71c-07176a52acb8.png" alt="f1695a67-13d6-4222-b71c-07176a52acb8" class="image--center mx-auto" width="1350" height="286" loading="lazy"></p>
<p>If you see the memory consumed near to <code>100%</code>, you might want to consider identifying the process that is consuming the memory and take necessary action. You might also want to consider adding more memory to your system.</p>
<p><strong>Run a stress test on your hardware</strong></p>
<p>The <code>memtester</code> command is a utility used for diagnosing memory-related issues by stressing the memory and checking for faults. It is often used in situations where you suspect faulty RAM might be causing system instability or crashes.</p>
<p>Here's how to use it effectively:</p>
<ul>
<li><p>First, install <code>memtester</code>.</p>
<pre><code class="lang-bash">  sudo apt install memtester
</code></pre>
</li>
<li><p>Determine the amount of RAM to test and the number of passes you’d like your RAM to go through. In the command below, <code>1G</code> is the amount of RAM to test (1 GB), and <code>5</code> is the number of test passes:</p>
<pre><code class="lang-bash">  sudo memtester 1G 5
</code></pre>
</li>
</ul>
<p>If all tests pass, your RAM is likely error-free. If errors are reported, your RAM might be faulty and could require replacement or further inspection. You can always run the test again with a different amount of RAM or test passes.</p>
<p>Note that, you shouldn't test too much memory at once, as your system also needs memory for running processes. If you have more RAM than can be tested at once, test in smaller segments sequentially.</p>
<p>Below is a snippet of the <code>memtester</code> output if all tests pass. Notice the <code>”ok”</code> status for each test.</p>
<pre><code class="lang-bash">memtester version 4.5.1 (64-bit)
Copyright (C) 2001-2020 Charles Cazabon.
Licensed under the GNU General Public License version 2 (only).

pagesize is 4096
pagesizemask is 0xfffffffffffff000
want 1024MB (1073741824 bytes)
got  1024MB (1073741824 bytes), trying mlock ...locked.
Loop 1/5:
  Stuck Address       : ok
  Random Value        : ok
  Compare XOR         : ok
  Compare SUB         : ok
  Compare MUL         : ok
  Compare DIV         : ok
  Compare OR          : ok
  Compare AND         : ok
  Sequential Increment: ok
  Solid Bits          : ok
  Block Sequential    : ok
  Checkerboard        : ok
  Bit Spread          : ok
  Bit Flip            : ok
  Walking Ones        : ok
  Walking Zeroes      : ok
  8-bit Writes        : ok
  16-bit Writes       : ok
.
.
.
</code></pre>
<p>Below is a snippet of the output if a test fails. Notice the <code>FAILURE</code> status for each test.</p>
<pre><code class="lang-bash">memtester version 4.5.1 (64-bit)
Copyright (C) 2001-2020 Charles Cazabon.
Licensed under the GNU General Public License version 2 (only).

pagesize is 4096
pagesizemask is 0xfffffffffffff000
want 1024MB (1073741824 bytes)
got  1024MB (1073741824 bytes), trying mlock ...locked.
Loop 1/5:
  Stuck Address       : testing   1FAILURE: possible bad address line at offset 0x25378a58.
Skipping to next <span class="hljs-built_in">test</span>...
  Random Value        : FAILURE: 0x4df704aaafdf8848 != 0x4df704aaafdfc848 at offset 0x05379a48.
  Compare XOR         : ok
  Compare SUB         : ok
  Compare MUL         : ok
  Compare DIV         : ok
  Compare OR          : ok
  Compare AND         : ok
  Sequential Increment: ok
  Solid Bits          : testing   6FAILURE: 0x00000000 != 0x00004000 at offset 0x05379a48.
  Block Sequential    : testing   3FAILURE: 0x303030303030303 != 0x303030303034303 at offset 0x05379a48.
  Checkerboard        : testing   0FAILURE: 0xaaaaaaaaaaaaaaaa != 0xaaaaaaaaaaaaeaaa at offset 0x05379a48.
  Bit Spread          : testing  12FAILURE: 0xffffffffffffafff != 0xffffffffffffefff at offset 0x05379a48.
  Bit Flip            : testing   0FAILURE: 0x00000001 != 0x00004001 at offset 0x05379a48.
  Walking Ones        : ok
  Walking Zeroes      : testing   0FAILURE: 0x00000001 != 0x00001001 at offset 0x053af9f8.
  8-bit Writes        : -FAILURE: 0x57c7c8ba7d6f5b3b != 0x57c7c8ba7d6f1b3b at offset 0x0537da28.
  16-bit Writes       : -FAILURE: 0xd7768894fbf79099 != 0xd7768894fbf7d099 at offset 0x05379a48.
FAILURE: 0xfffc5633ffefca5d != 0xfffc5633ffefda5d at offset 0x053a5a38.
.
.
.
</code></pre>
<p>If errors persist across all test loops, it strongly suggests hardware issues, not transient software glitches.</p>
<h3 id="heading-8102-identifying-overheating-issues"><strong>8.10.2 Identifying Overheating Issues</strong></h3>
<p>Overheating can cause unexpected errors and crashes. To diagnose overheating issues, you can use a command line utility <code>lm-sensors</code>.</p>
<p><code>lm-sensors</code> allow syou monitor hardware health by reading data from various sensors. It provides information about system temperatures, voltages, and fan speeds.</p>
<p>Here's how you can identify and monitor your system temperature using <code>lm-sensors</code>:</p>
<ul>
<li><p>First, install <code>lm-sensors</code>:</p>
<pre><code class="lang-bash">  sudo apt install lm-sensors
</code></pre>
</li>
<li><p>Detect the available sensors on your system:</p>
<pre><code class="lang-bash">  sudo sensors-detect
</code></pre>
<p>  Follow the prompts and answer “YES” to detect the available sensors on your system.</p>
</li>
<li><p>Once the available sensors are detected, you can view the temperature of your system using the <code>sensors</code> command:</p>
<pre><code class="lang-bash">  sensors
</code></pre>
<p>  In the output below, you can see the temperature reading at the edge of the GPU, which is 41.0 degrees Celsius. You can also see other pieces of information like voltage supplied, power consumption and voltage supplied.</p>
<pre><code class="lang-bash">  amdgpu-pci-0400
  Adapter: PCI adapter
  vddgfx:      731.00 mV 
  vddnb:       687.00 mV 
  edge:         +41.0°C  
  PPT:           7.00 W
</code></pre>
<p>  Using <code>lm-sensors</code> ensures that the system is operating within safe parameters. It helps to detect potential hardware problems early and take corrective actions to prevent hardware damage.</p>
</li>
</ul>
<h3 id="heading-8103-evaluating-hard-drive-health"><strong>8.10.3 Evaluating Hard Drive Health</strong></h3>
<p>Disk errors can also cause application crashes. To identify disk issues, you can run disk check using <code>smartmontools</code>:</p>
<ul>
<li><p>First, install <code>smartmontools</code>:</p>
<pre><code class="lang-bash">  sudo apt install smartmontools
</code></pre>
</li>
<li><p>Run a quick health check using the command below and replace <code>/dev/sdX</code> with your disk name (check with <code>lsblk</code>).</p>
<pre><code class="lang-bash">  sudo smartctl -H /dev/sdX
</code></pre>
</li>
<li><p>Here is the result I got when I ran the command on my disk <code>/dev/nvme0n1</code>:</p>
<pre><code class="lang-bash">  sudo smartctl -H /dev/nvme0n1
  smartctl 7.4 2023-08-01 r5530 [x86_64-linux-6.8.0-52-generic] (<span class="hljs-built_in">local</span> build)
  Copyright (C) 2002-23, Bruce Allen, Christian Franke, www.smartmontools.org

  === START OF SMART DATA SECTION ===
  SMART overall-health self-assessment <span class="hljs-built_in">test</span> result: PASSED
</code></pre>
</li>
<li><p>You can also run a detailed test:</p>
<pre><code class="lang-bash">  sudo smartctl -a /dev/nvme0n1
</code></pre>
</li>
</ul>
<p>The detailed test provides a full report, including:</p>
<ul>
<li><p>Temperature</p>
</li>
<li><p>Power-on hours</p>
</li>
<li><p>Error counts</p>
</li>
<li><p>Wear leveling (for SSDs), and more.</p>
</li>
</ul>
<h3 id="heading-8104-conducting-a-cpu-stress-test"><strong>8.10.4 Conducting a CPU Stress Test</strong></h3>
<p>Faulty CPUs can also lead to a number of performance issues. To test your CPU, you can use the <code>stress-ng</code> utility:</p>
<ul>
<li><p>Install <code>stress-ng</code>:</p>
<pre><code class="lang-bash">  sudo apt install stress-ng
</code></pre>
</li>
<li><p>Run a CPU stress test:</p>
<pre><code class="lang-bash">  stress-ng --cpu 4 --timeout 60
</code></pre>
</li>
</ul>
<p>In the above command, <code>4</code> is the number of CPU cores you’d like to test and <code>60</code> is the duration in seconds. The command will stress all 4 CPU cores for 60 seconds. Notice the CPU is at <code>100%</code> load during the test:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739277374316/9ab475c2-7f09-4c40-989b-e474e334935c.png" alt="9ab475c2-7f09-4c40-989b-e474e334935c" class="image--center mx-auto" width="1079" height="600" loading="lazy"></p>
<p>If the system crashes during this test, the CPU may be faulty.</p>
<h3 id="heading-8105-examining-system-logs-for-errors"><strong>8.10.5 Examining System Logs for Errors</strong></h3>
<p><code>systemd</code> is a Linux system manager responsible for booting the system, managing system processes, and handling system services.</p>
<p><code>journalctl</code> is a command to query the <code>systemd</code> journal logs. It provides detailed logging for system processes, kernel events, user applications, and more.</p>
<p>You can check system logs for hardware-related errors using the command: <code>journalctl -k | grep -iE "error|fault|panic"</code>.</p>
<p>In the logs, look for messages about:</p>
<ul>
<li><p>Memory faults.</p>
</li>
<li><p>I/O errors.</p>
</li>
<li><p>Hardware timeouts.</p>
</li>
</ul>
<p>Here is what errors in the log file can look like:</p>
<pre><code class="lang-bash">Feb 11 10:15:32 hostname kernel: [Hardware Error]: CPU 0: Machine Check: 0 Bank 4: b200000000070f0f
Feb 11 10:15:32 hostname kernel: [Hardware Error]: TSC 0 ADDR fef1c000 MISC 38a0000086 
Feb 11 10:15:32 hostname kernel: [Hardware Error]: PROCESSOR 0:306a9 TIME 1613045732 SOCKET 0 APIC 0 microcode 1f
Feb 11 10:16:45 hostname kernel: EXT4-fs error (device sda1): ext4_find_entry:1453: inode <span class="hljs-comment">#2: comm ls: reading directory lblock 0</span>
Feb 11 10:17:12 hostname kernel: [drm:drm_atomic_helper_commit_cleanup_done [drm_kms_helper]] *ERROR* [CRTC:36:pipe A] flip_done timed out
Feb 11 10:18:05 hostname kernel: Kernel panic - not syncing: Fatal exception
</code></pre>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Thank you for reading the book until the end. If you found it helpful, consider sharing it with others.</p>
<p>This book doesn't end here, though. I will continue to improve it and add new materials in the future. If you found any issues or if you would like to suggest any improvements, <a target="_blank" href="https://github.com/zairahira/Mastering-Linux-Handbook">feel free to open a PR/ Issue.</a></p>
<p><strong>Stay Connected and Continue Your Learning Journey!</strong></p>
<p>Your journey with Linux doesn't have to end here. Stay connected and take your skills to the next level:</p>
<ol>
<li><p><strong>Follow Me on Social Media</strong>:</p>
<ul>
<li><p><a target="_blank" href="https://twitter.com/hira_zaira">X</a>: I share useful short form content there. My DMs are always open.</p>
</li>
<li><p><a target="_blank" href="https://www.linkedin.com/in/zaira-hira/">LinkedIn</a>: I share articles and posts on tech there. Leave a recommendation on LinkedIn and endorse me on relevant skills.</p>
</li>
</ul>
</li>
<li><p><strong>Get access to exclusive content</strong>: For one-on-one help and exclusive content go <a target="_blank" href="https://buymeacoffee.com/zairah/extras">here</a>.</p>
</li>
</ol>
<p>My <a target="_blank" href="https://www.freecodecamp.org/news/author/zaira/">articles</a> and books, like this one, are part of my mission to increase accessibility to quality content for everyone. This book will also be open to translation in other languages. Each piece takes a lot of time and effort to write. This book will be free, forever. If you've enjoyed my work and want to keep me motivated, consider <a target="_blank" href="https://buymeacoffee.com/zairah">buying me a coffee</a>.</p>
<p>Thank you once again and happy learning!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Hello World in Rust – Example Program ]]>
                </title>
                <description>
                    <![CDATA[ Starting with a new programming language is like taking your first step into a whole new world. One of the very first things you'll do is write a simple program that says "Hello World!". Rust, known for being fast and safe, is no exception. Let's jum... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/hello-world-in-rust/</link>
                <guid isPermaLink="false">66bb8809c32849d18c5cdc9d</guid>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Rust ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Sahil ]]>
                </dc:creator>
                <pubDate>Mon, 08 Apr 2024 09:21:17 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/04/Neon-Green-Motivational.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Starting with a new programming language is like taking your first step into a whole new world. One of the very first things you'll do is write a simple program that says "Hello World!".</p>
<p>Rust, known for being fast and safe, is no exception. Let's jump right in and create our very first Rust program together!</p>
<h2 id="heading-how-to-write-a-hello-world-program-in-rust">How to Write a Hello World Program in Rust</h2>
<p>First, create a file named <code>main.rs</code>. Every Rust program contains <code>.rs</code> as its file extension.</p>
<p>Then write the following code in the file:</p>
<pre><code class="lang-rust"><span class="hljs-comment">// main.rs</span>
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Hello World!"</span>);
}
</code></pre>
<p>In the code above, we are trying to print <code>Hello World!</code> in the console or terminal.</p>
<h2 id="heading-how-to-compile-rust-code">How to Compile Rust Code</h2>
<p>In Rust, compiling and running the code are two separate processes.</p>
<p>First, you need to compile the Rust program. To compile it, write the following in the terminal (make sure in the terminal is at at the same directory where the Rust file lives):</p>
<pre><code class="lang-bash">rustc main.rs
</code></pre>
<p>For now, you won't see any output because the code was just compiled. But one thing you can see in the current directory is that a new executable file has been added with the same name as the Rust file.</p>
<h2 id="heading-how-to-run-the-executable-file">How to Run the Executable File</h2>
<p>Now you can run the executable file that gets generated after you successfully compiled the Rust code.</p>
<p>To run the executable file, write the following in your terminal:</p>
<pre><code class="lang-bash">./main
</code></pre>
<p>You should see an output like this:</p>
<pre><code class="lang-bash">Hello World!
</code></pre>
<h2 id="heading-understanding-the-hello-world-code-in-depth">Understanding the Hello World Code in Depth</h2>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {

}
</code></pre>
<p>The program starts with a function called <code>main()</code>. Every Rust executable code starts execution from the main function. </p>
<p>The main function can have some parameters inside the <code>()</code> parenthesis, but we have no need for them in the code so we left that empty.</p>
<p>Everything that is between the curly braces <code>{}</code> is the body of the function. It is necessary to have braces for the body otherwise it'll throw an error.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
  <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Hello World!"</span>);
}
</code></pre>
<p>This line does the work of printing the "Hello World!" text to the terminal or console.</p>
<p>Here, <code>println!</code> is not a function unlike other languages like C, Python, and so on. It is a macro – if there's an <code>!</code> symbol at the end of a keyword, then it's a macro.</p>
<p>Finally, we passed the string as argument to the macro and it prints the string to the terminal.</p>
<p>To end the statement in Rust, you must use <code>;</code>.If you don't provide the semi-colon at the end of every statement, then it'll throw an error.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>And there we have it – your first Rust program! By printing out "Hello World!" you've dipped your toes into the world of Rust. </p>
<p>This simple program has given you a taste of Rust's syntax and how it compiles. As you keep going, you'll discover more about Rust's cool features and find out just how powerful it can be. </p>
<p>Ready to dive deeper? Let's keep exploring!</p>
<p>If you have any feedback, then feel free to DM me on <a target="_blank" href="https://twitter.com/introvertedbot">Twitter</a> and <a target="_blank" href="https://www.linkedin.com/in/sahil-mahapatra/">LinkedIn</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Git and GitHub – a Guide for Beginners and Experienced Developers ]]>
                </title>
                <description>
                    <![CDATA[ Welcome to Git and GitHub for Beginners! This comprehensive guide is tailored to help you navigate the world of version control and collaboration.  Whether you're a newbie just starting out or an experienced developer looking to brush up on your skil... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/guide-to-git-github-for-beginners-and-experienced-devs/</link>
                <guid isPermaLink="false">66bb56fe0da5b03e481107c4</guid>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Git ]]>
                    </category>
                
                    <category>
                        <![CDATA[ GitHub ]]>
                    </category>
                
                    <category>
                        <![CDATA[ version control ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Isaiah Clifford Opoku ]]>
                </dc:creator>
                <pubDate>Sat, 06 Apr 2024 01:38:29 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/04/Attractive.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Welcome to Git and GitHub for Beginners! This comprehensive guide is tailored to help you navigate the world of version control and collaboration. </p>
<p>Whether you're a newbie just starting out or an experienced developer looking to brush up on your skills, this guide offers a step-by-step approach to understanding and effectively using Git and GitHub.</p>
<p>By the end of this journey, you'll have a solid foundation in Git and GitHub. You'll be equipped with practical knowledge to streamline your coding workflow, collaborate seamlessly with teams, and contribute to open-source projects. </p>
<p>So, let's dive in and get started on your Git and GitHub adventure!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-who-is-this-guide-for">Who is this guide for?</a></li>
<li><a class="post-section-overview" href="#heading-technologies">Technologies</a></li>
<li><a class="post-section-overview" href="#heading-terms">Terms</a></li>
<li><a class="post-section-overview" href="#heading-what-is-github">What is GitHub?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-github-used-for">What is GitHub used for?</a></li>
<li><a class="post-section-overview" href="#heading-common-tasks-youll-perform-with-git">Common tasks you'll perform with Git</a></li>
<li><a class="post-section-overview" href="#heading-how-to-install-git">How to install Git</a></li>
<li><a class="post-section-overview" href="#heading-how-to-configure-git">How to configure Git</a></li>
<li><a class="post-section-overview" href="#heading-how-to-set-the-default-editor">How to set the default editor</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-repository-using-the-github-website">How to create a repository using the Github website</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-repository-using-the-git-command-line">How to create a repository using the Git command line</a></li>
<li><a class="post-section-overview" href="#heading-how-to-connect-a-local-repository-to-a-remote-repository-on-github">How to connect a local repository to a remote repository on GitHub</a></li>
<li><a class="post-section-overview" href="#heading-how-to-pull-changes-from-a-remote-repository-to-a-local-repository">How to pull changes from a remote repository to a local repository</a></li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-git-commands">How to work with Git commands</a></li>
<li><a class="post-section-overview" href="#heading-how-to-make-changes-to-a-file">How to make changes to a file</a></li>
<li><a class="post-section-overview" href="#heading-how-to-check-the-status-of-the-current-branch">How to check the status of the current branch</a></li>
<li><a class="post-section-overview" href="#heading-how-to-stage-changes">How to stage changes</a></li>
<li><a class="post-section-overview" href="#heading-how-to-commit-changes">How to commit changes</a></li>
<li><a class="post-section-overview" href="#heading-how-to-push-changes-to-a-remote-repository">How to push changes to a remote repository</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-branch">How to create a branch</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-pull-request">How to create a pull request</a></li>
<li><a class="post-section-overview" href="#heading-how-to-merge-a-pull-requset">How to merge a pull request</a></li>
<li><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></li>
</ul>
<h2 id="who-is-this-guide-for">Who is This Guide For?</h2>

<p>This guide is for everyone who wants to level up their coding skills and become proficient in using Git and GitHub. </p>
<p>Whether you're:</p>
<ul>
<li>just starting your tech career and need to learn the basics of version control.</li>
<li>an aspiring developer eager to integrate <code>Git</code> into your workflow.</li>
<li>an experienced programmer looking to refresh your knowledge or discover new features.</li>
<li>a team lead or manager interested in fostering a culture of collaboration and efficient code management.</li>
</ul>
<p>Regardless of your background or experience, this guide is designed to empower you with the tools and knowledge you need to excel in your coding endeavors.</p>
<h2 id="technologies">Technologies</h2>

<p>Before you start, make sure:</p>
<ul>
<li>You have a <a target="_blank" href="https://github.com/">GitHub account</a></li>
<li><a target="_blank" href="https://git-scm.com/">Git</a> is installed on your machine</li>
<li>You have a text editor, such as <a target="_blank" href="https://code.visualstudio.com/">Visual Studio Code</a> installed</li>
<li><a target="_blank" href="https://nodejs.org/en/">Node.js</a> is installed on your machine</li>
</ul>
<h2 id="terms">Terms</h2>

<p>They are a lot of terms around Git and Github that you may meet when you're working with version control. Let me break it down for you before we start:</p>
<ul>
<li><strong>Branch</strong>: A version of the codebase that diverges from the main branch to isolate changes for specific features, fixes, or experiments.</li>
<li><strong>Commit</strong>: A snapshot of your changes, saved to your local repository. Each commit is uniquely identified by a checksum.</li>
<li><strong>Stage</strong>: The area where Git tracks changes that are ready to be included in the next commit. Files in the staging area are prepared (staged) for the next commit.</li>
<li><strong>Merge</strong>: The process of integrating changes from one branch into another, typically the main branch.</li>
<li><strong>Pull Request</strong>: A proposal to merge changes from one branch into another, often used in collaborative environments to review and discuss changes before they are merged.</li>
<li><strong>Fork</strong>: A personal copy of someone else's project that lives on your GitHub account.</li>
<li><strong>Clone</strong>: The act of downloading a repository from a remote source to your local machine.</li>
<li><strong>Remote</strong>: A common repository that all team members use to exchange their changes.</li>
<li><strong>Origin</strong>: The default name Git gives to the server from which you cloned.</li>
<li><strong>Upstream</strong>: The original repository that was cloned.</li>
<li><strong>Master</strong>: The default branch name given to a repository when it is created. In modern practice, it is often replaced with <code>main</code>.</li>
<li><strong>Repository</strong>: A storage location where your project lives, containing all the files and revision history.</li>
<li><strong>Working Directory</strong>: The directory on your computer where you are making changes to your project.</li>
<li><strong>Staging Area</strong>: Also known as the "Index," it's an area where Git tracks changes that are ready to be committed.</li>
<li><strong>Index</strong>: Another name for the staging area, where Git tracks changes that are ready to be committed.</li>
<li><strong>HEAD</strong>: A reference to the last commit in the currently checked-out branch.</li>
<li><strong>Checkout</strong>: The action of switching from one branch to another or to a specific commit.</li>
<li><strong>Push</strong>: The action of sending your commits to a remote repository.</li>
<li><strong>Pull</strong>: The action of fetching changes from a remote repository and merging them into your current branch.</li>
<li><strong>Fetch</strong>: The action of retrieving updates from a remote repository without merging them into your current branch.</li>
</ul>
<h2 id="what-is-github">What is GitHub?</h2>

<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/GitHub-1.png" alt="GitHub-1" width="600" height="400" loading="lazy"></p>
<p>GitHub is a platform that hosts code, providing version control and collaboration features. It enables you and others to work together on projects from anywhere in the world. </p>
<p>This guide will introduce you to essential GitHub concepts such as <code>repositories</code>, <code>branches</code>, <code>commits</code>, and <code>Pull Requests</code>. You will learn how to create your own 'Hello World' repository and understand GitHub's Pull Request workflow, a widely-used method for creating and reviewing code. </p>
<p>By the end of this guide, you'll be equipped with the knowledge and skills to collaborate effectively on GitHub.</p>
<h2 id="what-is-github-used-for">What is GitHub Used For?</h2>

<p>GitHub is more than just a code hosting platform. It's a tool that allows for seamless collaboration and version control. Here are some of its uses:</p>
<ul>
<li>Hosting and sharing your code with others.</li>
<li>Tracking and assigning issues to maintain an organized workflow.</li>
<li>Managing pull requests to review and incorporate changes into your project.</li>
<li>Creating your own website using GitHub Pages, a static site hosting service.</li>
<li>Collaborating with others on projects, making it an excellent tool for open-source contributions.</li>
</ul>
<h2 id="what-is-git">What is Git?</h2>

<p>Git is a free and open-source distributed version control system. It's designed to handle everything from small to very large projects with speed and efficiency</p>
<p>Git is easy to learn and has a tiny footprint with lightning-fast performance. It outclasses SCM tools like Subversion, CVS, Perforce, and ClearCase with features like cheap local branching, convenient staging areas, and multiple workflows</p>
<p>Git was initially designed and developed by Linus Torvalds for Linux kernel development.</p>
<p>Some features/benefits of Git:</p>
<ul>
<li>Allows you to track changes to your code over time.</li>
<li>Enables you to collaborate with others on the same codebase.</li>
<li>You can easily revert to a previous version of your code or experiment with new features without affecting the main codebase.</li>
<li>Provides a record of all changes made to your code, including who made them and when which can be useful for auditing and debugging.</li>
</ul>
<h2 id="common-tasks-youll-perform-with-git"> Common Tasks You'll Perform with Git </h2>

<ul>
<li>Create a repository</li>
<li>Create a branch</li>
<li>Make changes to a file</li>
<li>Stage changes</li>
<li>Commit changes</li>
<li>Push changes to a remote repository</li>
<li>Merge changes</li>
<li>Revert changes</li>
<li>Delete a branch</li>
</ul>
<h2 id="how-to-install-git">  How to Install Git </h2>

<p>To install Git on your local machine, you need to follow these steps:</p>
<ol>
<li><p>Download Git from the official website: <a target="_blank" href="https://git-scm.com/downloads">Git Downloads</a></p>
</li>
<li><p>Install Git on your local machine by following the instructions provided on the official website: <a target="_blank" href="https://git-scm.com/book/en/v2/Getting-Started-Installing-Git">Installing Git</a></p>
</li>
</ol>
<p><em>Congratulations!</em> You have successfully installed Git on your local machine. You are now ready to start using Git for your projects.</p>
<h2 id="how-to-configure-git">  How to Configure Git </h2>

<p>Git offers a variety of configurations that can streamline your workflow. In this section, I will guide you through the process of setting up Git on your local machine. Let's get started.</p>
<p>Configuring your <code>name</code> and <code>email</code> address on your local machine is an essential step in setting up Git. These details are attached to each commit you make, providing context and ownership. Let's learn how to use the <code>git config --global</code> command to set your name and email globally on your local machine.</p>
<p>To set up your name, you need to type the following command in your terminal:</p>
<pre><code class="lang-bash">
<span class="hljs-comment"># Set a name that is identifiable for credit when reviewing version history</span>

$ git config --global user.name <span class="hljs-string">"Your Name"</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/userNameEmail.png" alt="userNameEmail" width="600" height="400" loading="lazy"></p>
<p>As you can see in the image above, I have entered my name.</p>
<p>After entering your name, press <code>Enter</code> to save it. You won't receive any response, but rest assured, your name has been stored successfully.</p>
<p>Just like we set up the user name, we also need to set up the user email. This email will be associated with each commit you make. Let's learn how to use the <code>git config --global</code> command to set your email globally on your local machine.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Set an email address that will be associated with each history marker</span>
$ git config --global user.email <span class="hljs-string">"your-email@example.com"</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/Email.png" alt="Email" width="600" height="400" loading="lazy"></p>
<p>Make sure to replace this with your actual email used in your GitHub account.</p>
<p>Now that we have finished setting up your username and email for Git and GitHub, let's verify that everything is configured correctly.</p>
<p>To do this, use the following command:</p>
<pre><code class="lang-bash">git config --global --list
</code></pre>
<p>This command will list the username and email being used in the console for you to see.</p>
<p>You should see some information displayed in your terminal.</p>
<h2 id="how-to-set-the-default-editor"> How to Set the Default Editor</h2>

<p>In modern development, having a code editor can significantly simplify your workflow, especially when you're focused on coding.</p>
<p>Now, let's see how to configure Git to use a default editor by using this command:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Set the default editor for Git</span>
$ git config --global core.editor <span class="hljs-string">"code --wait"</span>
</code></pre>
<p><em>Congratulations!</em> You have successfully configured Git on your local machine. You are now ready to start using Git for your projects.</p>
<h2 id="how-to-create-a-repository-using-the-github-website">  How to Create a Repository Using the Github Website </h2>

<p>Creating a repository is the first step in using Git. A repository is a storage location where your projects live, containing all the files and revision history. </p>
<p>In this section, I will guide you through the process of creating a repository on GitHub. </p>
<p>There are two ways to create a repository: using the <code>GitHub website</code> or the command line. Let's get started. In this section, we'll focus on creating a repository using the GitHub website and the command line.</p>
<p>After logging into your GitHub account, you can create a new repository by following these steps:</p>
<ol>
<li>Click on the <code>+</code> sign in the top right corner of the page and select <code>New Repository</code> from the dropdown menu.</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/Github-create-repo.png" alt="Github-create-repo" width="600" height="400" loading="lazy"></p>
<p>Above is an image of the new repository button on GitHub.</p>
<ol start="2">
<li><p>You will be directed to a new page where you can fill in the details of your new repository. You will need to enter the following information:</p>
</li>
<li><p><code>Repository name</code>: This is the name of your repository. It should be unique and descriptive.</p>
</li>
<li><code>Description</code>: A brief description of your repository.</li>
<li><code>Public or Private</code>: You can choose to make your repository public or private. Public repositories are visible to everyone, while private repositories are only visible to you and the people you share them with.</li>
<li><code>Initialize</code> this repository with a README: You can choose to initialize your repository with a README file. This is useful if you want to provide information about your project or instructions on how to use it.</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/github-repo-infor.png" alt="github-repo-infor" width="600" height="400" loading="lazy"></p>
<p>The image above shows the form where you'll fill in the details of your new repository.</p>
<ol start="3">
<li>Once you have filled in the details, click on the <code>Create Repository</code> button to create your new repository.</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/github-create-repo-button.png" alt="github-create-repo-button" width="600" height="400" loading="lazy"></p>
<p>The image above shows the <code>Create Repository</code> button_.</p>
<p><em>Congratulations!</em> You have successfully created a new repository on GitHub. You can now start adding files and making changes to your repository.</p>
<p>You should see a page like the one below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/github-new-repo.png" alt="github-new-repo" width="600" height="400" loading="lazy"></p>
<p>Now let's create a repository using the command line.</p>
<h2 id="how-to-create-a-repository-using-the-git-command-line">  How to Create a Repository Using the Git Command Line </h2>


<p>To create a new <code>repository</code> using the command line, you need to follow these steps:</p>
<ol>
<li><p>Open your terminal and navigate to the directory where you want to create your new repository.</p>
</li>
<li><p>Use the <code>git init</code> command to create a new repository. This command will create a new directory called <code>.git</code> in your current directory, which will contain all the necessary files for your repository.</p>
</li>
</ol>
<pre><code class="lang-bash">
<span class="hljs-comment"># initialize a new repository called my-project</span>

$ git init my-project
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/terminal-init.png" alt="terminal-init" width="600" height="400" loading="lazy"></p>
<p>The image above shows the command to initialize a new repository called <code>my-project</code>.</p>
<ol start="3">
<li>Once you have created your new repository, you can start adding files and making changes to it. You can also connect your local repository to a remote repository on GitHub by following the instructions provided on the GitHub website.</li>
</ol>
<p><em>Congratulations!</em> You have successfully created a new repository using the command line. </p>
<p>Now we have successfully created a repository using the GitHub website and the command line – but how do we connect them? Now let's learn how to connect a local repository to a remote repository on GitHub.</p>
<h2 id="how-to-connect-a-local-repository-to-a-remote-repository-on-github">  How to Connect a Local Repository to a Remote Repository on GitHub </h2>

<p>To connect your local repository to a remote repository on GitHub, you need to follow these steps:</p>
<ol>
<li><p>On GitHub, navigate to the main page of the repository you created earlier.</p>
</li>
<li><p>Click on the <code>Code</code> button to copy the URL of your repository.</p>
</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/Github-code-url-cope.png" alt="Github-code-url-cope" width="600" height="400" loading="lazy"></p>
<p>The image above shows the code button to copy the URL of your repository.</p>
<ol start="3">
<li><p>In your terminal, navigate to the directory of your local repository.</p>
</li>
<li><p>Use the <code>git remote add origin</code> command to connect your local repository to the remote repository on GitHub. Replace repository-URL with the URL of your repository.</p>
</li>
</ol>
<pre><code class="lang-bash">$ git remote add origin repository-url
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/terminal-remote-add-origin.png" alt="terminal-remote-add-origin" width="600" height="400" loading="lazy"></p>
<p>The image above shows the command to connect your local repository to the remote repository on GitHub.</p>
<ol start="5">
<li>Once you have connected your local repository to the remote repository on GitHub, you can start pushing your changes to the remote repository using the <code>git push</code> command.</li>
</ol>
<p><em>Congratulations!</em> You have successfully connected your local repository to the remote repository on GitHub.</p>
<h2 id="how-to-pull-changes-from-a-remote-repository-to-a-local-repository">   How to Pull Changes from a Remote Repository to a Local Repository </h2>

<p>To pull changes from the remote repository to the local repository, you need to follow these steps:</p>
<ol>
<li><p>In your terminal, navigate to the directory of your local repository.</p>
</li>
<li><p>Use the <code>git pull</code> command to pull changes from the remote repository to the local repository.</p>
</li>
</ol>
<pre><code class="lang-bash">
$ git pull origin main
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/terminal-git-pull.png" alt="terminal-git-pull" width="600" height="400" loading="lazy"></p>
<p>The image above shows the command to pull changes from the remote repository to the local repository.</p>
<p>After that, navigate the main branch by using the following command:</p>
<pre><code class="lang-bash">
$ git checkout main
</code></pre>
<p><em>Congratulations!</em> You have successfully pulled changes from a remote repository to a local repository. Your local repository is now up-to-date with the remote repository on GitHub*.</p>
<h2 id="how-to-work-with-git-commands"> How to Work with Git Commands </h2>

<p>In this section, we will cover some of the most commonly used Git commands and their functions. These commands will help you navigate your way through the Git workflow in your GitHub repository. Let's get started. </p>
<p>First, I will add some files so that we can start using the Git commands.</p>
<h2 id="how-to-make-changes-to-a-file"> How to Make Changes to a File </h2>

<p>To make changes to a file in Git, you need to follow these steps:</p>
<ol>
<li><p>Open your terminal and navigate to the directory of your local repository.</p>
</li>
<li><p>Use a text editor to make changes to the file. For example, you can use the <code>code</code> command to open the file in Visual Studio Code.</p>
</li>
</ol>
<pre><code class="lang-bash">
$ code file-name  <span class="hljs-comment"># For example, code index.html</span>
</code></pre>
<ol start="3">
<li>Once you have made your changes, save the file and close the text editor.</li>
</ol>
<p><em>Congratulations!</em> You have successfully made changes to a file in your local repository. Next, let's proceed to the next step: staging changes.</p>

<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/file-cahnge-added.png" alt="file-cahnge-added" width="600" height="400" loading="lazy"></p>
<p>The image above shows the new file I added which is a React and TypeScript app.</p>
<p>Visual Studio Code (VS Code) includes a source control feature that allows you to interact directly with your GitHub repository. This feature supports a variety of operations, including staging, committing, pushing, and pulling changes. </p>
<p>In addition to the source control feature, you can also use the integrated terminal in VS Code to interact with your GitHub repository. </p>
<p>Currently, if you look at the source control section in VS Code, you'll see the file we added listed under changes. </p>
<p>Next, let's explore how to use the terminal to interact with our GitHub repository.</p>
<p>Open your terminal and navigate to the directory of your local repository.</p>
<p>Now, let's use the <code>git status</code> command to check the status of the current branch.</p>
<h2 id="how-to-check-the-status-of-the-current-branch">  How to Check the Status of the Current Branch </h2>

<p>The <code>git status</code> command shows the status of the current branch, including any changes that have been made to the files in the repository. It provides information about which files have been modified, which files have been staged, and which files are untracked. </p>
<p>This command is useful for understanding the current state of your repository and determining which files need to be staged and committed.</p>
<pre><code class="lang-bash"><span class="hljs-comment">#  Check the status of the current branch</span>

$ git status  <span class="hljs-comment"># On branch master</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/terminal-git-status.png" alt="terminal-git-status" width="600" height="400" loading="lazy"></p>
<p>The image above shows the command to check the status of the current branch.</p>
<p>You may notice that parts of the file are highlighted in different colors. The <code>red</code> color indicates that the file has been modified, while the <code>green</code> color signifies that the file has been added to the staging area. </p>
<p>Currently, all files should be highlighted in <code>red</code> because we have not yet added any files to the staging area.</p>
<p>Let's add the file to the staging area using the <code>git add</code> command.</p>
<h2 id="how-to-stage-changes">  How to Stage Changes </h2>

<p>The <code>git add</code> command adds files to the staging area, preparing them for the next commit. You can add all the files in the current directory to the staging area using the <code>git add .</code> command. </p>
<p>If you want to add a specific file, use the <code>git add &lt;file-name&gt;</code> command, replacing <code>&lt;file-name&gt;</code> with the name of your file. This process is known as staging, which prepares files for the next commit.</p>
<pre><code class="lang-bash">
<span class="hljs-comment"># Add files to the staging area</span>

$ git add .  <span class="hljs-comment"># Changes to be committed:</span>

or 

$ git add file-name  <span class="hljs-comment"># Changes to be committed:</span>
</code></pre>
<p>Think of it like this: getting into the car is like adding files to the staging area, and driving the car is like making a commit. </p>
<p>Now, let's use the <code>git commit</code> command to commit the changes to the current branch.</p>
<h2 id="how-to-commit-changes">  How to Commit Changes </h2>

<p>The <code>git commit</code> command commits the changes to the current branch. You can use the <code>-m</code> flag to add a message to your commit. This message should provide a brief summary of the changes you've made.</p>
<p>For instance, "Initial commit" could be your commit message. This command is used to save the changes to the local repository.</p>
<pre><code class="lang-bash">

<span class="hljs-comment"># Commit changes to the current branch</span>

$ git commit -m <span class="hljs-string">"Commit message"</span>   <span class="hljs-comment"># For example, git commit -m "Initial commit"</span>
</code></pre>
<p>We've successfully committed the changes to the current branch. Next, we'll push these changes to the remote repository on GitHub using the <code>git push</code> command.</p>
<h2 id="how-to-push-changes-to-a-remote-repository">  How to Push Changes to a Remote Repository </h2>

<p>The <code>git push</code> command pushes changes from your local repository to a remote repository on GitHub. You can use the <code>git push</code> command to push changes from your local repository to the remote repository on GitHub. This process is essential for updating the remote repository with the changes you've made locally.</p>
<pre><code class="lang-bash">
<span class="hljs-comment"># Push changes to a remote repository</span>

$ git push origin main  <span class="hljs-comment"># For example, git push origin master</span>
</code></pre>
<p><em>Congratulations!</em> You have successfully pushed your changes to the remote repository on GitHub. You can now view your changes on the GitHub website.  </p>
<p>Now that we've successfully pushed our changes to the remote repository on GitHub, let's proceed to the next step: creating a branch. </p>
<p>Depending on your PC environment, your local repository may have a default branch named either <code>main</code> or <code>master</code>. In this guide, we'll use <code>main</code> as the default branch name, aligning with GitHub's recent change from <code>master</code> to <code>main</code>.</p>
<p>Before we start adding files, let's ensure our local repository is up-to-date with the remote repository by pulling any changes. </p>
<p>If the term <code>branch</code> seems unfamiliar, don't worry. In the next section, we'll cover how to create a branch and how to pull changes from the remote repository to the local repository.</p>
<h2 id="how-to-create-a-branch">  How to Create a Branch </h2>

<p>Branching is a fundamental concept in Git. It allows you to diverge from the main line of development and continue working without impacting the main codebase. </p>
<p>In this section, I'll guide you through the process of creating a new branch using the <code>git branch</code> command. This command creates a new branch but does not switch to it. In the following steps, we'll also cover how to switch to your newly created branch using the <code>git checkout</code> command. Let's dive in.</p>
<p>To create a new branch, you need to follow these steps:</p>
<ol>
<li><p>Open your terminal and navigate to the directory of your local repository.</p>
</li>
<li><p>Use the <code>git branch</code> command to create a new branch. Replace <code>&lt;branch-name&gt;</code> with the name of your new branch.</p>
</li>
</ol>
<pre><code class="lang-bash">
<span class="hljs-comment"># Create a new branch</span>

$ git branch &lt;branch-name&gt;  <span class="hljs-comment"># For example, git branch feature-branch</span>
</code></pre>
<p>The <code>git branch</code> command creates a new branch but does not switch to it. To switch to your newly created branch, use the <code>git checkout</code> command.</p>
<pre><code class="lang-bash">
<span class="hljs-comment"># Switch to the newly created branch</span>

$ git checkout &lt;branch-name&gt;  <span class="hljs-comment"># For example, git checkout feature-branch</span>
</code></pre>
<p>The <code>git checkout</code> command is used to switch from one branch to another. Replace <code>&lt;branch-name&gt;</code> with the name of your new branch. In this case, we're switching to the <code>feature-branch</code> branch. But we if want to delete the branch, we can use the following command:</p>
<pre><code class="lang-bash">

<span class="hljs-comment"># Delete a branch</span>

$ git branch -d &lt;branch-name&gt;  <span class="hljs-comment"># For example, git branch -d feature-branch</span>
</code></pre>
<p>The <code>git branch -d</code> command is used to delete a branch. Replace <code>&lt;branch-name&gt;</code> with the name of the branch you want to delete. In this case, we're deleting the <code>feature-branch</code> branch.</p>
<p><em>Congratulations!</em> You have successfully created a new branch and switched to it. You can now start adding files and making changes to your new branch.</p>
<p>Now you know how to create GitHub repository, connect a local repository to a remote repository on GitHub, pull changes from a remote repository to a local repository, work with Git commands, and create a branch. </p>
<p>Let's proceed to the next section, where we'll cover how to create a pull request. This is a crucial step in the collaborative workflow, as it allows you to propose changes and request a review from other collaborators.</p>
 <h2 id="how-to-create-a-pull-request"> How to Create a Pull Request  </h2>

<p>A pull request is a proposal to merge changes from one branch into another. It's a widely-used method for creating and reviewing code. In this section, I'll guide you through the process of creating a pull request using the GitHub website. </p>
<p>For instance, let's say you have a branch named <code>feature-branch</code> and you want to merge it into the <code>main</code> branch. We'll walk you through how to create a pull request for this scenario. Let's get started.</p>
<p>First, let's make a change to our feature branch by adding a file to it:</p>
<pre><code class="lang-bash">
$ git checkout feature-branch
</code></pre>
<p>You should see something like this in your terminal:</p>
<pre><code class="lang-bash">
git checkout feature-branch
Switched to a new branch <span class="hljs-string">'feature-branch'</span>
branch <span class="hljs-string">'feature-branch'</span> <span class="hljs-built_in">set</span> up to track <span class="hljs-string">'origin/feature-branch'</span>.
</code></pre>
<p>Now, let's add a file to the feature branch. </p>
<pre><code class="lang-bash">
$ touch feature-branch-file.txt
</code></pre>
<p>After running the command, you should see a new file called <code>feature-branch-file.txt</code> in your directory.</p>
<p>The <code>touch</code> command is used to create a new file. Replace <code>feature-branch-file.txt</code> with the name of your file. In this case, we're creating a new file called <code>feature-branch-file.txt</code>.</p>
<p>Now, let's add some content to the file.</p>
<pre><code class="lang-bash">
$ <span class="hljs-built_in">echo</span> <span class="hljs-string">"This is a file in the feature branch"</span> &gt;&gt; feature-branch-file.txt
</code></pre>
<p>This command adds the text "This is a file in the feature branch" to the <code>feature-branch-file.txt</code> file.</p>
<p>The <code>echo</code> command is used to add content to a file. In this case, we're adding the text "This is a file in the feature branch" to the <code>feature-branch-file.txt</code> file.</p>
<p>Now that we have some text in the file, let's stage and commit the changes to the feature branch.</p>
<pre><code class="lang-bash">
$ git add .
</code></pre>
<p>The <code>git add .</code> command stages all the changes in the current directory.</p>
<pre><code class="lang-bash">

$ git commit -m <span class="hljs-string">"Add file to feature branch"</span>
</code></pre>
<p>The <code>git commit -m</code> command commits the changes to the current branch. Replace <code>Add file to feature branch</code> with your own descriptive message. This message should provide a brief summary of the changes you've made. In this case, we're committing the changes to the feature branch.</p>
<p>Now, let's push the changes to the remote repository on GitHub.</p>
<pre><code class="lang-bash">
$ git push origin feature-branch
</code></pre>
<p>The <code>git push</code> command is used to push changes from your local repository to the remote repository on GitHub. Replace <code>feature-branch</code> with the name of your branch. In this case, we're pushing the changes to the <code>feature-branch</code> branch.</p>
<p><em>Congratulations!</em> You have successfully pushed your changes to the remote repository on GitHub. You can now view your changes on the GitHub website.</p>
<p>Now when you open your GitHub repository, you should see a message indicating that you recently pushed a new branch. You can click on the <code>Compare &amp; pull request</code> button to create a pull request for the <code>feature-branch</code> branch. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/github-compare-pull-request.png" alt="github-compare-pull-request" width="600" height="400" loading="lazy"></p>
<p>The image above shows the <code>Compare &amp; pull request</code> button on GitHub.</p>
<p>After clicking on the <code>Compare &amp; pull request</code> button, you will be directed to a new page where you can fill in the details of your pull request. </p>
<p>You will need to enter the following information:</p>
<ul>
<li>Title: a brief summary of your pull request.</li>
<li>Description: a detailed description of your pull request, including information about the changes you've made and why you've made them.</li>
<li>Reviewers: you can choose to request a review from specific collaborators.</li>
<li>Assignees: you can choose to assign your pull request to specific collaborators.</li>
<li>Labels: you can choose to add labels to your pull request to categorize it.</li>
<li>Projects: you can choose to add your pull request to a project board.</li>
<li>Milestone: you can choose to add your pull request to a milestone.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/github-pull-request-form.png" alt="github-pull-request-form" width="600" height="400" loading="lazy"></p>
<p>The image above shows the form to fill in the details of your pull request.</p>
<p>You can decide to file the details of your pull request or create the pull request. After creating the pull request, you can view it on the GitHub website. You can also request a review from specific collaborators and make changes to your pull request if necessary. </p>
<p>Once your pull request has been reviewed and approved, you can merge it into the <code>main</code> branch. In our case we not going to file the form but we are going to create the pull request.</p>

<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/github-pull-request-created.png" alt="github-pull-request-created" width="600" height="400" loading="lazy"></p>
<p>The image above shows the pull request created on GitHub.</p>
<p>Now that we have created a pull request, let's proceed to the next section, where we'll cover how to merge a pull request. This is the final step in the collaborative workflow, as it allows you to incorporate changes into the main codebase.</p>
<h2 id="how-to-merge-a-pull-request">How to Merge a Pull Requset  </h2>

<p>Merging a pull request signifies the integration of changes from one branch into another, often the main branch. This step is pivotal in collaborative workflows, enabling the assimilation of modifications into the primary codebase. </p>
<p>In this section, we'll navigate the process of merging a pull request via the GitHub website. </p>
<p>After creating a pull request, you can merge it into the <code>main</code> branch by following these steps:</p>
<ol>
<li><p>On GitHub, navigate to the main page of the repository where you created the pull request.</p>
</li>
<li><p>Click on the <code>Pull requests</code> tab to view the list of pull requests.</p>
</li>
</ol>

<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/github-pull-request-tab.png" alt="github-pull-request-tab" width="600" height="400" loading="lazy"></p>
<p>The image above shows the <code>Pull requests</code> tab on GitHub.</p>
<ol start="3">
<li><p>Click on the pull request you want to merge.</p>
</li>
<li><p>Click on the <code>Merge pull request</code> button to merge the pull request into the <code>main</code> branch.</p>
</li>
<li><p>Click on the <code>Confirm merge</code> button to confirm the merge.</p>
</li>
</ol>
<p>After that you should see a message indicating that the pull request has been successfully merged. You can also delete the branch after merging the pull request.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/github-pull-request-merged.png" alt="github-pull-request-merged" width="600" height="400" loading="lazy"></p>
<p>Now you have successfully merged the pull request into the <code>main</code> branch. You can now delete the <code>feature-branch</code> branch, as it is no longer needed.  </p>
 <h2 id="wrapping-up"> Wrapping Up </h2>

<p>Throughout this guide, we've delved into the core concepts of Git and GitHub, equipping you with a robust understanding of version control and collaborative practices. </p>
<p>We've navigated the essential Git operations, including setting up a repository, linking the local repository to its remote counterpart on GitHub, synchronizing changes between the local and remote repositories, executing Git commands, branching, initiating pull requests, and merging those requests. </p>
<p>Mastering these principles will significantly enhance your coding workflow, facilitate seamless team collaboration, and enable meaningful contributions to open-source projects. </p>
<p>I trust that this guide has instilled in you the knowledge and confidence to excel in your programming journey and start contributing to open source projects. Here's to your success in coding!</p>
<p>You can contact me on <a target="_blank" href="https://twitter.com/Clifftech_Dev">Twitter</a> or <a target="_blank" href="https://www.linkedin.com/in/isaiah-clifford-opoku/">LinkedIn</a> for any questions or feedback. I'd love to hear from you!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn Git Fundamentals – A Handbook on Day-to-Day Development Tasks ]]>
                </title>
                <description>
                    <![CDATA[ Welcome to my comprehensive guide on Git, the distributed version control system that has revolutionized collaboration and code management in software development.  Whether you're a seasoned developer or just starting your journey in programming, und... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-git-basics/</link>
                <guid isPermaLink="false">66c7218e55df43f1418b5b2c</guid>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Git ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ version control ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Samyak Jain ]]>
                </dc:creator>
                <pubDate>Wed, 03 Apr 2024 03:57:39 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/04/Learn-Git-Basics-Cover-3--1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Welcome to my comprehensive guide on Git, the distributed version control system that has revolutionized collaboration and code management in software development. </p>
<p>Whether you're a seasoned developer or just starting your journey in programming, understanding Git is essential to gain proper control over your code, efficiently managing your projects and collaborating with others. </p>
<p>In this tutorial, I'll take you through the fundamentals of Git, covering everything from its basic workflow to advanced branching strategies and rebasing techniques. </p>
<p>By the end of this guide, you'll have a solid understanding of Git's core concepts and be confident and well equipped with the skills to effectively use it in your development workflow.</p>
<h2 id="heading-prerequisites">Prerequisites:</h2>
<p>All you need to bring to the table is a curious and eager-to-learn mindset. This guide is crafted with beginners in mind, so no prior knowledge of version control systems or programming is required. Whether you're a complete novice or have some experience with coding, you'll find this tutorial accessible and easy to follow.</p>
<h2 id="heading-table-of-contents"><strong>Table of Contents:</strong></h2>
<ol>
<li><a class="post-section-overview" href="#heading-what-is-git">What is Git?</a><br>– <a class="post-section-overview" href="#heading-what-makes-git-different-from-other-version-control-systems">Difference from other version control systems</a><br>– <a class="post-section-overview" href="#heading-the-three-states-and-basic-git-workflow">The Three States and Basic Git Workflow</a></li>
<li><a class="post-section-overview" href="#heading-first-time-git-setup">First-Time Git Setup</a></li>
<li><a class="post-section-overview" href="#heading-how-to-get-help-in-git">Get Help in Git</a></li>
<li><a class="post-section-overview" href="#heading-how-to-get-a-git-repository">How to Get a Git Repository</a><br>– <a class="post-section-overview" href="#heading-1-how-to-initialize-a-repository-in-an-existing-directory-in-git">Initialize a Repository in an Existing Directory</a><br>– <a class="post-section-overview" href="#heading-2-how-to-clone-an-existing-repository-in-git">Clone an Existing Repository in Git</a></li>
<li><a class="post-section-overview" href="#heading-how-to-record-changes-to-the-repository">How to Record Changes to the Repository</a></li>
<li><a class="post-section-overview" href="#heading-how-to-view-commit-history-in-git">View Commit History in Git</a></li>
<li><a class="post-section-overview" href="#heading-how-to-undo-things-in-git">Undo Things in Git</a></li>
<li><a class="post-section-overview" href="#how-to-work-with-remote-repositories-in-git">Remote Repositories in Git</a></li>
<li><a class="post-section-overview" href="#heading-tagging-in-git">Tagging in Git</a></li>
<li><a class="post-section-overview" href="#heading-git-aliases">Git Aliases</a></li>
<li><a class="post-section-overview" href="#heading-git-branching">Git Branching</a><br>– <a class="post-section-overview" href="#heading-how-to-create-a-new-branch-in-git">Create a New Branch in Git</a><br>– <a class="post-section-overview" href="#heading-understanding-branches">Understanding Branches</a><br>– <a class="post-section-overview" href="#heading-how-to-switch-to-another-branch-in-git">Switch to Another Branch in Git</a><br>– <a class="post-section-overview" href="#how-to-visualise-branches-in-git-">Visualise Branches in Git</a></li>
<li><a class="post-section-overview" href="#heading-how-to-manage-branches-in-git">How to Manage Branches in Git</a><br>– <a class="post-section-overview" href="#heading-how-to-manage-merged-branches">Managing Merged Branches</a><br>– <a class="post-section-overview" href="#heading-how-to-rename-branches">Renaming Branches</a><br>– <a class="post-section-overview" href="#heading-how-to-change-the-default-branch-name">Changing the Default Branch Name</a></li>
<li><a class="post-section-overview" href="#heading-branching-workflow">Branching Workflow</a></li>
<li><a class="post-section-overview" href="#heading-rebasing-in-git">Rebasing in Git</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<h2 id="heading-what-is-git">What is Git?</h2>
<p>Git is a distributed version control system that helps you and your team collaborate effectively while keeping your project's history safe. It's like having a time machine for your code!</p>
<h3 id="heading-what-makes-git-different-from-other-version-control-systems">What makes Git different from other Version Control Systems?</h3>
<h4 id="heading-conceptual-difference">Conceptual Difference:</h4>
<p>The big thing that sets Git apart from other tools is how it thinks about data. Instead of storing changes to files, Git thinks of its data as a series of snapshots of your project, means, every time you make a change and save it (commit), Git takes a snapshot of all your files at that moment. If a file hasn't changed, Git just keeps a link to the previous identical file.</p>
<h4 id="heading-local-operations">Local Operations:</h4>
<p>With Git, most things you do don't need a connection to a server. Because you have the entire project history on your computer, operations are super fast. You can browse project history or see changes between versions without waiting for a server.</p>
<h4 id="heading-data-integrity">Data Integrity:</h4>
<p>Git makes sure nothing gets lost or corrupted. Every file and directory is checksummed, and Git knows if anything changes. </p>
<p>Git uses a SHA-1 hash, a unique code for each version of a file. If any changes are made to the content, even a single character, it will result in a different SHA-1 hash.</p>
<h4 id="heading-append-only-model">Append-Only Model:</h4>
<p>In Git, almost everything adds data to the project, making it hard to accidentally lose information. Once you commit changes, they are safely stored. Experimenting is less risky with Git.</p>
<h3 id="heading-the-three-states-and-basic-git-workflow">The Three States and Basic Git Workflow</h3>
<p>Understanding Git's three states—modified, staged, and committed—is essential for effective version control:</p>
<ul>
<li><strong>Modified</strong>: Changes made to files in your <strong>Working tree</strong> that are not yet committed.</li>
<li><strong>Staged</strong>: Modifications marked for the next commit in the <strong>Staging area</strong> to be included in next commit.</li>
<li><strong>Committed</strong>: Changes permanently stored in the local <strong>Git directory</strong>.</li>
</ul>
<p><strong>Basic Git Workflow</strong>:</p>
<ol>
<li><strong>Modify files</strong> in your working tree.</li>
<li><strong>Stage changes</strong> you want to include in the next commit.</li>
<li><strong>Commit changes</strong>, which permanently saves snapshots to the Git directory.</li>
</ol>
<h2 id="heading-first-time-git-setup">First-Time Git Setup</h2>
<p>Setting up Git for the first time involves customizing your Git environment to suit your preferences. But first, you'll need to download Git from <a target="_blank" href="https://git-scm.com/download/win">Git - Downloads</a> or use the Chocolatey package. Then just follow the installation instructions and you should be good to go.</p>
<h3 id="heading-git-configuration">Git Configuration</h3>
<p>We use the <code>git config</code> tool to customize our Git environment. This tool allows us to both retrieve and set configuration variables that dictate how Git operates. These variables can be stored in three different locations:</p>
<ol>
<li><strong>System-wide Configuration:</strong><br>Stored in the <code>/etc/gitconfig</code> file, these settings apply to all users on the system and all repositories. We can interact with this file using the <code>--system</code> option with <code>git config</code>.</li>
<li><strong>User-specific Configuration:</strong><br>Stored in <code>~/.gitconfig</code> or <code>~/.config/git/config</code>, these values are specific to you as a user. We can interact with this file using the <code>--global</code> option with <code>git config</code>, affecting all repositories you work with on your system.</li>
<li><strong>Repository-specific Configuration:</strong><br>Stored in the <code>.git/config</code> file within a specific repository, these settings override global configurations and apply only to that repository.</li>
</ol>
<p>Each level of configuration overrides values from the previous level. For instance, values in <code>.git/config</code> will override those in <code>~/.gitconfig</code>.</p>
<p>To view all configuration settings and their sources/origins:</p>
<pre><code class="lang-bash">$ git config --list --show-origin
</code></pre>
<h4 id="heading-how-to-configure-your-identity-in-git">How to Configure your identity in Git:</h4>
<p>Identity in Git is used for attributing commits properly. Let's set up your user name and email address.</p>
<pre><code class="lang-bash">$ git config --global user.name <span class="hljs-string">"Your Name"</span>
$ git config --global user.email <span class="hljs-string">"your.email@example.com"</span>
</code></pre>
<p>If you need to override this for specific projects, you can omit the <code>--global</code> option when setting the values, and they'll only apply to that particular repository.</p>
<h4 id="heading-how-to-configure-your-default-text-editor">How to Configure Your Default Text Editor</h4>
<p>After configuring your identity, it's important to set up your default text editor in Git. This text editor will be used when Git needs you to input messages, such as when writing commit messages or resolving merge conflicts.</p>
<p>By default, Git uses your system's default text editor. However, if you prefer to use a different text editor, such as Emacs, you can set it up like this:</p>
<pre><code class="lang-bash">$ git config --global core.editor <span class="hljs-string">"emacs"</span>
</code></pre>
<p>On Windows systems, setting up a different text editor requires specifying the full path to its executable file. For example, if you want to use Notepad++, you might use a command like this:</p>
<pre><code class="lang-bash">$ git config --global core.editor <span class="hljs-string">"'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"</span>
</code></pre>
<p>Make sure you provide the correct path to the executable file of your text editor.</p>
<p>By the way, these – <code>"-multiInst -notabbar -nosession -noPlugin"</code> – are options used to customize the behavior of Notepad++ when it is launched by Git.</p>
<h4 id="heading-how-to-change-default-branch-name-in-git-optional">How to Change default branch name in Git (optional):</h4>
<p>By default, when you initialize a new repository with <code>git init</code>, Git creates a branch named <code>master</code>. But from Git version 2.28 onwards, you have the option to set a different name for the initial branch.</p>
<pre><code class="lang-bash">$ git config --global init.defaultBranch main
</code></pre>
<h4 id="heading-how-to-check-configurationsettings-in-git">How to Check Configuration/settings in Git:</h4>
<p>You can view your Git configuration using:</p>
<pre><code class="lang-bash">$ git config --list
$ git config user.name  <span class="hljs-comment"># To check a specific setting (e.g., user name):</span>
</code></pre>
<p>The <code>git config --list</code> command lists all the configuration settings Git can find at that moment.</p>
<h2 id="heading-how-to-get-help-in-git">How to Get Help in Git</h2>
<p>There are three equivalent ways to get detailed help for any Git command:</p>
<ol>
<li>Git Help Command: <code>$ git help &lt;verb&gt;</code></li>
<li>Using the <code>--help</code> Option: <code>$ git &lt;verb&gt; --help</code></li>
<li>Manual pages (manpages): <code>$ man git-&lt;verb&gt;</code></li>
</ol>
<p>Replace the <code>&lt;verb&gt;</code> with whatever command you need help with. For example, to get help for the <code>config</code> command, you can type:</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">help</span> config
or
$ man git-config
</code></pre>
<p>These commands work offline as well, which is handy.</p>
<p>If you need quick, concise information about the available options for a Git command, you can use the <code>-h</code> option:</p>
<pre><code class="lang-bash">$ git add -h    <span class="hljs-comment"># This will display options available for the add command</span>
</code></pre>
<h2 id="heading-how-to-get-a-git-repository">How to Get a Git Repository</h2>
<p>To start using Git, you typically obtain a Git repository. There are essentially two main ways to get started:</p>
<h3 id="heading-1-how-to-initialize-a-repository-in-an-existing-directory-in-git">1. How to Initialize a Repository in an Existing Directory in Git</h3>
<p>Open a terminal or command prompt. Use the <code>cd</code> command to change the directory to your project's location: <code>cd /path/to/your/project</code>.</p>
<p>Once you're in your project directory, initialize a Git repository by running:</p>
<pre><code class="lang-bash">$ git init
</code></pre>
<p>This command creates a new subdirectory named <code>.git</code> where Git stores all the necessary files for your Git repository. At this point, none of your project files are being tracked yet.</p>
<p>Now, Suppose you have certain files that you want Git to start tracking:</p>
<pre><code class="lang-bash">$ git add *.py        <span class="hljs-comment"># Add all Python files</span>
$ git add README.md   <span class="hljs-comment"># Add README file</span>
$ git commit -m <span class="hljs-string">'Initial commit'</span>
</code></pre>
<p><code>git add</code> adds files to the staging area indicating that you want to include them in the next commit, and then commit the changes. The <code>-m</code> flag allows you to add a descriptive message to the commit.</p>
<h3 id="heading-2-how-to-clone-an-existing-repository-in-git">2. How to Clone an Existing Repository in Git:</h3>
<p>The second way to obtain a Git repository is by cloning an existing one. This is useful when you want to work on a project that already exists elsewhere (for example, a project you'd like to contribute to).</p>
<p><strong>Note:</strong> When you clone a repository, Git retrieves a full copy of nearly all data that the server has. This includes every version of every file for the history of the project. This means you'll have a complete copy of the repository's history on your local machine.</p>
<p>To clone a repo, Use the <code>git clone</code> command followed by the URL of the repo you want to clone. For example, to clone the grok-1 repository, you can use:</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">clone</span> https://github.com/xai-org/grok-1.git
</code></pre>
<p>This creates a directory named grok-1, initializes a <code>.git</code> directory inside it, and pulls down all the data for that repository.</p>
<p>BTW, <code>.git</code> is just a convention to signify that the URL points to a Git repository. You can use it or not, it doesn't matter.</p>
<p>If you want to clone into a directory with a different name, you can specify it. To clone the grok-1 repo into a directory named "chatgpt" instead of "grok-1", do this:</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">clone</span> https://github.com/xai-org/grok-1.git chatgpt
</code></pre>
<p>Git provides various transfer protocols you can use for cloning repos. The example above uses the <code>https://</code> protocol, but you may also see <code>git://</code> or <code>user@server:path/to/repo.git</code>, which uses the SSH transfer protocol.</p>
<h2 id="heading-how-to-record-changes-to-the-repository">How to Record Changes to the Repository</h2>
<p>Now that you have a Git repository set up, you'll often need to make changes and record those changes in your repository. The process involves tracking files, staging changes, and committing snapshots. Let's explore the steps involved:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/lifecycle.png" alt="Image" width="600" height="400" loading="lazy">
<em>pic credit - https://git-scm.com/</em></p>
<h3 id="heading-1-how-to-check-the-status-of-your-files-in-git">1. How to Check the Status of Your Files in Git:</h3>
<p>When working with a Git repository, it's crucial to understand the status of your files. </p>
<p>Git categorizes files into two types: tracked and untracked. Tracked files are those that Git recognizes, either because they were part of the last snapshot (commit) or have been staged. Untracked files are everything else—files that Git is not currently monitoring. To check the status of your repository:</p>
<pre><code class="lang-bash">$ git status
</code></pre>
<p>This command provides comprehensive information about the current branch, its synchronization status, and the status of your files. </p>
<p><code>git status</code> also suggests actions you can take. For instance, when files are modified but not staged for commit, <code>git status</code> suggests using <code>git add &lt;file&gt;</code> to stage them. It also suggests using <code>git checkout -- &lt;file&gt;</code> to discard changes in the working directory. These suggestions streamline your workflow by providing quick access to relevant Git commands.</p>
<p>Also, <code>git status</code> offers a Short Status mode (<code>git status -s</code>), which presents a more concise view of your changes using symbols like M (modified), A (added), and ?? (untracked) to represent file statuses.</p>
<h3 id="heading-2-how-to-track-new-files-in-git">2. How to Track New Files in Git</h3>
<p>When you create a new file in your project, Git initially considers it untracked. To start tracking a new file, you need to add it to the staging area using the <code>git add</code> command.</p>
<p>For instance, let's create a new file called <code>index.html</code> for our project and add it to the staging area:</p>
<pre><code class="lang-bash">$ touch index.html
$ git add index.html
</code></pre>
<p>After adding, running <code>git status</code> again will show that the <code>index.html</code> file is now tracked and staged for commit.</p>
<h3 id="heading-3-how-to-stage-modified-files-in-git">3. How to Stage Modified Files in Git</h3>
<p>If you modify an existing tracked file, you need to stage the changes using <code>git add</code>. Let's say we modify an existing file called <code>styles.css</code></p>
<pre><code class="lang-bash">$ vim styles.css
</code></pre>
<p>After making changes, stage the file:</p>
<pre><code class="lang-bash">$ git add styles.css
</code></pre>
<p>Now, when you check the status, you'll see both the modified file and the new file staged for commit.</p>
<h3 id="heading-4-how-to-ignore-files-in-git">4. How to Ignore Files in Git</h3>
<p>Often, there are files or directories within a project that aren't intended for Git tracking. These might include log files, build artifacts, or sensitive information like local environment settings (such as *.env or config.json). You can specify these files to be ignored using a <code>.gitignore</code> file.</p>
<p>Create a <code>.gitignore</code> file :</p>
<pre><code class="lang-bash">$ nano .gitignore
</code></pre>
<p>List the patterns of files or directories you want to ignore.:</p>
<pre><code class="lang-bash">$ <span class="hljs-built_in">echo</span> <span class="hljs-string">'*.log'</span> &gt;&gt; .gitignore
$ <span class="hljs-built_in">echo</span> <span class="hljs-string">'build/'</span> &gt;&gt; .gitignore
</code></pre>
<p>Here, we're telling Git to ignore all files with a <code>.log</code> extension and the <code>build/</code> directory.</p>
<p><strong>Note:</strong> Files already tracked by Git before being added to the <code>.gitignore</code> file will remain tracked. To remove them, you'll need to manually untrack them using Git commands. </p>
<p>Here are some patterns you can use to work more effectively in Git.</p>
<ul>
<li><strong>Target individual files or file extensions precisely:</strong> For example, <code>test.txt</code> ignores only that specific file, while <code>*.log</code> ignores all files ending with <code>.log</code>.</li>
<li><strong>Wildcards for broader matches:</strong> The asterisk (<code>*</code>) wildcard matches any number of characters. For example, <code>*.doc</code> ignores all files with the <code>.doc</code> extension, regardless of their name.</li>
</ul>
<h3 id="heading-5-how-to-view-changes-in-git">5. How to View Changes in Git:</h3>
<p>If you want to see the exact changes you've made to your files before committing, you can use the <code>git diff</code> command.</p>
<p>To see unstaged changes:</p>
<pre><code class="lang-bash">$ git diff
</code></pre>
<p>And to see staged changes:</p>
<pre><code class="lang-bash">$ git diff --cached README.md
</code></pre>
<p><code>git diff</code> provides a detailed view of the actual modifications. Use <code>git diff &lt;filename&gt;</code> to focus on changes within a particular file.</p>
<h3 id="heading-6-how-to-commit-changes">6. How to Commit Changes:</h3>
<p>When you are ready to commit your changes, use the <code>git commit</code> command. This opens your text editor for you to provide a commit message. Alternatively, you can use the <code>-m</code> flag to add a commit message directly:</p>
<p>Once you have staged the changes you want to include in the commit, you can commit them using <code>git commit</code></p>
<pre><code class="lang-bash">$ git commit -m <span class="hljs-string">"Your commit message here"</span>
</code></pre>
<h3 id="heading-7-how-to-remove-files-in-git">7. How to Remove Files in Git:</h3>
<p>If you need to remove a file from Git's tracking, you can use <code>git rm</code>. It remove the file from both the repository and working directory. Suppose you want to remove a file named <code>temp.txt</code>:</p>
<pre><code class="lang-bash">$ git rm temp.txt
</code></pre>
<p>If you only want to remove it from the repository but keep it in the working directory, use the <code>--cached</code> option:</p>
<pre><code class="lang-bash">$ git rm --cached temp.txt
</code></pre>
<h3 id="heading-8-how-to-move-or-rename-files-in-git">8. How to Move (or Rename) Files in Git:</h3>
<p>Git doesn't explicitly track file movements. But you can use <code>git mv</code> to rename or move files within your repository. For example, to rename <code>old_file.txt</code> to <code>new_file.txt</code>:</p>
<pre><code class="lang-bash">$ git mv old_file.txt new_file.txt
</code></pre>
<p>It is equivalent to manually moving the file, followed by using <code>git rm</code> to remove the old file, and then <code>git add</code> to add the new file. <code>git mv</code> basically consolidates these steps into a single command.</p>
<p>These commands form the basic workflow for making changes, staging them, and committing them to your Git repository.</p>
<h2 id="heading-how-to-view-commit-history-in-git">How to View Commit History in Git</h2>
<p>After creating multiple commits or cloning a repository, the <code>git log</code> command allows you to examine the commit history. </p>
<p>By default, it lists commits in reverse chronological order, displaying each commit with its SHA-1 checksum, author's name and email, date, and commit message.<br>Now let's see how can we enhance this output:</p>
<h3 id="heading-how-to-view-commit-differences-in-git">How to View Commit Differences in Git:</h3>
<p>To view the difference introduced in each commit, you can use the <code>-p</code> or <code>--patch</code> option:</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">log</span> -p -2    <span class="hljs-comment"># -2 is used to view the differences introduced in each of the last two commits</span>
</code></pre>
<h3 id="heading-how-to-display-statistics-in-git">How to Display Statistics in Git:</h3>
<p>The <code>--stat</code> option provides summarized statistics for each commit, including the modified files, lines added/deleted, and a summary.</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">log</span> --<span class="hljs-built_in">stat</span>
</code></pre>
<h3 id="heading-how-to-customize-git-log-output-format">How to Customize Git Log Output Format:</h3>
<p>The <code>--pretty</code> option allows you to alter the log output format. Various options are available for different formats:</p>
<ul>
<li><code>oneline</code>: Concise, single-line summary of each commit. </li>
<li><code>short</code>: Default format with author, date, and message. </li>
<li><code>full</code>: Detailed format with commit hash, author, date, message, and diff.</li>
<li><code>fuller</code>: More detailed format, including full file paths. </li>
<li><code>format</code>: Customize the output using format specifiers.</li>
</ul>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">log</span> --pretty=oneline
</code></pre>
<p><strong>Useful format specifiers for</strong> <code>--pretty=format</code>:</p>
<ul>
<li><code>%h:</code> Abbreviated commit hash</li>
<li><code>%an:</code> Author name</li>
<li><code>%ae:</code> Author email</li>
<li><code>%ad:</code> Author date</li>
<li><code>%s:</code> Subject (commit message)</li>
</ul>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">log</span> --pretty=format:<span class="hljs-string">"%h %an %ad %s"</span>
</code></pre>
<p><strong>ASCII Graph</strong>:</p>
<p>Using <code>--graph</code>, you can also visualize branch and merge history.</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">log</span> --pretty=format:<span class="hljs-string">"%h %s"</span> --graph
</code></pre>
<h3 id="heading-how-to-limit-git-log-output">How to Limit Git Log Output:</h3>
<p>In addition to formatting options, <code>git log</code> offers various limiting options to refine the displayed commit history.</p>
<ul>
<li><code>-&lt;n&gt;:</code> Shows only the last n commits.</li>
<li><code>--since, --until:</code> Limits commits to those made after/before the specified date.</li>
<li><code>--author:</code> Shows commits only by a specific author.</li>
<li><code>--grep:</code> Filters commits by a keyword in the commit messages.</li>
<li><code>-S:</code> Shows commits changing</li>
</ul>
<p><strong>Example Usage:</strong> View the last 3 commits by author Abbey since a certain date, with patch details:</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">log</span> --author=<span class="hljs-string">"Abbey"</span> --since=<span class="hljs-string">"2024-01-01"</span> -p -3
</code></pre>
<h2 id="heading-how-to-undo-things-in-git">How to Undo Things in Git</h2>
<p>Undoing changes is a common need in Git, and several options are available for this purpose.</p>
<h3 id="heading-how-to-undo-a-commit-in-git">How to Undo a Commit in Git</h3>
<p>If you've committed too early or need to make additional changes to the last commit, use this command:</p>
<pre><code class="lang-bash">$ git commit --amend
</code></pre>
<p>This opens the commit message editor allowing you to modify the message. If no changes were made since the last commit, it simply allows you to edit the commit message.</p>
<p><strong>Note</strong>: Only amend commits that are still local and haven't been pushed yet to avoid issues for collaborators.</p>
<h3 id="heading-how-to-unstage-a-staged-file-with-git-reset">How to Unstage a Staged File with <code>git reset</code></h3>
<p>To unstage a file that was accidentally included, you can use the <code>git reset HEAD &lt;file&gt;</code> command. For example:</p>
<pre><code class="lang-bash">$ git reset HEAD CONTRIBUTING.md
</code></pre>
<p>The file is unstaged, allowing you to make further changes without committing the unintended ones.</p>
<h3 id="heading-how-to-unmodify-a-modified-file-with-git-checkout">How to Unmodify a Modified File with <code>git checkout</code></h3>
<p>Suppose you made some modifications to files that you later realize you don't want to keep. Use <code>git checkout -- &lt;file&gt;</code> to discard the changes made to a file and revert it back to its previous state.</p>
<pre><code class="lang-bash">$ git checkout -- CONTRIBUTING.md
</code></pre>
<p>This will replace the modified file with the last staged or committed version. </p>
<h3 id="heading-undoing-things-with-git-restore">Undoing Things with <code>git restore</code></h3>
<p>Let's explore the alternatives introduced by Git version 2.23.0, <code>git restore</code>, which serves as an alternative to <code>git reset</code> for many undo operations.</p>
<h4 id="heading-how-to-unstage-a-staged-file-with-git-restore">How to unstage a staged file with <code>git restore</code></h4>
<p>If you accidentally stage a file that you didn't intend to commit, you can use <code>git restore --staged &lt;file&gt;</code> to unstage it.</p>
<pre><code class="lang-bash">$ git restore --staged CONTRIBUTING.md
</code></pre>
<p>The file is unstaged, similar to <code>git reset HEAD &lt;file&gt;</code>, allowing you to make further changes without committing the unintended ones.</p>
<h4 id="heading-how-to-unmodify-a-modified-file-with-git-restore">How to unmodify a modified file with <code>git restore</code></h4>
<p>To discard changes made to a file in the working directory, use <code>git restore &lt;file&gt;</code>:</p>
<pre><code class="lang-bash">$ git restore CONTRIBUTING.md
</code></pre>
<p>Similar to <code>git checkout -- &lt;file&gt;</code>, this command discard the changes made to the specified file, reverting it back to the state it was in at the last commit.</p>
<p><strong>Important Note:</strong> Use commands like <code>git reset</code>, <code>git checkout --</code>,<code>git restore</code> cautiously as they can discard local changes permanently. Use these commands when you're certain that the changes are not needed and you don't have any unsaved local changes. </p>
<p><strong>Alternatives:</strong> Stashing and branching are alternative methods to temporarily set aside changes without discarding them entirely. These methods are safer if you're unsure about discarding changes.</p>
<h2 id="heading-how-to-work-with-remotes-in-git">How to Work with Remotes in Git</h2>
<p>Remote repositories are versions of your project hosted on the internet or a network. Collaborating with others involves managing these remote repositories, including adding, removing, and inspecting them. Let's learn how to manage them effectively.</p>
<h3 id="heading-how-to-show-your-remotes-in-git">How to Show Your Remotes in Git</h3>
<p>To start, let's see which remote servers are configured for our project using:</p>
<pre><code class="lang-bash">$ git remote
</code></pre>
<p>This command lists the shortnames of all remote handles we've specified. For instance, if we've cloned a repository, we'll typically see <code>origin</code>, the default name Git assigns to the server we cloned from.</p>
<p>Adding the <code>-v</code> option provides additional details, such as the URLs associated with each remote.</p>
<pre><code class="lang-bash">$ git remote -v
</code></pre>
<p>This displays both the fetch and push URLs for each remote, allowing us to understand where our project is hosted and how we interact with it.</p>
<h3 id="heading-how-to-add-remote-repositories-in-git">How to Add Remote Repositories in Git</h3>
<p>To explicitly add a new remote repository, use <code>git remote add &lt;shortname&gt; &lt;url&gt;</code>:</p>
<pre><code class="lang-bash">$ git remote add example https://github.com/example/example.git
</code></pre>
<p>Here, we've added a remote named <code>example</code> with the specified URL. This allows us to reference this remote repository using the shortname <code>example</code> in our commands.</p>
<h3 id="heading-how-to-fetch-and-pull-from-remotes-in-git">How to Fetch and Pull from Remotes in Git</h3>
<p>To fetch data from a remote repository, we use the <code>git fetch</code> command followed by the remote name:</p>
<pre><code class="lang-bash">$ git fetch origin // Here we are not specifying any particular branch.
</code></pre>
<p>It downloads any new changes from the <code>origin</code> remote repository to our local repository, allowing us to stay up-to-date with the latest developments. </p>
<p>Alternatively, if we want to fetch and merge changes from a remote branch into our current branch in a single step, we use the <code>git pull</code> command:</p>
<pre><code class="lang-bash">$ git pull origin master
</code></pre>
<p>Here, we're specifically pulling changes from the <code>master</code> branch of the <code>origin</code> remote repository into our current branch.</p>
<h3 id="heading-how-to-push-changes-to-remotes-in-git">How to Push Changes to Remotes in Git</h3>
<p>To share our work with others, we push our changes to a remote repository using:</p>
<pre><code class="lang-bash">$ git push origin main
</code></pre>
<p>In this example, we're pushing our local changes to the <code>main</code> branch of the <code>origin</code> remote repository.</p>
<h3 id="heading-how-to-inspect-a-remote-in-git">How to Inspect a Remote in Git</h3>
<p>Lastly, we can inspect a remote repository to gather more information about it using:</p>
<pre><code class="lang-bash">$ git remote show origin
</code></pre>
<p>This command displays details such as the fetch and push URLs, the tracked branches, and local branch configurations associated with the <code>origin</code> remote repository.</p>
<h3 id="heading-how-to-rename-remotes-in-git">How to Rename Remotes in Git</h3>
<p>Now Suppose we want to rename a remote's shortname from <code>example</code> to <code>new-example</code>:</p>
<pre><code class="lang-bash">$ git remote rename example new-example
</code></pre>
<h3 id="heading-how-to-remove-remotes-in-git">How to Remove Remotes in Git</h3>
<p>If, for some reason, we no longer need a remote repository and want to remove it from our project:</p>
<pre><code class="lang-bash">$ git remote remove new-example
or
$ git remote rm new-example
</code></pre>
<p>After removal, the remote-tracking branches and associated configuration settings are also deleted.</p>
<h2 id="heading-tagging-in-git">Tagging in Git</h2>
<p>Tagging in Git is a fundamental feature allowing developers to mark specific points in a repository's history as significant. Typically, tags are used to denote release points, such as v1.0, v2.0, and so forth.</p>
<h3 id="heading-how-to-list-existing-tags-in-git">How to List Existing Tags in Git</h3>
<p>Imagine you're working on a project with multiple release versions. To list existing tags:</p>
<pre><code class="lang-bash">$ git tag
</code></pre>
<p>Also, you can search for tags matching a specific pattern using the <code>-l</code> or <code>--list</code> option. For Example:</p>
<pre><code class="lang-bash">$ git tag -l <span class="hljs-string">"v2.0*"</span>
</code></pre>
<p>This command will list tags like <code>v2.0</code>, <code>v2.0-beta</code>, and so on, matching the specified pattern.</p>
<h3 id="heading-how-to-create-tags-in-git">How to Create Tags in Git</h3>
<p>Git supports two types of tags: lightweight and annotated.</p>
<h4 id="heading-lightweight-tags">Lightweight Tags</h4>
<p>Use lightweight tags when you want to mark a specific commit without adding any additional information. Example:</p>
<pre><code class="lang-bash">$ git tag v1.1-lw
</code></pre>
<p>To view commit information associated with this tag, use:</p>
<pre><code class="lang-bash">$ git show v1.1-lw
</code></pre>
<h4 id="heading-annotated-tags">Annotated Tags</h4>
<p>Annotated tags, on the other hand, contain additional info such as tagger information, date, and a tagging message.</p>
<p>Creating an annotated tag involves using the <code>-a</code> option with the <code>git tag</code> command, along with a tagging message. e.g:</p>
<pre><code class="lang-bash">$ git tag -a v2.0 -m <span class="hljs-string">"Release version 2.0"</span>
</code></pre>
<p>To view detailed information about this tag, including the commit it points to and the tagging message, use:</p>
<pre><code class="lang-bash">$ git show v2.0
</code></pre>
<h3 id="heading-how-to-tag-an-older-commit-in-git">How to tag an older commit in Git</h3>
<p>Sometimes, you might forget to tag a specific commit. Not to worry, you can tag it later by specifying the commit checksum</p>
<p>Example: suppose you forgot to tag a commit with ID <code>abcdefg</code>. You can tag it as follows:</p>
<pre><code class="lang-bash">$ git tag -a v1.2 abcdefg
</code></pre>
<h4 id="heading-how-to-push-tag-to-a-remote-repo-in-git">How to Push Tag to a Remote repo in Git</h4>
<p>To push a specific tag to a remote server, you can use:</p>
<pre><code class="lang-bash">$ git push origin &lt;tagname&gt;
</code></pre>
<p>If you have multiple tags and want to push them all at once, you can use the <code>--tags</code> option:</p>
<pre><code class="lang-bash">$ git push origin --tags
</code></pre>
<h4 id="heading-how-to-delete-tags-in-git">How to Delete Tags in Git</h4>
<p>To delete a tag locally (removing from local repo):</p>
<pre><code class="lang-bash">$ git tag -d &lt;tagname&gt;
</code></pre>
<p>For Example, to delete a lightweight tag named <code>v1.4-lw</code>:</p>
<pre><code class="lang-bash">$ git tag -d v1.4-lw
</code></pre>
<p>On the other hand, you can delete a tag from a remote server in two ways:</p>
<ol>
<li>Using the <code>git push</code> command with a refspec:</li>
</ol>
<pre><code class="lang-bash">$ git push origin :refs/tags/v1.1-lw
</code></pre>
<ol start="2">
<li>Using the <code>--delete</code> option with <code>git push</code>:</li>
</ol>
<pre><code class="lang-bash">$ git push origin --delete v1.1-lw
</code></pre>
<h4 id="heading-how-to-check-out-tags-in-git">How to Check Out Tags in Git</h4>
<p>To view the state of files at a specific tag, you can check out that tag:</p>
<pre><code class="lang-bash">$ git checkout v2.0
</code></pre>
<p>This command puts your repository in a "detached HEAD" state, where you can view files but cannot make changes directly.</p>
<p>If you need to work on files at that tag, it's better to create a new branch:</p>
<pre><code class="lang-bash">$ git checkout -b v2.0-branch v2.0
</code></pre>
<p>Now you can make changes and commits without altering the original tag.</p>
<h2 id="heading-git-aliases">Git Aliases</h2>
<p>Git aliases are shortcuts or custom commands that you can create to simplify and streamline your Git workflow.  </p>
<p>To create a Git alias, you use the <code>git config</code> command with the <code>--global</code> flag to make the alias available across all your Git repositories. </p>
<h3 id="heading-basic-aliases-for-common-commands">Basic Aliases for Common Commands</h3>
<p>You can create aliases for frequently used Git commands to make them easier to remember and type. For example:</p>
<pre><code class="lang-bash">$ git config --global alias.co checkout
$ git config --global alias.br branch
$ git config --global alias.ci commit
</code></pre>
<p>Now, instead of typing out the full commands, you can use shorter aliases like <code>git co</code>, <code>git br</code>, and <code>git ci</code> respectively.</p>
<p>You can also <strong>create custom aliases for actions you frequently perform</strong> or for improving command readability. Example:</p>
<pre><code class="lang-bash">$ git config --global alias.unstage <span class="hljs-string">'reset HEAD --'</span>
</code></pre>
<p>Now, you can use <code>git unstage &lt;file&gt;</code> instead of <code>git reset HEAD -- &lt;file&gt;</code> to unstage a file.</p>
<h4 id="heading-how-to-combine-multiple-commands-in-git">How to Combine Multiple Commands in Git</h4>
<p>Aliases can also be used to combine multiple Git commands into a single alias. For example, let's create an alias to stage all changes and then commit them with a single command:</p>
<pre><code class="lang-bash">$ git config --global alias.commitall <span class="hljs-string">'!git add -A &amp;&amp; git commit'</span>
</code></pre>
<p>Now, running <code>git commitall</code> will stage all changes (<code>git add -A</code>) and then commit them, saving you time and keystrokes.</p>
<h2 id="heading-git-branching">Git Branching</h2>
<p>Branches in Git provide a powerful way to manage your project's codebase, allowing for parallel development and experimentation without affecting the main codebase.</p>
<p>Git branching allows you to diverge from the main line of development, work on features or fixes, and then merge your changes back. Unlike many other version control systems, Git's branching model is lightweight and efficient, making branching operations nearly instantaneous.</p>
<h3 id="heading-what-are-branches-in-git">What are Branches in Git?</h3>
<p>A branch is a lightweight, movable pointer to a commit. The default branch name is often "master," but it's not special – it's like any other branch.</p>
<p>Creating and switching between branches allows you to work on different features simultaneously.</p>
<h3 id="heading-how-to-create-a-new-branch-in-git">How to Create a New Branch in Git:</h3>
<p>When you want to start working on a new feature or experiment with an idea, you can create a new branch in Git. This new branch serves as a separate line of development, allowing you to make changes without affecting the main branch.</p>
<pre><code class="lang-bash">$ git branch new_feature
</code></pre>
<p>This command creates a new branch named 'new-feature' pointing to the same commit as the current branch. Branches can coexist, and Git keeps a special pointer called <code>HEAD</code> to indicate the current branch.</p>
<h3 id="heading-understanding-branches">Understanding Branches</h3>
<p>Firstly, let's grasp the basics of branches in Git. When you initialize a Git repository, you start with a default branch, usually named 'master' or 'main'. Branches are essentially pointers to commits, enabling you to work on different features or fixes independently. </p>
<p>To view all branches in your repository, use the command:</p>
<pre><code class="lang-bash">$ git branch
</code></pre>
<p>This will display a list of branches with an asterisk (*) indicating the currently checked out branch. For additional information like the last commit on each branch, utilize:</p>
<pre><code class="lang-bash">$ git branch -v
</code></pre>
<h3 id="heading-how-to-switch-to-another-branch-in-git">How to Switch to Another Branch in Git:</h3>
<p>To switch to an existing different branch, use <code>git checkout</code>. </p>
<pre><code class="lang-bash">$ git checkout new_feature
</code></pre>
<p>This command switches the 'HEAD' pointer to the 'new-feature' branch, making it the currently active branch.</p>
<p>To create and switch to a new branch in one operation:</p>
<pre><code class="lang-bash">$ git checkout -b &lt;newbranchname&gt;
</code></pre>
<p>In Git version 2.23 onwards, you can use <code>git switch</code> instead of <code>git checkout</code>.</p>
<ul>
<li>Switch to an existing branch: <code>git switch existing-branch</code>.</li>
<li>Create and switch to new branch: <code>git switch -c new-branch</code>.</li>
</ul>
<h3 id="heading-how-to-visualize-branches-in-git">How to Visualize Branches in Git:</h3>
<p>After creating and switching branches, you can visualize the branch structure using:</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">log</span> --oneline --decorate --graph --all
</code></pre>
<p>This command displays a concise and graphical representation of the commit history and branch pointers, allowing you to see how branches diverge and merge over time.</p>
<h2 id="heading-how-to-manage-branches-in-git">How to Manage Branches in Git</h2>
<h3 id="heading-how-to-manage-merged-branches">How to Manage Merged Branches</h3>
<p>As your project evolves, you'll merge branches back into the main branch once their changes are finalized. To identify merged branches, execute:</p>
<pre><code class="lang-bash">$ git branch --merged
</code></pre>
<p>This command lists branches that have been successfully merged into the current branch. These branches are generally safe to delete using:</p>
<pre><code class="lang-bash">$ git branch -d branch_name
</code></pre>
<p>However, for branches containing unmerged work, use:</p>
<pre><code class="lang-bash">$ git branch --no-merged
</code></pre>
<p>Deleting such branches requires the '-D' flag:</p>
<pre><code class="lang-bash">$ git branch -D branch_name
</code></pre>
<p>This ensures that you don't inadvertently lose any unmerged changes.</p>
<h3 id="heading-how-to-rename-branches">How to Rename Branches</h3>
<p>To rename a local branch:</p>
<pre><code class="lang-bash">$ git branch --move old_branch_name new_branch_name
</code></pre>
<p>This command updates the branch name locally. To reflect the change on the remote repository, push the renamed branch:</p>
<pre><code class="lang-bash">$ git push --set-upstream origin new_branch_name
</code></pre>
<p>Verify the changes using: </p>
<pre><code class="lang-bash">$ git branch --all
</code></pre>
<p>Ensure to delete the old branch on the remote:</p>
<pre><code class="lang-bash">$ git push origin --delete old_branch_name
</code></pre>
<p>This ensures uniformity across local and remote repositories.</p>
<h3 id="heading-how-to-change-the-default-branch-name">How to Change the Default Branch Name</h3>
<p>Renaming the default branch, often 'master', requires caution and coordination, as it impacts project integrations and collaborators.</p>
<pre><code class="lang-bash">$ git branch --move master main
</code></pre>
<p>Once renamed, push the updated branch to the remote repo:</p>
<pre><code class="lang-bash">$ git push --set-upstream origin main
</code></pre>
<p>Make sure you remember to update references and configurations across dependencies, tests, scripts, and repository hosts. Once done, delete the old master branch on the remote:</p>
<pre><code class="lang-bash">$ git push origin --delete master
</code></pre>
<p>This is <strong>different from <code>$ git config --global init.defaultBranch main</code></strong> that we discussed in the configuration part in the following ways:</p>
<ul>
<li><code>$ git branch --move master main</code>: This command renames the existing branch named "master" to "main" within the current repository. It is a sort of local operation that affects only the repository.</li>
<li><code>$ git config --global init.defaultBranch main</code>: This command sets the default branch name for new repositories globally. It does not rename existing branches but ensures that any new repositories created thereafter will use "main" as the default branch name instead of "master".</li>
</ul>
<p><strong>Additional Resource</strong>: Consider checking out this official Git <a target="_blank" href="https://git-scm.com/book/en/v2/Git-Branching-Remote-Branches">resource</a> for its informative visuals and diagrams which can provide you more clarity on remote branches and branch management concepts.</p>
<h2 id="heading-branching-workflow">Branching Workflow</h2>
<p>Let's understand branches in more detail and look at a common branching workflow that is used in large projects.</p>
<h3 id="heading-long-running-branches">Long-Running Branches:</h3>
<p>In Git, long-running branches are branches that remain open over an extended period. </p>
<h3 id="heading-topic-branches">Topic Branches:</h3>
<p><code>Topic</code>/<code>Feature</code> branches are short-lived branches created for specific features or pieces of work. Unlike long-running branches, which persist over time, topic branches are created, used, and often deleted once the work is complete. </p>
<p><strong>Example:</strong> Let's consider a scenario where a team maintains two long-running branches: <code>master</code> and <code>develop</code>.</p>
<ul>
<li>The <code>master</code> branch contains only stable code, possibly what has been released or will be released.</li>
<li>The <code>develop</code> branch acts as a staging area for ongoing development. While it might not always be stable, it serves as a testing ground for new features.</li>
</ul>
<p>Developers merge changes from feature branches into the <code>develop</code> branch for testing. Once features are thoroughly tested and stable, they are merged into <code>master</code>.</p>
<p>Note how changes progress through different levels of stability, moving from the least stable (feature branches) to more stable ones (such as the develop branch), as they undergo testing and refinement, and are finally merged into the most stable main/master branch. </p>
<p>This maintains a clear separation between stable and development code, ensuring that only thoroughly tested features make their way into the stable release.</p>
<h3 id="heading-branching-best-practices">Branching Best Practices</h3>
<ol>
<li><strong>Create Descriptive Branch Names</strong>: Use meaningful branch names that reflect the purpose or feature being developed.</li>
<li><strong>Delete Unused Branches</strong>: Once a branch has served its purpose and its changes have been merged into the main branch, consider deleting it to keep the repository clean and manageable.</li>
</ol>
<h2 id="heading-rebasing-in-git">Rebasing in Git</h2>
<p>In Git, when you're working with branches, there are two primary ways to integrate changes from one branch into another: merging and rebasing. </p>
<p>Unlike merging, which can create a cluttered history with multiple merge commits, rebasing produces a linear history, making it easier to understand the sequence of changes made over time. </p>
<h3 id="heading-basic-rebase-example">Basic Rebase Example:</h3>
<p>Imagine you're working on a project with two branches: "feature" and "master". You've made some commits on the "feature" branch and now want to integrate these changes into the "master" branch using rebasing.</p>
<p>First, you switch to your "feature" branch:</p>
<pre><code class="lang-bash">$ git checkout feature
</code></pre>
<p>Then, you rebase your feature branch onto the master branch: </p>
<pre><code class="lang-bash">$ git rebase master
</code></pre>
<p>This command takes all the commits/changes you made on your "feature" branch and applies them on top of the latest commits in the "master" branch, and replays the commits one by one.</p>
<p>Not only master branch, you can also rebase a topic branch onto another topic branch. Example:</p>
<p>Suppose you're working on a project with two feature branches: "frontend" and "backend". You made some commits on the "frontend" branch and now want to integrate these changes into the "backend" branch.</p>
<p>Let's use a different approach this time -<br>use <code>--onto</code> option of <code>git rebase</code> to rebase the "frontend" branch onto the "backend" branch:</p>
<pre><code class="lang-bash">$ git rebase --onto backend frontend
</code></pre>
<p>After rebasing, switch back to the "backend" branch and perform a fast-forward merge:</p>
<pre><code class="lang-bash">$ git checkout backend
$ git merge frontend
</code></pre>
<p>Now, your project history appears linear, reflecting the sequential integration of changes from the "frontend" branch into the "backend" branch.</p>
<h3 id="heading-rebasing-vs-merging-which-is-better">Rebasing vs Merging: Which is Better?</h3>
<h4 id="heading-rebasing-use-cases">Rebasing Use Cases:</h4>
<ul>
<li>Suitable for feature branches that need a clean integration into the mainline branch.</li>
<li>Preferred for open-source contributions where a clean commit history is valued.</li>
</ul>
<h4 id="heading-merging-use-cases">Merging Use Cases:</h4>
<ul>
<li>Appropriate for collaborative environments where transparency in the project's development process is crucial.</li>
<li>Useful for projects where maintaining an accurate historical record is a priority.</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This handbook serves as a comprehensive guide to understanding and utilizing Git, a powerful version control system widely used in software development. </p>
<p>From basic workflows to setting up a repository, tagging, and branching remote repositories, we have learnt a comprehensive suite of features that will help streamlining the development process.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn React – A Handbook for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ The goal of this handbook is to provide gentle step-by-step instructions that will help you learn the key concepts of React. Instead of covering all the theories and concepts of React in their entirety, I'll be teaching you important building blocks ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-for-beginners-handbook/</link>
                <guid isPermaLink="false">66bd919d1bb54b9103c678c0</guid>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nathan Sebhastian ]]>
                </dc:creator>
                <pubDate>Fri, 01 Mar 2024 00:34:46 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/03/Learn-React-Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The goal of this handbook is to provide gentle step-by-step instructions that will help you learn the key concepts of React.</p>
<p>Instead of covering all the theories and concepts of React in their entirety, I'll be teaching you important building blocks of the library. You'll learn about JSX, components, props, states, event handlers, creating forms, and running network requests.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-requirements">Requirements</a></li>
<li><a class="post-section-overview" href="#heading-chapter-1-introduction">Chapter 1: Introduction</a><ul>
<li><a class="post-section-overview" href="#heading-computer-setup">Computer Setup</a></li>
<li><a class="post-section-overview" href="#heading-your-first-react-application">Your First React Application</a></li>
<li><a class="post-section-overview" href="#heading-explaining-the-source-code">Explaining the Source Code</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-2-how-to-create-react-components">Chapter 2: How to Create React Components</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-return-multiple-elements-with-fragments">How to Return Multiple Elements With Fragments</a></li>
<li><a class="post-section-overview" href="#heading-how-to-render-to-the-screen">How to Render to the Screen</a></li>
<li><a class="post-section-overview" href="#heading-how-to-write-comments-in-react">How to Write Comments in React</a></li>
<li><a class="post-section-overview" href="#heading-how-to-compose-multiple-components-as-one">How to Compose Multiple Components as One</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-3-making-sense-of-jsx">Chapter 3: Making Sense of JSX</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-render-a-list-using-jsx">How to Render a List Using JSX</a></li>
<li><a class="post-section-overview" href="#heading-how-to-add-the-class-attribute">How to Add the Class Attribute</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-4-props-and-states">Chapter 4: Props and States</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-pass-down-multiple-props">How to Pass Down Multiple Props</a></li>
<li><a class="post-section-overview" href="#heading-props-are-immutable">Props are Immutable</a></li>
<li><a class="post-section-overview" href="#heading-state-in-react">State in React</a></li>
<li><a class="post-section-overview" href="#heading-how-to-pass-state-to-a-child-component">How to Pass State to a Child Component</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-react-devtools-to-inspect-states-and-props">How to Use React DevTools to Inspect States and Props</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-5-react-conditional-rendering">Chapter 5: React Conditional Rendering</a><ul>
<li><a class="post-section-overview" href="#heading-partial-rendering-with-a-regular-variable">Partial Rendering with a Regular Variable</a></li>
<li><a class="post-section-overview" href="#heading-inline-rendering-with-the-ampamp-operator">Inline Rendering with the &amp;&amp; Operator</a></li>
<li><a class="post-section-overview" href="#heading-inline-rendering-with-the-conditional-ternary-operator">Inline Rendering with the Conditional (Ternary) Operator</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-6-how-to-handle-user-events">Chapter 6: How to Handle User Events</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-change-the-ui-by-handling-events">How to Change the UI by Handling Events</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-7-css-in-react">Chapter 7: CSS in React</a><ul>
<li><a class="post-section-overview" href="#heading-react-inline-styling">React Inline Styling</a></li>
<li><a class="post-section-overview" href="#heading-css-files">CSS Files</a></li>
<li><a class="post-section-overview" href="#heading-css-modules">CSS Modules</a></li>
<li><a class="post-section-overview" href="#heading-tailwind-css">Tailwind CSS</a></li>
<li><a class="post-section-overview" href="#heading-which-one-should-you-use">Which One Should You Use?</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-8-how-to-build-forms-in-react">Chapter 8: How to Build Forms in React</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-handle-form-input">How to Handle Form Input</a></li>
<li><a class="post-section-overview" href="#heading-how-to-handle-form-submission">How to Handle Form Submission</a></li>
<li><a class="post-section-overview" href="#heading-how-to-handle-form-validation">How to Handle Form Validation</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-9-network-requests-in-react">Chapter 9: Network Requests in React</a><ul>
<li><a class="post-section-overview" href="#heading-the-useeffect-hook">The useEffect Hook</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></li>
</ul>
<p>By covering these concepts, you'll be equipped to dive further into advanced React topics.</p>
<h2 id="heading-requirements">Requirements</h2>
<p>To get the full benefit of this handbook, you should have basic knowledge of HTML, CSS, and JavaScript. No previous knowledge about React is needed, as we will start from the very basics.</p>
<p>If you need a JavaScript refresher, you can <a target="_blank" href="https://codewithnathan.com/beginning-modern-javascript">get my JavaScript book here</a>.</p>
<h2 id="heading-chapter-1-introduction">Chapter 1: Introduction</h2>
<p>React is a very popular JavaScript front-end library. It's received lots of love from developers around the world for its <strong>simplicity</strong> and <strong>fast performance</strong>.</p>
<p>React was initially developed by Facebook as a solution to front end problems they were facing:</p>
<ul>
<li>DOM manipulation is an expensive operation and should be minimized</li>
<li>No library specialized in handling front-end development at the time (there is Angular, but it's an ENTIRE framework.)</li>
<li>Using a lot of vanilla JavaScript can turn a web application into a mess that's hard to maintain.</li>
</ul>
<p>Why do developers love React? As a software developer myself, I can think of a few reasons why I love it:</p>
<ul>
<li><strong>It's minimalist</strong>. React takes care of only ONE thing: the user interface and how it changes according to the data you feed into it. React makes your interface dynamic with minimal code.</li>
<li><strong>It has a low learning curve</strong>. The core concepts of React are relatively easy to learn, and you don't need months or 40 hours of video lectures to learn the basics.</li>
<li><strong>It's unopinionated</strong>. React can be integrated with lots of different technologies. On the front-end, you can use different libraries to handle Ajax calls (Axios, Superagent, or just plain Fetch.) On the back-end, you can use PHP/ Ruby/ Go/ Python or whatever language you prefer.</li>
<li><strong>It has strong community support</strong>. To enhance React's capabilities, open source contributors have built an amazing ecosystem of libraries that enables you to make even more powerful applications. But most open source libraries for React are optional. You don't need to learn them until you've mastered React fundamentals.</li>
</ul>
<p>The bottom line is that with a low learning curve, React gives you incredible power in making your UI flexible, reusable, and spaghetti-free.</p>
<p>Learning React opens tremendous opportunities if you want to work as a web developer.</p>
<h3 id="heading-computer-setup">Computer Setup</h3>
<p>To start programming with React, you'll need to have three things:</p>
<ol>
<li>A web browser</li>
<li>A code editor</li>
<li>Node.js</li>
</ol>
<p>We're going to use the Chrome browser to run our JavaScript code, so if you don't have it, <a target="_blank" href="https://www.google.com/chrome/">you can download it here</a>.</p>
<p>The browser is available for all major operating systems. Once the download is complete, install the browser on your computer.</p>
<p>Next, you'll need to install a code editor if you don't already have one. There are several free code editors available on the Internet, such as Sublime Text, Visual Studio Code, and Notepad++.</p>
<p>Out of these editors, my favorite is Visual Studio Code, because it's fast and easy to use.</p>
<h4 id="heading-how-to-install-visual-studio-code">How to install Visual Studio Code</h4>
<p>Visual Studio Code, or VSCode for short, is an application created for the purpose of writing code. Aside from being free, VSCode is fast and available on all major operating systems.</p>
<p>You can <a target="_blank" href="https://code.visualstudio.com/">download Visual Studio Code here</a>.</p>
<p>When you open the link above, there should be a button showing the version compatible with your operating system as shown below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/1-installvscode-2.png" alt="Image" width="600" height="400" loading="lazy">
<em>Downloading Visual Studio Code</em></p>
<p>Click the button to download VSCode, and install it on your computer.</p>
<p>Now that you have a code editor installed, the next step is to install Node.js</p>
<h4 id="heading-how-to-install-nodejs">How to install Node.js</h4>
<p>Node.js is a JavaScript runtime application that enables you to run JavaScript outside of the browser. You need to install this application on your computer to install packages required in React development.</p>
<p>You can download and install Node.js from <a target="_blank" href="https://nodejs.org/">https://nodejs.org</a>. Pick the recommended LTS version because it has long-term support. The installation process is pretty straightforward.</p>
<p>To check if Node has been properly installed, type the command below on your command line (Command Prompt on Windows or Terminal on Mac):</p>
<pre><code class="lang-sh">node -v
</code></pre>
<p>The command line should respond with the version of the Node.js you have on your computer.</p>
<h3 id="heading-your-first-react-application">Your First React Application</h3>
<p>It's time to run your first React application. First, create a folder on your computer that will be used to store all files related to this book. You can name the folder 'beginning_react'.</p>
<p>The next step is to open your terminal and run the npm command to create a new React application using Vite.</p>
<p>Vite (pronounced 'veet') is a build tool that you can use to bootstrap a new React project. Inside the 'beginning_react' folder, you need to run the following command to create a new React project with Vite:</p>
<pre><code class="lang-sh">npm create vite@5.1.0 my-react-app -- --template react
</code></pre>
<p>You should see npm asking to install a new package (create-vite) as shown below. Proceed by typing 'y' and pressing Enter:</p>
<pre><code class="lang-txt">Need to install the following packages:
  create-vite@5.1.0
Ok to proceed? (y) y
</code></pre>
<p>Then Vite will create a new React project named 'my-react-app' as follows:</p>
<pre><code class="lang-txt">Scaffolding project in /dev/beginning_react/my-react-app...

Done. Now run:

  cd my-react-app
  npm install
  npm run dev
</code></pre>
<p>When you're done, follow the next steps you see in the output above. Use the <code>cd</code> command to change the working directory to the application you've just created, and then run <code>npm install</code> to install the packages required by the application.</p>
<p>Then, you need to run the <code>npm run dev</code> command to start your application:</p>
<pre><code class="lang-txt">$ npm run dev

&gt; my-react-app@0.0.0 dev
&gt; vite


  VITE v5.0.10  ready in 509 ms

  ➜  Local:   http://localhost:5173/
  ➜  Network: use --host to expose
  ➜  press h + enter to show help
</code></pre>
<p>Now you can view the running application from the browser, at the designated localhost address:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/1-vite-react-demo.png" alt="Image" width="600" height="400" loading="lazy">
<em>Vite-React Home Page</em></p>
<p>This means you have successfully created your first React app. Congratulations!</p>
<h3 id="heading-explaining-the-source-code">Explaining the Source Code</h3>
<p>Now that you've successfully run a React application, let's take a look at the source code generated by Vite to understand how things work.</p>
<p>Run the Visual Studio Code you've installed in the previous section, and open the 'my-react-app' folder inside VSCode.</p>
<p>Here, you should see several folders and files that make up the React application as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/1-vite-react-app.png" alt="Image" width="600" height="400" loading="lazy">
<em>Vite-React Application Structure</em></p>
<p>The <code>vite.config.js</code> is a configuration file that instructs Vite on how to run the application. Because we have a React application, you'll see the React plugin imported inside:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { defineConfig } <span class="hljs-keyword">from</span> <span class="hljs-string">'vite'</span>
<span class="hljs-keyword">import</span> react <span class="hljs-keyword">from</span> <span class="hljs-string">'@vitejs/plugin-react'</span>

<span class="hljs-comment">// https://vitejs.dev/config/</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> defineConfig({
  <span class="hljs-attr">plugins</span>: [react()],
})
</code></pre>
<p>When you run the <code>npm run dev</code> command, Vite will look into this file to know how to run the program.</p>
<p>The <code>package.json</code> file stores the information about the project, including the packages required to run the project without any issues. The <code>package-lock.json</code> file keeps track of the installed package versions.</p>
<p>The <code>.eslintrc.cjs</code> file contains ESLint rules. ESLint is a code analysis tool that can identify problematic code in your project without needing to run the project. It will report any errors and warnings in VSCode.</p>
<p>The <code>index.html</code> file is a static HTML document that's going to be used when running the React application, and the <code>README.md</code> file contains an introduction to the project.</p>
<p>You don't need to modify any of these files. Instead, let's go to the <code>src/</code> folder where the React application code is written.</p>
<pre><code class="lang-txt">src
├── App.css
├── App.jsx
├── assets
│   └── react.svg
├── index.css
└── main.jsx
</code></pre>
<p>First, the <code>App.css</code> file contains the CSS rules applied to the <code>App.jsx</code> file, which is the main React application code.</p>
<p>The <code>assets/</code> folder contains the assets required for this project. In this case, it's the React icon, which you had seen in the browser.</p>
<p>The <code>index.css</code> file is the root CSS file applied globally to the application, and the <code>main.jsx</code> file is the root file that access the <code>index.html</code> file to render the React application. Here's the content of <code>main.jsx</code> file:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom/client'</span>
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">'./App.jsx'</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./index.css'</span>

ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>)).render(
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">React.StrictMode</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">React.StrictMode</span>&gt;</span></span>,
)
</code></pre>
<p>Here, you can see that the ReactDOM library creates a root at the <code>&lt;div&gt;</code> element that contains the <code>root</code> ID, then renders the whole React application to that element.</p>
<p>You can open the <code>App.jsx</code> file to view the React code:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> reactLogo <span class="hljs-keyword">from</span> <span class="hljs-string">'./assets/react.svg'</span>
<span class="hljs-keyword">import</span> viteLogo <span class="hljs-keyword">from</span> <span class="hljs-string">'/vite.svg'</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./App.css'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>)

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://vitejs.dev"</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">{viteLogo}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"logo"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"Vite logo"</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://react.dev"</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">{reactLogo}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"logo react"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"React logo"</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Vite + React<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"card"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setCount((count) =&gt; count + 1)}&gt;
          count is {count}
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
          Edit <span class="hljs-tag">&lt;<span class="hljs-name">code</span>&gt;</span>src/App.jsx<span class="hljs-tag">&lt;/<span class="hljs-name">code</span>&gt;</span> and save to test HMR
        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"read-the-docs"</span>&gt;</span>
        Click on the Vite and React logos to learn more
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>In this file, a single component named <code>App</code> is defined. The Vite and React logos are rendered with a link to the respective library, and there's a counter button that will increment the counter by 1 when you click on it.</p>
<p>This file is where we will be exploring the fundamentals of React. Let's delete everything in this file, and write a simple <code>App</code> component that renders a <code>&lt;h1&gt;</code> element:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>Next, delete the <code>index.css</code>, <code>app.css</code>, and <code>assets/</code> folder. You also need to delete the <code>import './index.css'</code> statement in your <code>main.jsx</code> file.</p>
<p>If you open the browser again, you should see a single heading rendered as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/1-react-hello-world.png" alt="Image" width="600" height="400" loading="lazy">
<em>React Output From Code Changes</em></p>
<p>Alright! Now you're ready to learn the fundamentals of React. We'll start your first lesson in the next chapter.</p>
<h2 id="heading-chapter-2-how-to-create-react-components">Chapter 2: How to Create React Components</h2>
<p>In React, a component is a single independent unit of a user interface (UI). What you write inside a component will determine what should appear on the browser screen at a given time.</p>
<p>In the previous chapter, we created an <code>App</code> component that returns a heading element:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>A component is made up of a function that returns a single UI element.</p>
<p>When you want a component to render nothing, you can return a <code>null</code> or <code>false</code> instead of an element.</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>
}
</code></pre>
<p>All React components are saved under the <code>.jsx</code> file extension. As you can see in this project, you have <code>main.jsx</code> and <code>App.jsx</code>.</p>
<p>What is JSX? It's an extension of JavaScript that produces JavaScript-powered HTML elements. We're going to learn about it later.</p>
<h3 id="heading-how-to-return-multiple-elements-with-fragments">How to Return Multiple Elements With Fragments</h3>
<p>A component must always return a single element. When you need to return multiple elements, you need to wrap all of them in a single element like a <code>&lt;div&gt;</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Learning to code with React<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>But this will make your application render one extra <code>&lt;div&gt;</code> element in the browser. To avoid cluttering your application, you can render an empty tag <code>&lt;&gt;</code> like this:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Learning to code with React<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>The empty tag above is a React feature called a Fragment. By using a Fragment, your component won't render an extra element to the screen.</p>
<p>You can also import the <code>Fragment</code> module from React to make it explicit as follows:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { Fragment } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Fragment</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Learning to code with React<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Fragment</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>But you don't need to explicitly state the <code>Fragment</code> tag. Using an empty tag <code>&lt;&gt;</code> is enough.</p>
<h3 id="heading-how-to-render-to-the-screen">How to Render to the Screen</h3>
<p>To render a React component into the browser, you need to create a root React component using the ReactDOM library, which you've seen previously when viewing the <code>main.jsx</code> file.</p>
<p>You need to have an HTML file as the source from which your React component is rendered. </p>
<p>Usually, a very basic HTML document with a <code>&lt;div&gt;</code> is enough, as you can see in the <code>index.html</code> file:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"root"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/src/main.jsx"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>Next, you render the component into the <code>&lt;div&gt;</code> element. </p>
<p>Notice how ReactDOM is imported from <code>react-dom</code> package, and the <code>document.getElementById('root')</code> is used to select the <code>&lt;div&gt;</code> element below:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom/client'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}

ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>)).render(
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">React.StrictMode</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">React.StrictMode</span>&gt;</span></span>,
)
</code></pre>
<p>Here, you can see that the <code>App</code> component is placed in the same file as the ReactDOM library. You can do this if you want to remove the <code>App.jsx</code> file, so you have only a single <code>main.jsx</code> file as the source for your React application.</p>
<p>But it's confusing to have multiple components in one file, so let's not do this.</p>
<h3 id="heading-how-to-write-comments-in-react">How to Write Comments in React</h3>
<p>Writing comments in React components is similar to how you comment in regular JavaScript code. You can use the double forward slash syntax <code>//</code> to comment any code.</p>
<p>The following example shows how to comment the <code>export</code> statement:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Learning to code with React<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}

<span class="hljs-comment">// export default App</span>
</code></pre>
<p>When you want to comment the code inside the <code>return</code> statement, you need to use the curly brackets, forward slash, and asterisk format <code>{/* comment here */}</code> as shown below:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      {/* <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Learning to code with React<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span> */}
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>It may seem very annoying that you need to remember two different ways of commenting when writing React applications. But don't worry, because a modern tool like VSCode knows how to generate the right comment syntax.</p>
<p>You only need to press the comment shortcut, which is <code>CTRL + /</code> for Windows/ Linux or <code>Command + /</code> for macOS.</p>
<h3 id="heading-how-to-compose-multiple-components-as-one">How to Compose Multiple Components as One</h3>
<p>Up until this point, you've only rendered a single <code>App</code> component to the browser. But applications built using React can be composed of tens or hundreds of components.</p>
<p><strong>Composing components</strong> is the process of forming the user interface by using loosely coupled components. It's kind of like making a house out of Lego blocks, as I will show you in the following example:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">UserComponent</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">ProfileComponent</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">FeedComponent</span> /&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">UserComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span> User Component <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ProfileComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span> Profile Component <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">FeedComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span> Feed Component<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
}
</code></pre>
<p>From the example above, you can see how the <code>&lt;ParentComponent&gt;</code> renders three children components:</p>
<ul>
<li><code>&lt;UserComponent&gt;</code></li>
<li><code>&lt;ProfileComponent&gt;</code></li>
<li><code>&lt;FeedComponent&gt;</code></li>
</ul>
<p>The composition of many components will form a single tree of React components in a top-down approach.</p>
<p>The tree will then be rendered into the DOM through the <code>ReactDOM.render()</code> method:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/2-react-tree.png" alt="Image" width="600" height="400" loading="lazy">
<em>React Component Tree Illustrated</em></p>
<p>By composing multiple components, you can split the user interface into independent, reusable pieces, and develop each piece in isolation.</p>
<h2 id="heading-chapter-3-making-sense-of-jsx">Chapter 3: Making Sense of JSX</h2>
<p>In the previous chapter, you learned that a component must always have a <code>return</code> statement that contains elements to render on the screen:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}
</code></pre>
<p>The tag <code>&lt;h1&gt;</code> looks like a regular HTML tag, but it's actually a special template language included in React called JSX.</p>
<p>JSX is a syntax extension that produces JavaScript powered HTML elements. It can be assigned to JavaScript variables and can be returned from function calls. For example:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> myElement = <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
  <span class="hljs-keyword">return</span> myElement
}
</code></pre>
<p>Because of JSX, you can also embed JavaScript expressions inside an element by using curly brackets <code>{}</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> lowercaseClass = <span class="hljs-string">'text-lowercase'</span>;
<span class="hljs-keyword">const</span> text = <span class="hljs-string">'Hello World!'</span>;
<span class="hljs-keyword">const</span> App = <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{lowercaseClass}</span>&gt;</span>{text}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
</code></pre>
<p>This is what makes React elements different from HTML elements. You can't embed JavaScript directly by using curly braces in HTML.</p>
<p>Instead of creating a whole new templating language, you just need to use JavaScript functions to control what is being displayed on the screen.</p>
<h3 id="heading-how-to-render-a-list-using-jsx">How to Render a List Using JSX</h3>
<p>For example, let's say you have an array of users that you'd like to show:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> users = [
  { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Nathan'</span>, <span class="hljs-attr">role</span>: <span class="hljs-string">'Web Developer'</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>, <span class="hljs-attr">role</span>: <span class="hljs-string">'Web Designer'</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Jane'</span>, <span class="hljs-attr">role</span>: <span class="hljs-string">'Team Leader'</span> },
]
</code></pre>
<p>You can use the <code>map()</code> function to loop over the array:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> users = [
    { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Nathan'</span>, <span class="hljs-attr">role</span>: <span class="hljs-string">'Web Developer'</span> },
    { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>, <span class="hljs-attr">role</span>: <span class="hljs-string">'Web Designer'</span> },
    { <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Jane'</span>, <span class="hljs-attr">role</span>: <span class="hljs-string">'Team Leader'</span> },
  ]

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>The currently active users list:<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
      {
        users.map(function(user){
          // returns Nathan, then John, then Jane
          return (
            <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span> {user.name} as the {user.role} <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;/&gt;</span></span>
  )
}
</code></pre>
<p>Inside React, you don't need to store the return value of the <code>map()</code> function in a variable. The example above will return a <code>&lt;li&gt;</code> element for each array value into the component.</p>
<p>While the above code is already complete, React will trigger an error in the console, saying that you need to put a "key" prop in each child of a list (the element that you return from <code>map()</code> function):</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/3-react-array-warning.png" alt="Image" width="600" height="400" loading="lazy">
<em>React 'key' Warning on Browser Console</em></p>
<p>A prop (short for property) is an input that you can pass to a component when rendering that component. The <code>key</code> prop is a special prop that React will use to determine which child element has been changed, added, or removed from the list.</p>
<p>You won't use it actively in any part of your array rendering code, but React will ask for one when you render a list.</p>
<p>It is recommended that you put the unique identifier of your data as the key value. In the example above, you can use the <code>user.id</code> data. Here's how you pass a <code>key</code> prop for each <code>&lt;li&gt;</code> element:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">return</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{user.id}</span>&gt;</span> 
    {user.name} as the {user.role} 
  <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span></span>
)
</code></pre>
<p>When you don't have any unique identifiers for your list, you can use the array <code>index</code> value as the last resort:</p>
<pre><code class="lang-jsx">users.map(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">user, index</span>)</span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{index}</span>&gt;</span>
      {user.name} as the {user.role}
    <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span></span>
  )
})
</code></pre>
<p>Props are one of the ingredients that make a React component powerful. You're going to learn more about it in the next chapter.</p>
<h3 id="heading-how-to-add-the-class-attribute">How to Add the Class Attribute</h3>
<p>You can add the <code>class</code> attribute to your elements by using the <code>className</code> keyword:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'text-lowercase'</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}
</code></pre>
<p>The keyword <code>class</code> is reserved for JavaScript classes, so you need to use <code>className</code> instead.</p>
<h2 id="heading-chapter-4-props-and-states">Chapter 4: Props and States</h2>
<p>Props and states are used to pass data inside React components. Props (or properties) are inputs passed down from a parent component to its child component.</p>
<p>On the other hand, states are variables defined and managed inside the components.</p>
<p>Let's start by understanding props. Suppose you have a <code>ParentComponent</code> that renders a <code>ChildComponent</code> like this:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ChildComponent</span> /&gt;</span></span>
}
</code></pre>
<p>You can pass a prop from <code>ParentComponent</code> into <code>ChildComponent</code> by adding a new attribute after the component name.</p>
<p>In the code below, the <code>name</code> prop with the value 'John' is passed to the <code>ChildComponent</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ChildComponent</span> <span class="hljs-attr">name</span>=<span class="hljs-string">'John'</span> /&gt;</span></span>
}
</code></pre>
<p>When the component is rendered on the browser, the <code>ChildComponent</code> will receive the name prop into the component.</p>
<p>You can access the <code>props</code> object by defining it in the function component's argument:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ChildComponent</span>(<span class="hljs-params">props</span>)</span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Hello World! my name is {props.name}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
}
</code></pre>
<p>The <code>props</code> parameter will always be an object, and any prop you define when rendering the component will be passed as a property to the object.</p>
<h3 id="heading-how-to-pass-down-multiple-props">How to Pass Down Multiple Props</h3>
<p>You can pass as many props as you want into a single child component. Just add the props when using the component as shown below:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ChildComponent</span>
      <span class="hljs-attr">name</span>=<span class="hljs-string">"John"</span>
      <span class="hljs-attr">age</span>=<span class="hljs-string">{29}</span>
      <span class="hljs-attr">hobbies</span>=<span class="hljs-string">{[</span>"<span class="hljs-attr">read</span> <span class="hljs-attr">books</span>", "<span class="hljs-attr">drink</span> <span class="hljs-attr">coffee</span>"]}
      <span class="hljs-attr">occupation</span>=<span class="hljs-string">"Software Engineer"</span>
    /&gt;</span></span>
  )
}
</code></pre>
<p>All the props above will be passed to the ChildComponent's <code>props</code> parameter.</p>
<p>You can even pass a function into props like this:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetings</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Hello World'</span>
  }

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ChildComponent</span> <span class="hljs-attr">greetings</span>=<span class="hljs-string">{greetings}</span> /&gt;</span></span>
}
</code></pre>
<p>In the child component, you can call the function as follows:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ChildComponent</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{props.greetings()}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
}
</code></pre>
<p>Note that if you pass anything other than a string as a prop value, you need to put the value in curly brackets (numbers, functions, arrays, objects, and so on)</p>
<p>This is because JavaScript expressions can't be processed by JSX unless you put the expression inside curly brackets.</p>
<h3 id="heading-props-are-immutable">Props are Immutable</h3>
<p>Immutable means that a prop's value can't be changed no matter what happens.</p>
<p>In the code below, the <code>ChildComponent</code> tries to change the value of <code>props.name</code> property:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ChildComponent</span>(<span class="hljs-params">props</span>)</span>{
  props.name = <span class="hljs-string">'Mark'</span>;
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Hello World! my name is {props.name}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ChildComponent</span> <span class="hljs-attr">name</span>=<span class="hljs-string">'John'</span>/&gt;</span></span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ParentComponent
</code></pre>
<p>But you'll get an error in the console as follows:</p>
<pre><code class="lang-txt">Uncaught TypeError: Cannot assign to read only property 'name' of object '#&lt;Object&gt;'
</code></pre>
<p>As you can see, React props can't be changed once you declare them. But what if your data needs to change as a user interacts with your application? This is where state comes to the rescue.</p>
<h3 id="heading-state-in-react">State in React</h3>
<p>In React, states are arbitrary data that you can declare and manage in your components. To create a state in React, you need to call the <code>useState</code> hook as shown below:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [name, setName] = useState(<span class="hljs-string">'John'</span>)

}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ParentComponent
</code></pre>
<p>In React, hooks are functions that allow you to tap into the features provided by React. The <code>useState</code> hook is a function that enables you to put value into the state mechanism.</p>
<p>When calling the <code>useState()</code> function, you can pass an argument that will serve as the initial value of the state. The function then returns an array with two elements.</p>
<p>The first element holds the state value, and the second element is a function that allows you to change the state value. You need to use the destructuring array syntax to receive both elements as shown above</p>
<p>You can give any names to the variables returned by <code>useState</code>, but it's recommended to use <code>[something, setSomething]</code>.</p>
<p>To render the state value, you can embed it into JSX as follows:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [name, setName] = useState(<span class="hljs-string">'John'</span>)

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello {name}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}
</code></pre>
<p>If you want to change the value of the <code>name</code> variable, you need to use the provided <code>setName()</code> function.</p>
<p>But you can't call <code>setName()</code> in the component's body, because React will refresh itself anytime you change the state value.</p>
<p>Instead, you can create a button that will change the value of name when you click it:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [name, setName] = useState(<span class="hljs-string">'John'</span>)

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello {name}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setName('Mark')}&gt;Change Name<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>In the code above, we create a <code>&lt;button&gt;</code> element and add the <code>onClick</code> prop, which gets executed anytime we click on the button.</p>
<p>Inside the prop, we pass a function that simply calls the <code>setName()</code> function, changing the state value.</p>
<h3 id="heading-how-to-pass-state-to-a-child-component">How to Pass State to a Child Component</h3>
<p>You can pass the state into any child component. When you need to update the state from a child component, you need to pass the <code>setSomething</code> function received from the <code>useState</code> hook.</p>
<p>Here's an example of passing a state from <code>ParentComponent</code> to <code>ChildComponent</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [name, setName] = useState(<span class="hljs-string">'John'</span>)

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ChildComponent</span> <span class="hljs-attr">name</span>=<span class="hljs-string">{name}</span> <span class="hljs-attr">setName</span>=<span class="hljs-string">{setName}</span> /&gt;</span></span>
}
</code></pre>
<p>In the <code>ChildComponent</code>, you can call the <code>setName()</code> function from <code>props</code> like this:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ChildComponent</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello {props.name}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> props.setName('Mark')}&gt;Change Name<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>When the button on the <code>ChildComponent</code> is clicked, the value of the <code>name</code> state will change. Internally, React will refresh the application and reflect the changes in the user interface.</p>
<h3 id="heading-how-to-use-react-devtools-to-inspect-states-and-props">How to Use React DevTools to Inspect States and Props</h3>
<p>To help ease your development, you can install the React Developer Tools (DevTools for short) to inspect the current state and props value of your components. </p>
<p>You can <a target="_blank" href="https://chromewebstore.google.com/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi">install React DevTool for Chrome here</a>.</p>
<p>Once installed, open the developer tool and you should have two extra tabs called <em>Components</em> and <em>Profiler</em> as shown below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/4-react-devtool-chrome.png" alt="Image" width="600" height="400" loading="lazy">
<em>Opening React DevTool</em></p>
<p>Similar to how you can inspect CSS rules applied to HTML elements, you can inspect the state and props of React components using the developer tools. Click the <em>Components</em> tab, and inspect one of the two components we created earlier.</p>
<p>Below, you can see the props and state of the <code>ParentComponent</code>, as well as other details:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/4-react-devtool-inspect.png" alt="Image" width="600" height="400" loading="lazy">
<em>Inspecting Components With React DevTool</em></p>
<p>When you click on the button, the state value will change accordingly. You can inspect the <code>ChildComponent</code> to view its details. These DevTools will come in handy when you develop React applications.</p>
<h2 id="heading-chapter-5-react-conditional-rendering">Chapter 5: React Conditional Rendering</h2>
<p>You can control what output is being rendered by a component by implementing conditional rendering in your JSX code.</p>
<p>For example, let's say you want to switch between rendering the login and logout buttons, depending on the availability of the <code>user</code> state:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">const</span> { user } = props

  <span class="hljs-keyword">if</span> (user) {
    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Logout<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
  }
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>You don't need to add an <code>else</code> statement in the component because React will stop further processes once it reaches a <code>return</code> statement.</p>
<p>In the example above, React will render the logout button when the <code>user</code> value is truthy, and the login button when <code>user</code> is falsy.</p>
<h3 id="heading-partial-rendering-with-a-regular-variable">Partial Rendering with a Regular Variable</h3>
<p>When developing with React, there will be cases where you want to render a part of your UI dynamically in a component.</p>
<p>In the example below, the JSX element is stored in a variable called <code>button</code>, and that variable is used again in the <code>return</code> statement:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">const</span> { user } = props

  <span class="hljs-keyword">let</span> button = <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>

  <span class="hljs-keyword">if</span> (user) {
    button = <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Logout<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello there!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      {button}
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>Instead of writing two return statements, you store the dynamic UI element inside a variable and use that variable in the <code>return</code> statement.</p>
<p>This way, you can have a component that has static and dynamic elements.</p>
<h3 id="heading-inline-rendering-with-the-ampamp-operator">Inline Rendering with the <code>&amp;&amp;</code> Operator</h3>
<p>It's possible to render a component only if a certain condition is met and render null otherwise.</p>
<p>For example, let's say you want to render a dynamic message for users when they have new emails in their inbox:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> newEmails = <span class="hljs-number">2</span>

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello there!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      {newEmails &gt; 0 &amp;&amp;
        <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>
          You have {newEmails} new emails in your inbox.
        <span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      }
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>In this example, the <code>&lt;h2&gt;</code> element only gets rendered when the <code>newEmails</code> count is greater than 0.</p>
<h3 id="heading-inline-rendering-with-the-conditional-ternary-operator">Inline Rendering with the Conditional (Ternary) Operator</h3>
<p>It's also possible to use a ternary operator in order to render the UI dynamically.</p>
<p>Take a look at the following example:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">const</span> { user } = props

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello there!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      { user? <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Logout<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span> : <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span> }
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>Instead of using a variable to hold the <code>&lt;button&gt;</code> element, you can simply use the ternary operator on the <code>user</code> value and render 'Logout' or 'Login' button according to the variable's value.</p>
<h2 id="heading-chapter-6-how-to-handle-user-events">Chapter 6: How to Handle User Events</h2>
<p>Under the hood, React has an internal event handler that connects to the native DOM event.</p>
<p>This is why we can add the <code>onClick</code> prop to buttons in the previous chapters, which gets executed in response to a click event.</p>
<p>When you call a function in response to events, the <code>event</code> object will be passed to the callback function as follows:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> handleClick = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World!"</span>);
    <span class="hljs-built_in">console</span>.log(event);
  }
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleClick}</span>&gt;</span>
      Click me
    <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
  )
}
</code></pre>
<p>When you click on the button above, the <code>event</code> variable will be logged as a <code>SyntheticBaseEvent</code> object in your console:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/8-react-synthetic-event.png" alt="Image" width="600" height="400" loading="lazy">
<em>React's SyntheticBaseEvent Log</em></p>
<p>The <code>SyntheticBaseEvent</code> object is a built-in React object used to interact with the native DOM events. Different browsers have different implementations of the DOM event object, so the <code>SyntheticBaseEvent</code> makes React compatible with these browsers.</p>
<p>Whenever a DOM event is triggered, that synthetic event will be handled by React so that you can decide what to do with that event.</p>
<p>The use case for this Synthetic event is the same as the native DOM event. Three of the most common event handlers you're going to use are:</p>
<ul>
<li><code>onChange</code></li>
<li><code>onClick</code></li>
<li><code>onSubmit</code></li>
</ul>
<p>You can respond to user interactions like clicking, hovering, focusing or typing on a form input, submitting a form, and so on.</p>
<h3 id="heading-how-to-change-the-ui-by-handling-events">How to Change the UI By Handling Events</h3>
<p>In the previous chapter, you saw how conditional logic can be used to render different outputs.</p>
<p>By combining conditional logic with state, props, and event handlers, you can create a dynamic component that renders different outputs based on the data it currently holds.</p>
<p>For example, suppose you want to show or hide a <code>&lt;div&gt;</code> element with a button click. Here's how you do it:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// State to hold the visibility status of the paragraph</span>
  <span class="hljs-keyword">const</span> [isParagraphVisible, setIsParagraphVisible] = useState(<span class="hljs-literal">true</span>);

  <span class="hljs-comment">// Function to toggle the visibility status of the paragraph</span>
  <span class="hljs-keyword">const</span> toggleStatus = <span class="hljs-function">() =&gt;</span> {
    setIsParagraphVisible(!isParagraphVisible);
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Change UI based on click<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      {isParagraphVisible &amp;&amp; (
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This paragraph will be shown/hidden on click<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      )}
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{toggleStatus}</span>&gt;</span>
        {isParagraphVisible ? 'Hide' : 'Show'} Paragraph
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>First, you create a state to hold the visibility status of the paragraph using the <code>useState</code> hook. The default value of the state is <code>true</code>.</p>
<p>Next, a function named <code>toogleStatus()</code> is defined. This function will change the <code>status</code> value from <code>true</code> to <code>false</code> and vice versa.</p>
<p>Finally, a <code>return</code> statement is added to render the elements to the screen. When the button is clicked, the <code>toogleStatus()</code> function will be executed. This will show or hide the paragraph depending on the current status.</p>
<p>By using states, props, and event handlers, the code you write becomes a description of what the user interface should look like. React then takes that description and renders it on the browser.</p>
<h2 id="heading-chapter-7-css-in-react">Chapter 7: CSS in React</h2>
<p>There are 4 common ways you can add CSS in a React application:</p>
<ol>
<li>Inline styling</li>
<li>CSS files</li>
<li>CSS modules</li>
<li>Tailwind CSS</li>
</ol>
<p>This chapter will explore these 4 different ways to write CSS in React components, and which one you should use when starting a React application.</p>
<h3 id="heading-react-inline-styling">React Inline Styling</h3>
<p>React components are composed of JSX elements. But just because you're not writing regular HTML elements doesn't mean you can't use the old inline style method.</p>
<p>The only difference with JSX is that inline styles must be written as an object instead of a string. See the example below:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">color:</span> '<span class="hljs-attr">red</span>' }}&gt;</span>Hello World<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
  );
}
</code></pre>
<p>In the style attribute above, the first set of curly brackets is used to write JavaScript expressions. The second set of curly brackets initializes a JavaScript object.</p>
<p>Style property names that have more than one word are written in camelCase instead of using the traditional hyphenated style. For example, the usual <code>text-align</code> property is written as <code>textAlign</code> in JSX:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">textAlign:</span> '<span class="hljs-attr">center</span>' }}&gt;</span>Hello World<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
  );
}
</code></pre>
<p>Because the style attribute is an object, you can also separate the style by writing it as a constant. This way, you can reuse the style in other elements as needed:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> pStyle = {
  <span class="hljs-attr">fontSize</span>: <span class="hljs-string">'16px'</span>,
  <span class="hljs-attr">color</span>: <span class="hljs-string">'blue'</span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{pStyle}</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{pStyle}</span>&gt;</span>The weather is sunny today.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>If you need to extend your paragraph style further down the line, you can use the spread operator.</p>
<p>This will let you add inline styles to your already declared style object. See the <code>&lt;p&gt;</code> element below:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> pStyle = {
  <span class="hljs-attr">fontSize</span>: <span class="hljs-string">'16px'</span>,
  <span class="hljs-attr">color</span>: <span class="hljs-string">'blue'</span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">...pStyle</span>, <span class="hljs-attr">color:</span> '<span class="hljs-attr">green</span>', <span class="hljs-attr">textAlign:</span> '<span class="hljs-attr">right</span>' }}&gt;</span>
      When you go to work, bring your umbrella with you!
    <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
  )
}
</code></pre>
<p>JSX inline styles allow you to write CSS directly into your component.</p>
<p>One of the benefits of using the inline style approach is that you will have a simple component-focused styling technique. When using an object for styling, you can extend your style by spreading the object.</p>
<p>But in a big and complex project where you have hundreds of React components to manage, this might not be the best choice for you.</p>
<p>You can't specify pseudo classes using inline styles. That means you can't define rules like <code>:hover</code>, <code>:focus</code>, <code>:active</code>, and so on.</p>
<p>Also, you can't specify media queries for responsive styling. Let's consider another way to style your React app.</p>
<h3 id="heading-css-files">CSS Files</h3>
<p>Another way to add CSS in React is to use <code>.css</code> files. Vite already knows how to handle a <code>.css</code> file, so all you need to do is import the CSS file into your JSX file and add the right <code>className</code> prop to your component.</p>
<p>Let's create a <code>style.css</code> file in your project folder with the following content:</p>
<pre><code class="lang-css"><span class="hljs-comment">/* style.css */</span>
<span class="hljs-selector-class">.paragraph-text</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">16px</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#ff0000</span>;
}
</code></pre>
<p>Now, let's import the CSS file into the <code>App.jsx</code> file and add the class prop to the component:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> <span class="hljs-string">'./style.css'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"paragraph-text"</span>&gt;</span>
        The weather is sunny today.
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
  );
}
</code></pre>
<p>This way, the CSS will be separated from your JavaScript files, and you can just write CSS syntax as usual.</p>
<p>You can even include a CSS framework such as Bootstrap in React with this approach. All you need to do is import the CSS file in your root component.</p>
<p>This method will enable you to use all CSS features, including pseudo classes and media queries.</p>
<h3 id="heading-css-modules">CSS Modules</h3>
<p>A CSS module is a regular CSS file with all of its class and animation names scoped locally by default.</p>
<p>When applying this method, each React component will have its own CSS file, and you need to import that CSS file into your component.</p>
<p>To let React know you're using CSS modules, name your CSS file using the <code>[name].module.css</code> convention.</p>
<p>Here's an example:</p>
<pre><code class="lang-css"><span class="hljs-comment">/* App.module.css */</span>
<span class="hljs-selector-class">.BlueParagraph</span> {
  <span class="hljs-attribute">color</span>: blue;
  <span class="hljs-attribute">text-align</span>: left;
}
<span class="hljs-selector-class">.GreenParagraph</span> {
  <span class="hljs-attribute">color</span>: green;
  <span class="hljs-attribute">text-align</span>: right;
}
</code></pre>
<p>Then import it to your component file:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> styles <span class="hljs-keyword">from</span> <span class="hljs-string">"./App.module.css"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{styles.BlueParagraph}</span>&gt;</span>
        The weather is sunny today.
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{styles.GreenParagraph}</span>&gt;</span>
        Still, don't forget to bring your umbrella!
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>When you build your app, Vite will automatically look for CSS files that have the <code>.module.css</code> name and process the class names to a new localized name.</p>
<p>Using CSS Modules ensures that your CSS classes are scoped locally, preventing CSS rules from colliding with each other.</p>
<p>Another advantage of using CSS Modules is that you can compose a new class by inheriting from other classes that you've written. This way, you'll be able to reuse CSS code that you've written previously, like this:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.MediumParagraph</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">20px</span>;
}
<span class="hljs-selector-class">.BlueParagraph</span> {
  <span class="hljs-attribute">composes</span>: MediumParagraph;
  <span class="hljs-attribute">color</span>: blue;
  <span class="hljs-attribute">text-align</span>: left;
}
<span class="hljs-selector-class">.GreenParagraph</span> {
  <span class="hljs-attribute">composes</span>: MediumParagraph;
  <span class="hljs-attribute">color</span>: green;
  <span class="hljs-attribute">text-align</span>: right;
}
</code></pre>
<p>But we're not going to explore every single feature of CSS modules here, only enough to get you familiar with them.</p>
<h3 id="heading-tailwind-css">Tailwind CSS</h3>
<p>Tailwind CSS is a modern utility-first CSS framework that allows you to style elements by combining a bunch of classes together.</p>
<p>CSS frameworks like Bootstrap and Bulma provide you with high-level components that you can immediately use in your project. When you need to style a button, you just need to apply the classes that contain the desired CSS properties:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"btn btn-primary"</span>&gt;</span>Subscribe<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>When using Bootstrap, the <code>btn</code> class provides a combination of CSS properties such as padding, color, opacity, font weight, and so on.</p>
<p>On the other hand, Tailwind gives you utility classes where each class has only one or two properties:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'px-5 py-2 text-white bg-blue-500 border-2'</span>&gt;</span>
  Subscribe
<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>In the example above, the <code>px-5</code> is short for padding <code>padding-left</code> and <code>padding-right</code>, while 5 is a specific size for the paddings. The <code>text-white</code> applies <code>color: white</code>, the <code>bg-blue-500</code> applies the <code>background-color</code> property, and <code>border</code> applies <code>border-width</code>.</p>
<h3 id="heading-which-one-should-you-use">Which One Should You Use?</h3>
<p>It depends on the method you feel comfortable with the most. If you're working with a team, you need to discuss and agree on the method you want to apply, because mixing the styles makes it hard to develop and maintain the application.</p>
<p>Remember: Always use only one way to style React components in a specific project to avoid confusion.</p>
<h2 id="heading-chapter-8-how-to-build-forms-in-react">Chapter 8: How to Build Forms in React</h2>
<p>One of the most common interfaces you're going to build as a web developer is a form. In React, you can create a form by using state as the single source of that form's data.</p>
<p>In this chapter, I will show you how to handle form input, form submission, and form validation using React.</p>
<h3 id="heading-how-to-handle-form-input">How to Handle Form Input</h3>
<p>For example, suppose you want to create a form with a single text input and a button.</p>
<p>You can first set up the state that will serve as the input value:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Form</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [username, setUsername] = useState();
}
</code></pre>
<p>Next, add the <code>return</code> statement and define the form. On the <code>&lt;input&gt;</code> element, assign the <code>username</code> state as the <code>value</code> prop:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Form</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [username, setUsername] = useState();
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
      Username:
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span> <span class="hljs-attr">name</span>=<span class="hljs-string">'username'</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{username}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}
</code></pre>
<p>Next, add the <code>onChange</code> prop to the <code>&lt;input&gt;</code> element. In that prop, assign the <code>value</code> of the text input as the value of the <code>username</code> state:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Form</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [username, setUsername] = useState();
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
      Username:
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span>
        <span class="hljs-attr">value</span>=<span class="hljs-string">{username}</span>
        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{e</span> =&gt;</span> setUsername(e.target.value)}
      /&gt;
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}
</code></pre>
<p>The <code>e</code> or <code>event</code> object is passed by the <code>onChange</code> prop to the callback function. From that object, we can get the value of the text input at <code>event.target.value</code> property.</p>
<p>Now whenever the input value changes, the state will be updated to reflect the changes.</p>
<h3 id="heading-how-to-handle-form-submission">How to Handle Form Submission</h3>
<p>The next step is to submit the form. Let's create a function that handles the submit event called <code>handleSubmit()</code> as follows:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Form</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [username, setUsername] = useState();

  <span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    e.preventDefault();
    alert(username);
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span>
      Username:
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span>
        <span class="hljs-attr">value</span>=<span class="hljs-string">{username}</span>
        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setUsername(e.target.value)}
      /&gt;
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}
</code></pre>
<p>Here, the <code>handleSubmit()</code> function will stop the default form submission behavior, which will trigger a refresh, and then create an alert box to display the <code>username</code> value.</p>
<p>The function then gets passed to the <code>onSubmit</code> prop of the <code>&lt;form&gt;</code> element. A <code>&lt;button&gt;</code> is also added so that the user can submit the form.</p>
<h3 id="heading-how-to-handle-form-validation">How to Handle Form Validation</h3>
<p>To handle form validation, you need to create another state that will store the error message. You can name this state <code>usernameError</code> as follows:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> [usernameError, setUsernameError] = useState();
</code></pre>
<p>Next, create a <code>handleUsername()</code> function that will run when the <code>username</code> input changes.</p>
<p>Inside this function, you can call the <code>setUsername()</code> function to update the state, and then write logic to validate the input value.</p>
<p>For example, suppose the <code>username</code> length must be longer than 6. Here's how you do it:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> handleUsername = <span class="hljs-function"><span class="hljs-params">e</span> =&gt;</span> {
  <span class="hljs-keyword">const</span> { value } = e.target;
  setUsername(value);

  <span class="hljs-comment">// Validate username value:</span>
  <span class="hljs-keyword">if</span> (value.length &lt;= <span class="hljs-number">6</span>) {
    setUsernameError(<span class="hljs-string">'Username length must be more than 6 characters'</span>);
  } <span class="hljs-keyword">else</span> {
    setUsernameError();
  }
};
</code></pre>
<p>Now that you have some validation logic, you need to set the <code>handleUsername()</code> function as the <code>onChange</code> prop handler.</p>
<p>Also, add a paragraph below the <code>&lt;input&gt;</code> element that will show the error message as follows:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">return</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span>
    Username:
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{username}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleUsername}</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{usernameError}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
);
</code></pre>
<p>Inside the <code>handleSubmit()</code> function, you can check if there's an error on the form by checking the <code>usernameError</code> state, then prevent the form from being submitted when there is an error:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  e.preventDefault();
  <span class="hljs-keyword">if</span>(usernameError){
    alert(<span class="hljs-string">'Unable to submit: Form contain errors'</span>);
  } <span class="hljs-keyword">else</span> {
    alert(username);
  }
}
</code></pre>
<p>This way, the form won't be submitted until the error is fixed.</p>
<p>Here's the full source code of the form if you want to try it:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [username, setUsername] = useState();
  <span class="hljs-keyword">const</span> [usernameError, setUsernameError] = useState();

  <span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    e.preventDefault();
    <span class="hljs-keyword">if</span>(usernameError){
      alert(<span class="hljs-string">'Unable to submit: Form contain errors'</span>);
    } <span class="hljs-keyword">else</span> {
      alert(username);
    }
  }

  <span class="hljs-keyword">const</span> handleUsername = <span class="hljs-function"><span class="hljs-params">e</span> =&gt;</span> {
    <span class="hljs-keyword">const</span> { value } = e.target;
    setUsername(value);

    <span class="hljs-comment">// Validate username value:</span>
    <span class="hljs-keyword">if</span> (value.length &lt;= <span class="hljs-number">6</span>) {
      setUsernameError(<span class="hljs-string">'Username length must be more than 6 characters'</span>);
    } <span class="hljs-keyword">else</span> {
      setUsernameError();
    }
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span>
      Username:
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span>
        <span class="hljs-attr">value</span>=<span class="hljs-string">{username}</span>
        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleUsername}</span>
      /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{usernameError}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>A form can be as complex or as simple as required, but you'll use the pattern you see here no matter what form you build:</p>
<ul>
<li>State values are used as the source of form data and validation</li>
<li><code>onChange</code> prop as a way to update the state</li>
<li>Validations are triggered by user inputs</li>
<li>A <code>handleSubmit()</code> function is executed when the form is submitted</li>
</ul>
<p>Using these building blocks, you can build any form required by your application.</p>
<h2 id="heading-chapter-9-network-requests-in-react">Chapter 9: Network Requests in React</h2>
<p>Modern web applications tend to have a modular architecture, where the back end is separated from the front end. The front end app will need to send an HTTP network request to a remote endpoint.</p>
<p>React doesn't tell you how you should send network requests. The library only focuses on rendering UI with data management using props and states.</p>
<p>To fetch data using React, you can use any valid JavaScript library like Axios, Superagent, and even the native Fetch API.</p>
<p>In this chapter, we're going to see how to do network requests using Fetch in React.</p>
<h3 id="heading-the-useeffect-hook">The useEffect Hook</h3>
<p>When you create a React application that needs to synchronize with a system outside of React, you need to use the <code>useEffect</code> hook.</p>
<p>This hook allows you to run some code after rendering so that you can synchronize your component with some system outside of React.</p>
<p>When the hook has finished performing the data request, you can set the response into your component states and render the appropriate components based on the state values.</p>
<p>To show you an example, let's fetch data from <a target="_blank" href="https://jsonplaceholder.typicode.com/todos/1">https://jsonplaceholder.typicode.com/todos/1</a> which is a dummy end point:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [title, setTitle] = useState(<span class="hljs-string">''</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    getData();
  }, []);

  <span class="hljs-keyword">const</span> getData = <span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos/1'</span>);
    <span class="hljs-keyword">const</span> task = <span class="hljs-keyword">await</span> response.json();
    <span class="hljs-built_in">console</span>.log(task)
    setTitle(task.title);
  };

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{title}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
}
</code></pre>
<p>In the code above, we create an <code>App</code> component that has a state called <code>title</code>, and we run the Fetch API to get a todo task from the API.</p>
<p>When a response is received, we parse the JSON string into a JavaScript object, log the object, and then set the <code>title</code> state to the <code>task.title</code> property value.</p>
<p>The response is as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/9-useeffect-log.png" alt="Image" width="600" height="400" loading="lazy">
<em>React useEffect Log</em></p>
<p>Here, you can see that the <code>console.log()</code> is called twice. This is because the <code>&lt;React.StrictMode&gt;</code> wrapper always runs a <code>useEffect</code> hook twice to help you in development.</p>
<p>If you remove the <code>&lt;React.StrictMode&gt;</code> wrapper in <code>main.jsx</code>, the <code>useEffect</code> hook will run only once.</p>
<p>The <code>useEffect</code> hook itself is a function that accepts two arguments:</p>
<ul>
<li>A callback function to run on every render</li>
<li>An array of state variables to watch for changes. <code>useEffect</code> will be skipped if none of the variables are updated.</li>
</ul>
<p>When you want to run <code>useEffect</code> only once, you can pass an empty array as the second argument to the function, as shown in the example above.</p>
<p>By using the <code>useEffect</code> hook, React can send HTTP requests and fetch data from any external system, then store that data in the component state.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>Congratulations on finishing this handbook! I hope you found it useful and now feel that learning React is not impossible or confusing at all. All you need is a step-by-step guide that reveals the key concepts of React one by one.</p>
<p>If you're eager to dive deeper into React and expand your skills, I encourage you to check out my new book called <em>Beginning React</em> here:</p>
<p><a target="_blank" href="https://codewithnathan.com/beginning-react"><img src="https://www.freecodecamp.org/news/content/images/2024/02/beginning-react-promo.png" alt="Beginning React Book" width="600" height="400" loading="lazy"></a></p>
<p>The goal of this book is to help you see how to build an application using React. There are two projects included in this book that will give you the "experience" of building a web application using React.</p>
<p>You will see how React concepts like components, JSX, props, states, hooks, and Context API are used to create a dynamic front-end application.</p>
<p>Here's my promise: <em>You will actually feel confident building web applications from scratch using React.</em></p>
<p>Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn Python Basics – A Guide for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ Are you eager to dive into the world of programming but unsure where to begin? Look no further – Python is an excellent starting point for both newcomers and seasoned developers.  In this guide, I'll take you through the basics so you can get started... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-python-basics/</link>
                <guid isPermaLink="false">66ba15982bddfbcfd2178948</guid>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Chepkirui Dorothy ]]>
                </dc:creator>
                <pubDate>Tue, 20 Feb 2024 19:04:56 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/learn-python-image.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Are you eager to dive into the world of programming but unsure where to begin? Look no further – Python is an excellent starting point for both newcomers and seasoned developers. </p>
<p>In this guide, I'll take you through the basics so you can get started on your Python journey.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
    <li><a href="#prerequisites">Prerequisites</a></li>
    <li><a href="#why-learn-python">Why Learn Python?</a></li>
    <li><a href="#key-characteristics-of-python">Key Characteristics of Python</a></li>
    <li><a href="#practical-uses-of-python">Practical Uses of Python</a></li>
    <li><a href="#how-to-write-hello-world-in-python">How to Write "Hello, World" in Python</a></li>
    <li><a href="#python-variables-and-data-types">Python Variables and Data Types</a>
        <ul>
            <li><a href="#primitive-fundamental-data-types-">Primitive (Fundamental) Data Types</a>
                <ul>
                    <li><a href="#characteristics-of-primitive-data-types-">Characteristics of Primitive Data Types</a></li>
                    <li><a href="#use-cases-for-primitive-data-types-">Use Cases for Primitive Data Types</a></li>
                </ul>
            </li>
            <li><a href="#non-primitive-composite-data-types-in-python">Non-Primitive (Composite) Data Types in Python</a>
                <ul>
                    <li><a href="#characteristics-of-non-primitive-data-types-">Characteristics of Non-Primitive Data Types</a></li>
                    <li><a href="#use-cases-for-non-primitive-data-types-">Use Cases for Non-Primitive Data Types</a></li>
                </ul>
            </li>
        </ul>
    </li>
    <li><a href="#operators-in-python">Operators in Python</a>
        <ul>
            <li><a href="#arithmetic-operators-">Arithmetic Operators</a></li>
            <li><a href="#comparison-operators">Comparison Operators</a></li>
        </ul>
    </li>
    <li><a href="#statements-in-python">Statements in Python</a>
        <ul>
            <li><a href="#assignment-statements">Assignment Statements</a> </li>

             <li><a href="#print-statement">Print Statement</a></li>


            <li><a href="#conditional-statements-if-elif-else-">Conditional Statements (if, elif, else)</a>

                    </li><li><a href="#loops-for-and-while-">Loops (for and while)</a>
                        <ul>
                            <li><a href="#for-loop-">For Loop</a></li>
                            <li><a href="#while-loop-">While Loop</a></li>

                    </ul></li></ul> </li>
                    <li><a href="#break-and-continue-statements">Break and Continue Statements</a></li>


        </ul>
    
    <li><a href="#functions-in-python">Functions in Python</a></li>
    <li><a href="#conclusion">Conclusion</a></li>



<h3 id="heading-prerequisites">Prerequisites</h3>
<p>Before you embark on this coding adventure, make sure you have the following:</p>
<ul>
<li><a target="_blank" href="https://www.python.org/downloads/">Python installed</a>.</li>
<li>A code editor like <a target="_blank" href="https://code.visualstudio.com/download">VSCode</a>, <a target="_blank" href="https://www.vim.org/download.php">Vim</a>, or <a target="_blank" href="https://www.sublimetext.com/3">Sublime</a>.</li>
</ul>
<p>Now, let's explore the advantages of using Python.</p>
<h2 id="heading-why-learn-python">Why Learn Python?</h2>
<p>If you're wondering why Python is an excellent choice for beginners and seasoned developers alike, here are some of the reasons:</p>
<ul>
<li><strong>Readability and Simplicity:</strong> Python's clean syntax enhances code readability, reducing development time and making it beginner-friendly.</li>
<li><strong>Versatility:</strong> You can use Python to build a diverse range of applications, from web development to data science and AI. It also has an extensive standard library and many helpful third-party packages.</li>
<li><strong>Community and Documentation:</strong> Python has a robust community and comprehensive documentation that provides ample support, fostering the language's popularity and growth.</li>
<li><strong>Cross-Platform Compatibility:</strong> Ensures seamless execution across Windows, macOS, and Linux.</li>
<li><strong>Extensive Libraries and Frameworks:</strong> A rich ecosystem simplifies complex tasks, saving time and effort for developers.</li>
</ul>
<p>Hopefully, you're intrigued by Python's perks – so let's delve into its key characteristics.</p>
<h2 id="heading-key-characteristics-of-python">Key Characteristics of Python</h2>
<p>Understanding the key characteristics of Python will give you insights into its strengths and why it's a popular choice among developers:</p>
<ul>
<li><strong>Interpreted Language:</strong> Your code is not directly translated by the target machine. Instead, a special program called the interpreter reads and executes the code, allowing for cross-platform execution of your code.</li>
<li><strong>Dynamically Typed:</strong> Dynamic typing eliminates the need for explicit data type declarations, enhancing simplicity and flexibility.</li>
<li><strong>Object-Oriented:</strong> Python supports object-oriented principles, promoting code modularity and reusability.</li>
<li><strong>Indentation-based Syntax:</strong> Indentation-based syntax enforces code readability and maintains a consistent coding style.</li>
<li><strong>Memory Management:</strong> Automatic memory management through garbage collection simplifies memory handling for developers.</li>
</ul>
<h2 id="heading-practical-uses-of-python">Practical Uses of Python</h2>
<p>Python's versatility and readability make it suitable for a wide array of applications. Here are some practical uses:</p>
<ul>
<li><strong>Web Development:</strong> Python, with frameworks like Django and Flask, powers back-end development for robust web applications.</li>
<li><strong>Data Science and Machine Learning:</strong> Widely used in data science, Python's libraries like NumPy and Pandas support data analysis and machine learning.</li>
<li><strong>Automation and Scripting:</strong> Python excels in automating tasks and scripting, simplifying repetitive operations.</li>
<li><strong>AI and NLP:</strong> Python, with libraries like TensorFlow, dominates in AI and natural language processing applications.</li>
<li><strong>Game Development:</strong> Python, combined with Pygame, facilitates 2D game development for hobbyists and indie developers.</li>
<li><strong>Scientific Computing:</strong> Python is a valuable tool in scientific computing, chosen by scientists and researchers for its extensive libraries.</li>
</ul>
<p>Python is pre-installed in most Linux distributions. Follow <a target="_blank" href="https://www.datacamp.com/blog/how-to-install-python">this article</a> on how to install Python on Windows and MacOS.</p>
<h2 id="heading-how-to-write-hello-world-in-python">How to Write "Hello, World" in Python</h2>
<p>This is usually the first achievement when starting to code in any language: having your code say 'Hello world'. Open any code editor of your choice, and create a file named <code>project.py</code>. Inside the file, type the following:</p>
<pre><code class="lang-python">     print(<span class="hljs-string">"Hello, World!"</span>)
</code></pre>
<p>To run this code, open the command line interface (CLI). Follow <a target="_blank" href="https://www.freecodecamp.org/news/command-line-for-beginners/">this article</a> to understand more about CLI.</p>
<p>Make sure to open the directory where the file is saved, and run the following:</p>
<pre><code class="lang-bash"> python3 project.py
</code></pre>
<p>When you run this program, you'll see the timeless greeting displayed in your command line interface.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-from-2024-01-30-11-59-12.png" alt="Image" width="600" height="400" loading="lazy">
<em>hello world displayed in the CLI</em></p>
<p>‌Congratulations! You've just executed your first Python script. Now that you've printed a simple message, let's dive deeper into Python.</p>
<h2 id="heading-python-variables-and-data-types"><strong>Python Variables and Data Types</strong></h2>
<p>The primary purpose of computers is to process data into useful information, for that to happen, the data needs to be stored in its memory. This is achieved using a programming language's variables and data types.</p>
<p>Data types in Python are particular kinds of data items, as defined by the value they can take. Variables, on the other hand, are like labeled containers that store this data. They enable you to manage and modify information using specific identifiers.</p>
<p>Data types are generally classified into two types:</p>
<h3 id="heading-primitive-fundamental-data-types">Primitive (Fundamental) Data Types:</h3>
<p>Primitive data types represent simple values. These data types are the most basic and essential units used to store and manipulate information in a program. They translate directly into low-level machine code. </p>
<p>Primitive data types include:</p>
<ul>
<li><strong>String (<code>str</code>):</strong> Represents sequences of characters. Should be enclosed in quotes. Example: <code>"Hello, Python!"</code></li>
<li><strong>Integer (<code>int</code>):</strong> Represents whole numbers without decimals. Example: <code>42</code></li>
<li><strong>Float (<code>float</code>):</strong> Represents numbers with decimals. Example: <code>3.14</code></li>
<li><strong>Boolean (<code>bool</code>):</strong> Represents either <code>True</code> or <code>False</code>.</li>
</ul>
<h4 id="heading-characteristics-of-primitive-data-types">Characteristics of Primitive Data Types:</h4>
<ul>
<li><strong>Immutability:</strong> Primitive data types are immutable, meaning their values cannot be changed after they are created. Any operation that appears to modify a primitive value creates a new value.</li>
<li><strong>Direct Representation:</strong> Each primitive data type directly corresponds to a specific low-level machine code representation.</li>
<li><strong>Atomic Values:</strong> Primitive data types represent individual, atomic values. They are not composed of other types or structures.</li>
</ul>
<h4 id="heading-use-cases-for-primitive-data-types">Use Cases for Primitive Data Types:</h4>
<ul>
<li>Strings are used for text manipulation and representation.</li>
<li>Integers and floats are essential for numerical calculations.</li>
<li>Booleans are employed in logical operations and decision-making.</li>
</ul>
<p>Let's see how these work by continuing to write some Python code.</p>
<p>Modify your <code>project.py</code> file to include the following:</p>
<pre><code class="lang-python"><span class="hljs-comment"># String Example </span>
name = <span class="hljs-string">"John"</span>
<span class="hljs-comment"># Integer Example</span>
age = <span class="hljs-number">25</span> 
<span class="hljs-comment"># Float Example </span>
height = <span class="hljs-number">1.75</span> 
<span class="hljs-comment"># Boolean Example</span>
is_student = <span class="hljs-literal">True</span>
<span class="hljs-comment"># Print variable values </span>
print(<span class="hljs-string">"Name:"</span>, name) 
print(<span class="hljs-string">"Age:"</span>, age) 
print(<span class="hljs-string">"Height:"</span>, height)
print(<span class="hljs-string">"Is student?"</span>, is_student)
</code></pre>
<p>In this snippet, you've introduced variables with different data types. Run the program and observe how Python handles these data types.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-from-2024-01-30-12-02-11.png" alt="Image" width="600" height="400" loading="lazy">
<em>primitive data types</em></p>
<p>The output reveals the values assigned to the variables in the Python script. The <code>print</code> statements display the contents of the <code>name</code>, <code>age</code>, <code>height</code>, and <code>is_student</code> variables. </p>
<h3 id="heading-non-primitive-composite-data-types-in-python">‌‌Non-Primitive (Composite) Data Types in Python</h3>
<p>Non-primitive data types are structures that can hold multiple values and are composed of other data types, including both primitive and other composite types. Unlike primitive data types, non-primitive types allow for more complex and structured representations of data.</p>
<p>Non-primitive data types include:</p>
<ul>
<li><strong>List (<code>list</code>):</strong> Represents an ordered and mutable collection of values. Example: <code>fruits = ["apple", "banana", "cherry"]</code></li>
<li><strong>Tuple (<code>tuple</code>):</strong> Represents an ordered and immutable collection of values. Example: <code>coordinates = (3, 7)</code></li>
<li><strong>Dictionary (<code>dict</code>):</strong> Represents an unordered collection of key-value pairs. Example: <code>person = {"name": "Alice", "age": 25, "is_student": True}</code></li>
</ul>
<h4 id="heading-characteristics-of-non-primitive-data-types">Characteristics of Non-Primitive Data Types:</h4>
<ul>
<li><strong>Mutability:</strong> Lists are mutable, meaning their elements can be modified after creation. Tuples, on the other hand, are immutable – their elements cannot be changed. Dictionaries are mutable – you can add, modify, or remove key-value pairs.</li>
<li><strong>Collection of Values:</strong> Non-primitive data types allow the grouping of multiple values into a single structure, enabling the creation of more sophisticated data representations.</li>
<li><strong>Ordered (Lists and Tuples):</strong> Lists and tuples maintain the order of elements, allowing for predictable indexing.</li>
<li><strong>Key-Value Mapping (Dictionary):</strong> Dictionaries map keys to values, providing a way to organize and retrieve data based on specific identifiers.</li>
</ul>
<h4 id="heading-use-cases-for-non-primitive-data-types">Use Cases for Non-Primitive Data Types:</h4>
<ul>
<li><strong>Lists:</strong> Useful when you need a collection that can be altered during the program's execution, such as maintaining a list of items that may change over time.</li>
<li><strong>Tuples:</strong> Suitable when you want to ensure that the data remains constant and cannot be accidentally modified. Often used for representing fixed sets of values.</li>
<li><strong>Dictionaries:</strong> Ideal for scenarios where data needs to be associated with specific labels or keys. They offer efficient data retrieval based on these identifiers.</li>
</ul>
<p>Alright, continuing with our Python code – modify the <code>project.py</code> file as shown below:</p>
<pre><code class="lang-python"><span class="hljs-comment"># List Example</span>
fruits = [<span class="hljs-string">"apple"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"cherry"</span>]
print(<span class="hljs-string">"List Example:"</span>, fruits)

<span class="hljs-comment"># Tuple Example</span>
coordinates = (<span class="hljs-number">3</span>, <span class="hljs-number">7</span>)
print(<span class="hljs-string">"Tuple Example:"</span>, coordinates)

<span class="hljs-comment"># Dictionary Example</span>
person = {<span class="hljs-string">"name"</span>: <span class="hljs-string">"Alice"</span>, <span class="hljs-string">"age"</span>: <span class="hljs-number">25</span>, <span class="hljs-string">"is_student"</span>: <span class="hljs-literal">True</span>}
print(<span class="hljs-string">"Dictionary Example:"</span>, person)
</code></pre>
<p>Run the program to see how lists and tuples allow you to organize and store data. In this code snippet:</p>
<ul>
<li>The <code>fruits</code> variable is a list containing strings representing different fruits.</li>
<li>The <code>coordinates</code> variable is a tuple with two integers representing coordinates.</li>
<li>The <code>person</code> variable is a dictionary associating keys ("name," "age," "is_student") with corresponding values.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-from-2024-01-31-11-19-39.png" alt="Image" width="600" height="400" loading="lazy">
<em>non-primitive data types</em></p>
<p>You can perform various operations on these structures, such as adding elements to a list or accessing individual items in a tuple.</p>
<p>Data types are crucial for several reasons:</p>
<ul>
<li><strong>Memory Allocation:</strong> Different data types require different amounts of memory. Knowing the data type allows the computer to allocate the appropriate amount of memory for a variable.</li>
<li><strong>Operations:</strong> Each data type supports specific operations. For example, you can add two <code>integer</code> numbers, concatenate two <code>strings</code>, or compare two <code>boolean</code> values.</li>
<li><strong>Error Prevention:</strong> Using the wrong data type in an operation can lead to errors. Data types help prevent unintended consequences by enforcing rules on how different types can interact.</li>
</ul>
<h2 id="heading-operators-in-python">Operators in Python</h2>
<p>Operators in Python are symbols that perform operations on variables and values.<br>An operand refers to the inputs or objects on which an operation is performed.</p>
<p>Let's explore some of the essential operators in Python:</p>
<h3 id="heading-arithmetic-operators">Arithmetic Operators:</h3>
<p>Arithmetic operators are fundamental components of any programming language, allowing developers to perform basic mathematical operations on numerical values. </p>
<p>In Python, several arithmetic operators enable you to carry out calculations efficiently. Let's explore these operators:</p>
<ul>
<li>Addition (+): Adds two operands.</li>
<li>Subtraction (-): Subtracts the right operand from the left operand.</li>
<li>Multiplication (*): Multiplies two operands.</li>
<li>Division (/): Divides the left operand by the right operand (always returns a float).</li>
<li>Modulus (%): Returns the remainder of the division of the left operand by the right operand.</li>
<li>Exponentiation (**): Raises the left operand to the power of the right operand.</li>
</ul>
<p>Modify your <code>project.py</code> file to include examples of these operators:</p>
<pre><code class="lang-python"> <span class="hljs-comment"># Arithmetic Operators</span>
 num1 = <span class="hljs-number">10</span> 
 num2 = <span class="hljs-number">3</span> 
 add_result = num1 + num2 
 sub_result = num1 - num2 
 mul_result = num1 * num2 
 div_result = num1 / num2 
 mod_result = num1 % num2 
 exp_result = num1 ** num2 
 print(<span class="hljs-string">"Addition:"</span>, add_result) 
 print(<span class="hljs-string">"Subtraction:"</span>, sub_result)
 print(<span class="hljs-string">"Multiplication:"</span>, mul_result) 
 print(<span class="hljs-string">"Division:"</span>, div_result) 
 print(<span class="hljs-string">"Modulus:"</span>, mod_result) 
 print(<span class="hljs-string">"Exponentiation:"</span>, exp_result)
</code></pre>
<p>The code above initializes two variables, <code>num1</code> and <code>num2</code>, with the values <code>10</code> and <code>3</code> respectively, representing two numerical operands.</p>
<p>Then, arithmetic operations are performed using these operands:</p>
<ul>
<li><code>add_result</code> stores the result of adding <code>num1</code> and <code>num2</code>.</li>
<li><code>sub_result</code> stores the result of subtracting <code>num2</code> from <code>num1</code>.</li>
<li><code>mul_result</code> stores the result of multiplying <code>num1</code> and <code>num2</code>.</li>
<li><code>div_result</code> stores the result of dividing <code>num1</code> by <code>num2</code>.</li>
<li><code>mod_result</code> stores the remainder of dividing <code>num1</code> by <code>num2</code>.</li>
<li><code>exp_result</code> stores the result of raising <code>num1</code> to the power of <code>num2</code>.</li>
</ul>
<p>Finally, the results of these arithmetic operations are printed using <code>print()</code> statements, each labeled appropriately, such as "Addition:", "Subtraction:", and so on, followed by the corresponding result.</p>
<p> Here's the output:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/arithmetic.png" alt="Image" width="600" height="400" loading="lazy">
<em>arithmetic operations</em></p>
<h3 id="heading-comparison-operators">Comparison Operators</h3>
<p>Comparison operators in Python are essential tools for evaluating and comparing values. They enable you to express conditions and make decisions based on the relationship between different values.  They return either <code>True</code> or <code>False</code> based on the comparison result.</p>
<p>Here are the common comparison operators:</p>
<ul>
<li>Equal to (==): Checks if two operands are equal.</li>
<li>Not equal to (!=): Checks if two operands are not equal.</li>
<li>Greater than (&gt;): Checks if the left operand is greater than the right operand.</li>
<li>Less than (&lt;): Checks if the left operand is less than the right operand.</li>
<li>Greater than or equal to (&gt;=): Checks if the left operand is greater than or equal to the right operand.</li>
<li>Less than or equal to (&lt;=): Checks if the left operand is less than or equal to the right operand.</li>
</ul>
<p>Extend your <code>project.py</code> file to include examples of comparison operators:</p>
<pre><code class="lang-python"> <span class="hljs-comment"># Comparison Operators </span>
 age = <span class="hljs-number">25</span>
 is_adult = age &gt;= <span class="hljs-number">18</span>
 is_teenager = age &gt;= <span class="hljs-number">13</span> <span class="hljs-keyword">and</span> age &lt; <span class="hljs-number">18</span>
 print(<span class="hljs-string">"Is adult?"</span>, is_adult)
 print(<span class="hljs-string">"Is teenager?"</span>, is_teenager)
</code></pre>
<p>The variable <code>age</code> is initialized with the value <code>25</code>, representing a person's age.</p>
<p>Then, the comparison operator <code>&gt;=</code> is used to evaluate whether <code>age</code> is greater than or equal to <code>18</code>. The result of this comparison determines the boolean value stored in the variable <code>is_adult</code>. If the age is <code>18</code> or older, <code>is_adult</code> will be <code>True</code>, indicating adulthood.</p>
<p>Then the logical operator <code>and</code> is utilized to combine two comparison operations. The first comparison, <code>age &gt;= 13</code>, checks if the age is <code>13</code> or older. The second comparison, <code>age &lt; 18</code>, ensures the age is less than <code>18</code>. If both conditions are true, <code>is_teenager</code> will be <code>True</code>, signifying teenage years.</p>
<p>Finally, the results are printed using <code>print()</code> statements, indicating whether the person is classified as an adult (<code>True</code> or <code>False</code>) and whether they are identified as a teenager (<code>True</code> or <code>False</code>).</p>
<p>Here's the output:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/is-adult.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-statements-in-python">Statements in Python</h2>
<p>Statements instruct the interpreter to perform specific actions or operations. These actions can range from simple assignments of values to variables to more complex control flow structures and iterations. </p>
<p>Understanding different types of statements is essential for writing effective and expressive Python code.</p>
<h3 id="heading-assignment-statements">Assignment Statements</h3>
<p>Assignment statements are the most basic type of statement in Python. They are used to assign values to variables, creating a named reference to data. </p>
<p>Here's an example:</p>
<pre><code class="lang-python">x = <span class="hljs-number">10</span> 
name = <span class="hljs-string">"Alice"</span>
</code></pre>
<p>In this snippet, <code>x</code> is assigned the integer value <code>10</code>, and the <code>name</code> is assigned the string <code>"Alice"</code>. These assignments create variables that can be used throughout the program.</p>
<h3 id="heading-print-statement">Print Statement</h3>
<p>The print statement is used to display output in the console. It is a crucial tool for debugging and providing information to users. Example:</p>
<pre><code class="lang-python">print(<span class="hljs-string">"Hello, Python!"</span>)
</code></pre>
<p>This code prints the string "Hello, Python!" to the console.</p>
<h3 id="heading-conditional-statements-if-elif-else">Conditional Statements (if, elif, else)</h3>
<p>Conditional statements are used when you want to execute different blocks of code based on certain conditions. </p>
<p>Suppose you wanted to determine if a person has reached the legal age for drinking.  Modify the <code>project.py</code> file with the following code:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Conditional Statement Example </span>
age = <span class="hljs-number">20</span>
<span class="hljs-keyword">if</span> age &lt; <span class="hljs-number">18</span>:
    print(<span class="hljs-string">"You are a minor."</span>)
<span class="hljs-keyword">elif</span> <span class="hljs-number">18</span> &lt;= age &lt; <span class="hljs-number">21</span>:
    print(<span class="hljs-string">"You are an adult, but not yet allowed to drink."</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"You are a legal adult."</span>)
</code></pre>
<p>In this example:</p>
<ul>
<li>The <code>if</code> statement checks if <code>age</code> is less than 18.</li>
<li>The <code>elif</code> statement (shorthand for else if) checks if <code>age</code> is between 18 (inclusive) and 21 (exclusive).</li>
<li>The <code>else</code> statement is executed if none of the above conditions are met.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/drinking.png" alt="Image" width="600" height="400" loading="lazy">
<em>if else statement</em></p>
<p>A person aged 20 is not allowed to drink.</p>
<h3 id="heading-loops-for-and-while">Loops (for and while)</h3>
<p>Loops are used to repeat a block of code multiple times. There are two main types of loops in Python: <code>for</code> loops and <code>while</code> loops.</p>
<h4 id="heading-for-loop">For Loop:</h4>
<p>A <code>for</code> loop is used when you know the number of iterations in advance. Suppose you had a list containing the names of fruits, and you wanted to print each fruit. In this case, a <code>for</code> loop is an ideal choice for iterating over the elements of the list. </p>
<p>Here's an example using Python:</p>
<pre><code class="lang-python"><span class="hljs-comment"># for loop Example </span>
fruits = [<span class="hljs-string">"apple"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"cherry"</span>]
<span class="hljs-keyword">for</span> fruit <span class="hljs-keyword">in</span> fruits:
    print(fruit)
</code></pre>
<p>‌In this example, the <code>for</code> loop iterates over each element in the <code>fruits</code> list and prints each fruit.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/apple.png" alt="Image" width="600" height="400" loading="lazy">
<em>list of fruits in the for loop</em></p>
<h4 id="heading-while-loop">While Loop:</h4>
<p>A <code>while</code> statement is a control flow statement that allows you to execute a block of code repeatedly as long as a specified condition is true.  </p>
<p>Suppose you want to simulate counting until a certain threshold is reached. Modify your <code>project.py</code> and add the following code:</p>
<pre><code class="lang-python"><span class="hljs-comment"># While Loop Example </span>
count = <span class="hljs-number">0</span>
<span class="hljs-keyword">while</span> count &lt; <span class="hljs-number">5</span>:
    print(<span class="hljs-string">"Count:"</span>, count)
    count += <span class="hljs-number">1</span>
</code></pre>
<p>In this scenario, the <code>while</code> loop continues executing as long as the <code>count</code> variable is less than 5. The code inside the loop increments the count and prints the current count in each iteration. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/count.png" alt="Image" width="600" height="400" loading="lazy">
<em>output of while loop</em></p>
<h3 id="heading-break-and-continue-statements">Break and Continue Statements</h3>
<p>Break and continue statements are used within loops.</p>
<ul>
<li><code>break</code>: Exits the loop.</li>
<li><p><code>continue</code>: Skips the rest of the code inside the loop for the current iteration, then continues the loop.</p>
<p>Examples:</p>
</li>
</ul>
<pre><code class="lang-python">‌<span class="hljs-comment"># Break Statement Example </span>
print(<span class="hljs-string">"Output with 'break':"</span>)
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">5</span>):
    <span class="hljs-keyword">if</span> i == <span class="hljs-number">3</span>:
        print(<span class="hljs-string">f"Encountered 'break' at i=<span class="hljs-subst">{i}</span>"</span>) 
        <span class="hljs-keyword">break</span>
    print(i)

<span class="hljs-comment"># Continue Statement Example </span>
print(<span class="hljs-string">"\nOutput with 'continue':"</span>)
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">5</span>):
    <span class="hljs-keyword">if</span> i == <span class="hljs-number">2</span>:
        print(<span class="hljs-string">f"Skipped iteration with 'continue' at i=<span class="hljs-subst">{i}</span>"</span>)
        <span class="hljs-keyword">continue</span>
    print(i)
</code></pre>
<p>‌In the <code>break</code> example, the loop stops when <code>i</code> is equal to 3, and the numbers 0, 1, and 2 are printed. </p>
<p>In the <code>continue</code> example, when <code>i</code> is equal to 2, the <code>continue</code> statement skips the <code>print(i)</code> statement for that iteration, resulting in the omission of the number 2 from the output.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/break1.png" alt="Image" width="600" height="400" loading="lazy">
<em>break and continue statements output</em></p>
<h2 id="heading-functions-in-python">Functions in Python</h2>
<p>Functions are reusable blocks of code, enhancing modularity by enclosing functionality into separate, organized units. This approach helps avoid code duplication and significantly improves code readability. </p>
<p>Inside the <code>project.py</code> file, write the following code:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">greet</span>():</span>
    print(<span class="hljs-string">"Hello, World!"</span>)

<span class="hljs-comment"># Call the function to execute</span>
greet()
</code></pre>
<p>The code above contains a simple Python function called <code>greet()</code>. When 'called' or 'invoked', this function prints "Hello, World!" to the console. It's a basic example illustrating how functions work in Python.</p>
<p>You can take this a step further by including parameters. Parameters serve as placeholders for values passed to a function during its invocation, allowing functions to accept input and perform operations based on that input.</p>
<p>Modify the previous example on <code>if elif else</code> statement to include functions:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_age</span>(<span class="hljs-params">age</span>):</span>
    <span class="hljs-keyword">if</span> age &lt; <span class="hljs-number">18</span>:
        print(<span class="hljs-string">"You are a minor."</span>)
    <span class="hljs-keyword">elif</span> <span class="hljs-number">18</span> &lt;= age &lt; <span class="hljs-number">21</span>:
        print(<span class="hljs-string">"You are an adult, but not yet allowed to drink."</span>)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">"You are a legal adult."</span>)

<span class="hljs-comment"># Call the function with a specific age</span>
check_age(<span class="hljs-number">20</span>)
</code></pre>
<p>In this example, the <code>check_age</code> function takes an <code>age</code> parameter and performs the same conditional check as the original code. The function allows you to reuse this logic for different age values by simply calling the function with the desired age.</p>
<p>You can call <code>check_age</code> function with any age value, and it will print the appropriate message based on the age provided.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-from-2024-02-07-13-03-23.png" alt="Image" width="600" height="400" loading="lazy">
<em>functions</em></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>‌‌‌‌Embarking on your Python learning journey, this guide introduces the benefits of learning Python, its key characteristics, and practical use cases. </p>
<p>Starting with the iconic "Hello, World!" and progressing through variables, data types, statements, and functions, you've gained some hands-on experience with basic Python. We also talked about primitive and non-primitive data types, conditional statements, and loops.</p>
<p>As your journey progresses, delve into advanced topics like object-oriented programming, file handling, and real-world projects. Armed with foundational knowledge, you can now embrace coding challenges that come your way. Stay curious, and relish the rewarding process of coding with Python. Happy coding!</p>
<p>‌‌</p>
<p>‌‌</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
