<?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[ Joel Olawanle - 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[ Joel Olawanle - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 31 May 2026 09:37:50 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/olawanlejoel/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Traditional Scraping vs AI Scraping: A Practical Guide for Developers and Data Teams ]]>
                </title>
                <description>
                    <![CDATA[ Enormous amounts of data are constantly generated on the open web. Product prices change, job listings go live and get taken down, news articles are published, and company information gets updated. Fo ]]>
                </description>
                <link>https://www.freecodecamp.org/news/traditional-scraping-vs-ai-scraping/</link>
                <guid isPermaLink="false">69e156abffbb787634ffa61a</guid>
                
                    <category>
                        <![CDATA[ web scraping ]]>
                    </category>
                
                    <category>
                        <![CDATA[ data ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joel Olawanle ]]>
                </dc:creator>
                <pubDate>Thu, 16 Apr 2026 21:37:47 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/c7f16b00-5245-48e2-a864-38a86d4292ae.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Enormous amounts of data are constantly generated on the open web. Product prices change, job listings go live and get taken down, news articles are published, and company information gets updated.</p>
<p>For developers and teams that rely on this kind of data, the question has never been whether to scrape the web, but how to do so reliably over time.</p>
<p>For a long time, the approach has been straightforward. You inspect a page, write selectors, and extract the data using tools like <a href="https://pypi.org/project/beautifulsoup4/">BeautifulSoup</a> or browser automation libraries like <a href="https://playwright.dev/">Playwright</a> and <a href="https://www.selenium.dev/">Selenium</a>. This works well, but it comes with a familiar problem: the moment the structure of a page changes, your scraper breaks and needs fixing.</p>
<p>Recently, a different approach has started gaining attention. Instead of writing selectors, you describe what you want and let the system figure out how to extract it. This is what people refer to as AI scraping.</p>
<p>Both approaches are widely used today, but they solve the problem in very different ways. This guide breaks down how each one works, where each one fits, and how to decide which approach makes sense for your use case.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a href="#heading-what-is-traditional-web-scraping">What is Traditional Web Scraping?</a></p>
</li>
<li><p><a href="#heading-traditional-scraping-in-practice">Traditional Scraping in Practice</a></p>
</li>
<li><p><a href="#heading-what-is-ai-web-scraping">What is AI Web Scraping?</a></p>
</li>
<li><p><a href="#heading-ai-scraping-in-practice">AI Scraping in Practice</a></p>
</li>
<li><p><a href="#heading-traditional-scraping-vs-ai-scraping-when-to-use-each">Traditional Scraping vs AI Scraping: When to Use Each</a></p>
</li>
</ul>
<h2 id="heading-what-is-traditional-web-scraping">What is Traditional Web Scraping?</h2>
<p><a href="https://www.freecodecamp.org/news/web-scraping-in-javascript-with-puppeteer/">Traditional web scraping</a> scraping is built on a simple idea that if a browser can load a page and display data to a user, then a program should be able to do the same and extract that data automatically.</p>
<p>This is done with CSS selectors and XPath. For CSS selectors, a selector like <code>.product-card .price</code> means “find the price element inside a product card.” It's easy to understand and works well for most use cases.</p>
<p>XPath, on the other hand, is more powerful but more complex. It allows you to navigate the structure of a page in more detail, including moving up and down the DOM, filtering by text, or handling deeply nested elements.</p>
<p>In practice, most developers start with CSS selectors and only use XPath when the structure becomes too complex.</p>
<p>This idea has been around since the early days of the web. Instead of manually copying information from a page, developers started writing scripts that send requests, receive HTML responses, and extract the pieces they care about.</p>
<p>At its core, nothing about that model has really changed.</p>
<p>You still fetch a page, inspect its structure, and extract data from it. The difference today is not the concept, but how sophisticated the tooling and scale have become.</p>
<h3 id="heading-the-tools-behind-traditional-scraping">The Tools Behind Traditional Scraping</h3>
<p>Over time, a solid ecosystem of tools has developed around this approach.</p>
<ul>
<li><p><a href="https://pypi.org/project/requests/"><strong>Requests</strong></a> is the de facto Python library for making HTTP calls. Most traditional scrapers use <code>requests</code> to fetch pages and then pass the response to BeautifulSoup for parsing. It's simple and reliable for static sites.</p>
</li>
<li><p><a href="https://pypi.org/project/beautifulsoup4/"><strong>BeautifulSoup</strong></a> is a Python library for parsing HTML and XML. It takes raw HTML and builds a navigable tree of objects from it. It's fast to learn, very readable, and excellent for static pages. Its main limitation is that it has no browser engine, so it can't execute JavaScript. If a site renders content dynamically after page load, BeautifulSoup will see an empty container.</p>
</li>
<li><p><a href="https://www.selenium.dev/"><strong>Selenium</strong></a> and <a href="https://playwright.dev/"><strong>Playwright</strong></a> are browser automation tools that control a real browser. They can click buttons, scroll, and wait for JavaScript to finish loading before extracting data. The trade-off is that they are slower and more resource-intensive than simple HTTP requests, but they are necessary for dynamic sites.</p>
</li>
</ul>
<h2 id="heading-traditional-scraping-in-practice">Traditional Scraping in Practice</h2>
<p>Let's build a real, working scraper using <a href="https://books.toscrape.com/">Books to Scrape</a>, a sandbox site built specifically for practicing web scraping. The goal is to extract the title, price, and star rating for every book listed on the first page.</p>
<h3 id="heading-step-1-install-dependencies">Step 1: Install Dependencies</h3>
<pre><code class="language-plaintext">pip install requests beautifulsoup4
</code></pre>
<h3 id="heading-step-2-inspect-the-page">Step 2: Inspect the Page</h3>
<p>Before writing a single line of code, open the target page in your browser and inspect its HTML. Right-click any book title and choose "Inspect" to see the structure.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e33f66ffc003cfb0c64069e/3b47f64a-8ac8-4cf2-9237-b117355bec5f.png" alt="Inspecting the page structure" style="display:block;margin:0 auto" width="3018" height="1654" loading="lazy">

<p>You'll notice each book lives inside an <code>&lt;article class="product_pod"&gt;</code> element, and within it:</p>
<ul>
<li><p>The title is in the <code>&lt;h3&gt;</code> tag, inside an <code>&lt;a&gt;</code> element (as a <code>title</code> attribute)</p>
</li>
<li><p>The price is in a <code>&lt;p class="price_color"&gt;</code> element</p>
</li>
<li><p>The star rating is encoded in the CSS class of a <code>&lt;p&gt;</code> element — for example, <code>&lt;p class="star-rating Three"&gt;</code> means three stars</p>
</li>
</ul>
<p>This is the core detective work of traditional scraping: you study the HTML, find the patterns, and write selectors to match them.</p>
<h3 id="heading-step-3-write-the-scraper">Step 3: Write the Scraper</h3>
<pre><code class="language-python">import requests
from bs4 import BeautifulSoup

# 1. Fetch the page
url = "https://books.toscrape.com/"
response = requests.get(url)

# Always check the request succeeded before going further
if response.status_code != 200:
    print(f"Failed to fetch page: {response.status_code}")
    exit()

# 2. Parse the HTML
soup = BeautifulSoup(response.content, "html.parser")

# 3. Find all book containers on the page
books = soup.select("article.product_pod")

# 4. Extract data from each book
results = []

for book in books:
    # Title is stored as an attribute, not visible text
    title = book.select_one("h3 a")["title"]

    # Price is the text inside the price element
    price = book.select_one("p.price_color").get_text(strip=True)

    # Rating is encoded as a word in the CSS class: "star-rating Three"
    # We grab the second class name and map it to a number
    rating_word = book.select_one("p.star-rating")["class"][1]
    rating_map = {"One": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5}
    rating = rating_map.get(rating_word, 0)

    results.append({
        "title": title,
        "price": price,
        "rating": rating
    })

# 5. Display results
for book in results:
    print(f"{book['title']} | {book['price']} | {book['rating']} stars")
</code></pre>
<h3 id="heading-step-4-run-it">Step 4: Run It</h3>
<pre><code class="language-bash">python scraper.py
</code></pre>
<p>Your output will look something like this:</p>
<pre><code class="language-bash">A Light in the Attic | £51.77 | 3 stars
Tipping the Velvet | £53.74 | 1 stars
Soumission | £50.10 | 1 stars
Sharp Objects | £47.82 | 4 stars
Sapiens: A Brief History of Humankind | £54.23 | 5 stars
...
</code></pre>
<p>Twenty books, all structured and clean.</p>
<h3 id="heading-step-5-extend-it-to-multiple-pages">Step 5: Extend It to Multiple Pages</h3>
<p>The site has 50 pages. Extending the scraper to crawl all of them requires following the "next" button:</p>
<pre><code class="language-python">import requests
from bs4 import BeautifulSoup

BASE_URL = "https://books.toscrape.com/catalogue/"
start_url = "https://books.toscrape.com/catalogue/page-1.html"

all_books = []
url = start_url

while url:
    response = requests.get(url)
    soup = BeautifulSoup(response.content, "html.parser")

    for book in soup.select("article.product_pod"):
        title = book.select_one("h3 a")["title"]
        price = book.select_one("p.price_color").get_text(strip=True)
        rating_word = book.select_one("p.star-rating")["class"][1]
        rating_map = {"One": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5}
        rating = rating_map.get(rating_word, 0)
        all_books.append({"title": title, "price": price, "rating": rating})

    # Check for a "next" button and follow it
    next_btn = soup.select_one("li.next a")
    url = BASE_URL + next_btn["href"] if next_btn else None

print(f"Scraped {len(all_books)} books total.")
</code></pre>
<p>Running this crawls all 1,000 books across all 50 pages.</p>
<h3 id="heading-what-makes-this-approach-fragile">What Makes This Approach Fragile</h3>
<p>This scraper works well today because <code>books.toscrape.com</code> is a static, stable sandbox. In production, the same approach has a well-known weakness: it's completely dependent on the HTML structure staying the same.</p>
<p>If the site's developer renames <code>product_pod</code> to <code>book-card</code>, or moves the price into a <code>&lt;div&gt;</code> instead of a <code>&lt;p&gt;</code>, every selector breaks. You get no data, or worse, incorrect data with no error, and you only discover the breakage when someone notices the output looks wrong.</p>
<p>This is one of the problems AI scraping is designed to address.</p>
<h2 id="heading-what-is-ai-web-scraping">What is AI Web Scraping?</h2>
<p>Traditional scraping works by following the structure of a page. It looks for specific elements, class names, or patterns in the HTML and extracts data based on those rules.</p>
<p>AI-powered scraping approaches the same problem differently. Instead of relying only on structure, it focuses on understanding the content itself. It looks at a page and identifies what something represents, not just where it's located.</p>
<p>In a traditional scraper, you might write something like:</p>
<pre><code class="language-javascript">response.css(".product-card .price::text").get()
</code></pre>
<p>You're telling the system exactly where to look. But, with AI scraping, you describe the outcome:</p>
<pre><code class="language-plaintext">Extract the product name, price, and availability for each item on this page.
</code></pre>
<p>The system reads the page, identifies what appears to be a product listing, extracts the relevant fields, and returns structured data.</p>
<h3 id="heading-whats-actually-happening-under-the-hood">What's Actually Happening Under the Hood</h3>
<p>AI scraping can feel like magic at first, but it's built on a combination of familiar components.</p>
<p>At the core are <strong>large language models (LLMs)</strong> trained on vast amounts of text, including web content and HTML. Over time, they learn patterns such as what a product listing looks like, how prices are usually presented, or how job listings are structured.</p>
<p>When given a page, the model can recognize these patterns and map them to the fields you asked for.</p>
<p>But the model is only one part of the system. You still need something to load and interact with the page. That is where <strong>browser automation</strong> comes in. Most AI scraping tools rely on headless browsers like Chromium or frameworks like Playwright to render pages, execute JavaScript, and handle real-world behavior such as scrolling or clicking.</p>
<p>On top of that, there's a layer that interprets your input. When you write a <strong>prompt</strong> describing the data you want, the system translates that into an extraction task. It decides what parts of the page are relevant and how to structure the output.</p>
<p>Finally, the system formats the results into clean data, typically as JSON or CSV, so you can use them directly with minimal post-processing.</p>
<p><strong>Note:</strong> Tools like ChatGPT can interpret content, but they're not scraping systems. They don't crawl pages, handle workflows, or run repeatable data extraction. AI scraping tools combine this intelligence with the infrastructure required to collect data reliably.</p>
<h3 id="heading-popular-tools-behind-ai-scraping">Popular Tools Behind AI Scraping</h3>
<p>As AI scraping has grown more popular, a number of tools have emerged that make this approach accessible without requiring you to build everything from scratch.</p>
<p>For example:</p>
<ul>
<li><p><a href="https://spidra.io/"><strong>Spidra</strong></a> takes a pretty direct approach to extraction. You describe the data you want, and it handles loading the page, interpreting the content, and returning structured results. It also manages things like navigation and interactions behind the scenes, which makes it useful when you want to extract data without worrying about selectors or maintaining scraping logic.</p>
</li>
<li><p><a href="https://www.firecrawl.dev/"><strong>Firecrawl</strong></a> focuses on turning web pages into clean, structured content. Instead of extracting specific fields like price or title, it converts entire pages into formats like markdown or simplified JSON. This makes it especially useful when you want to feed web content into AI systems or work with it in a readable format without dealing with messy HTML.</p>
</li>
<li><p><a href="https://jina.ai/reader/"><strong>Jina Reader</strong></a> is designed to simplify web pages into clean text. It strips away layout noise such as navigation, ads, and styling, and focuses on the actual content. This is helpful when your goal is to understand or process the information on a page rather than extract structured fields.</p>
</li>
<li><p><a href="https://brightdata.com/products/web-scraper/ai"><strong>Bright Data AI scrapers</strong></a> combine AI-based extraction with a strong scraping infrastructure. They allow you to request structured data without writing selectors, while also handling challenges like blocking and scaling. This makes them more suitable for larger or more demanding scraping tasks.</p>
</li>
<li><p><a href="https://apify.com/"><strong>Apify</strong></a> sits somewhere in between traditional and AI-driven scraping. It provides a full platform for building and running scrapers, and allows you to introduce AI where it makes sense, whether for extraction or post-processing. This makes it useful when you need more control over the entire pipeline.</p>
</li>
</ul>
<p>In practice, these tools aren't trying to solve the exact same problem. Some focus on extracting structured data, others on cleaning content, and others on building full scraping workflows. The right choice depends on what you're trying to achieve, not just the tool itself.</p>
<h2 id="heading-ai-scraping-in-practice">AI Scraping in Practice</h2>
<p>Let's run the same data collection task of extracting books from <code>books.toscrape.com</code> using an AI scraping tool. We'll use Spidra's API so you can see exactly what changes.</p>
<h3 id="heading-step-1-get-an-api-key">Step 1: Get an API Key</h3>
<p>Sign up at <a href="http://spidra.io">spidra.io</a> and create an API key from your dashboard. You'll use this key to authenticate every request.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e33f66ffc003cfb0c64069e/b4dd4103-d9ee-4193-b8df-b62cd815bb16.png" alt="Getting Spidra API key" style="display:block;margin:0 auto" width="3024" height="1656" loading="lazy">

<h3 id="heading-step-2-understand-the-api-structure">Step 2: Understand the API Structure</h3>
<p>Spidra's scrape endpoint accepts a JSON payload. The two most important fields are <code>url</code> (where to scrape) and <code>prompt</code> (what to extract, written in plain English). You can optionally specify the <code>output</code> format — JSON works best for structured data.</p>
<pre><code class="language-bash">POST https://api.spidra.io/scrape
Authorization: Bearer YOUR_API_KEY
Content-Type: application/json
</code></pre>
<p>You see, we don't need selectors or HTML inspection. Just a URL and a description.</p>
<h3 id="heading-step-3-write-a-single-page-extraction">Step 3: Write a Single-Page Extraction</h3>
<p>Here's the equivalent of our traditional scraper, written as an API call:</p>
<pre><code class="language-python">import requests
import json

API_KEY = "your_api_key_here"

payload = {
    "urls": [{"url": "https://books.toscrape.com/"}],
    "prompt": "Extract all books on this page. For each book, return the title, price, and star rating as a number from 1 to 5.",
    "output": "json"
}

response = requests.post(
    "https://api.spidra.io/scrape",
    headers={
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    },
    json=payload
)

data = response.json()
print(json.dumps(data, indent=2))
</code></pre>
<p>That's the entire scraper. No <code>BeautifulSoup</code>, no selector logic, and no HTML parsing.</p>
<h3 id="heading-step-4-understand-the-output">Step 4: Understand the Output</h3>
<p>The API returns a structured JSON response. Each book is represented as an object with the fields you described:</p>
<pre><code class="language-json">{
  "results": [
    {
      "title": "A Light in the Attic",
      "price": "£51.77",
      "rating": 3
    },
    {
      "title": "Tipping the Velvet",
      "price": "£53.74",
      "rating": 1
    },
    {
      "title": "Soumission",
      "price": "£50.10",
      "rating": 1
    }
    ...
  ]
}
</code></pre>
<p>The model identified the star rating encoding (<code>star-rating Three</code> → 3) without being told how ratings are represented. It understood the intent of "star rating as a number from 1 to 5" and handled the mapping itself.</p>
<h3 id="heading-step-5-use-actions-for-multi-step-workflows">Step 5: Use Actions for Multi-Step Workflows</h3>
<p>Where AI scraping starts to show its real advantages is with workflows that would require significant engineering in a traditional scraper.</p>
<p>Suppose you want to visit each book's detail page and extract the full description and availability status (not just what's visible on the listing page).</p>
<p>In a traditional scraper, this means building a follow-link loop, managing state, handling errors on each detail page, and maintaining separate selectors for the detail page's different structure. In an AI scraper like Spidra, you can mimic a real human interaction with <a href="https://docs.spidra.io/features/actions">browser actions</a>:</p>
<pre><code class="language-python">{
  "urls": [{
    "url": "https://books.toscrape.com/catalogue/category/books/mystery_3/index.html",
    "actions": [{
      "type":            "forEach",
      "observe":         "Find all book cards in the product grid",
      "mode":            "inline",
      "captureSelector": "article.product_pod",
      "maxItems":        10,
      "itemPrompt":      "Extract the book title, price, and star rating (One/Two/Three/Four/Five). Return as JSON: {title, price, star_rating}"
    }]
  }]
}
</code></pre>
<p>The system navigates to each book's page, reads the new content, extracts the additional fields, and returns them as part of the same result set.</p>
<p>You can also configure how you want your data to be:</p>
<pre><code class="language-python">{
  "urls": [{ "url": "https://jobs.example.com/senior-engineer" }],
  "prompt": "Extract the job details",
  "schema": {
    "type": "object",
    "required": ["title", "company", "remote", "employment_type"],
    "properties": {
      "title":           { "type": "string" },
      "company":         { "type": "string" },
      "location":        { "type": ["string", "null"] },
      "remote":          { "type": ["boolean", "null"] },
      "salary_min":      { "type": ["number", "null"] },
      "salary_max":      { "type": ["number", "null"] },
      "employment_type": {
        "type": ["string", "null"],
        "enum": ["full_time", "part_time", "contract", null]
      },
      "skills": {
        "type": "array",
        "items": { "type": "string" }
      }
    }
  }
}
</code></pre>
<p>There is more to these AI scrapers, like <a href="https://docs.spidra.io/features/batch-scraping">batch scraping</a>, AI crawling, and lots more.</p>
<h3 id="heading-where-ai-scraping-earns-its-keep">Where AI Scraping Earns Its Keep</h3>
<p>Now suppose the site updates its frontend. The class <code>product_pod</code> gets renamed to <code>book-card</code>. The price moves into a different element.</p>
<p>In the traditional scraper, you get zero results and no error until you notice the data is missing. You then re-inspect the page, update the selectors, test, and redeploy.</p>
<p>In the AI scraper, you run the same prompt. The model isn't looking for <code>product_pod</code> or <code>price_color</code>. It's looking for content that resembles a product listing with pricing information. The layout change is invisible to the extraction logic.</p>
<p>This is the core operational advantage of the AI approach: <strong>structural changes to a page don't automatically break your extraction.</strong></p>
<h2 id="heading-traditional-scraping-vs-ai-scraping-when-to-use-each">Traditional Scraping vs AI Scraping: When to Use Each</h2>
<p>At this point, the difference between the two approaches is clear. The more important question is when each one actually makes sense in practice.</p>
<p>A simple way to think about it is this:</p>
<table>
<thead>
<tr>
<th><strong>Scenario</strong></th>
<th><strong>Traditional Scraping</strong></th>
<th><strong>AI Scraping</strong></th>
</tr>
</thead>
<tbody><tr>
<td>Stable websites</td>
<td>✅ Best choice</td>
<td>✅ Works but may sometimes become an overkill</td>
</tr>
<tr>
<td>Frequently changing layouts</td>
<td>❌ Breaks often</td>
<td>✅ More resilient</td>
</tr>
<tr>
<td>Large-scale crawling</td>
<td>✅ More cost-efficient</td>
<td>✅ Efficient but can get expensive</td>
</tr>
<tr>
<td>Fast prototyping</td>
<td>❌ Slower setup</td>
<td>✅ Very fast</td>
</tr>
<tr>
<td>Non-technical users</td>
<td>❌ Requires coding</td>
<td>✅ More accessible</td>
</tr>
<tr>
<td>Full control &amp; transparency</td>
<td>✅ High control</td>
<td>❌ Less transparent</td>
</tr>
<tr>
<td>Messy or inconsistent data</td>
<td>❌ Hard to maintain</td>
<td>✅ Easier to handle</td>
</tr>
<tr>
<td>Complex workflows (login, steps)</td>
<td>⚠️ Possible but manual</td>
<td>✅ Often built-in</td>
</tr>
</tbody></table>
<p>In practice, it's not a cut-and-dry choice between the two. Traditional scraping works best when everything is predictable and stable. AI scraping becomes useful when things are messy, dynamic, or time-sensitive. Most real-world systems combine both approaches rather than relying on one alone.</p>
<h2 id="heading-wrapping-up">Wrapping up</h2>
<p>Web scraping is not going away. What's changing is how we approach it.</p>
<p>Traditional scraping gives you control and precision, but it can be fragile and time-consuming to maintain. AI scraping makes things faster and more flexible, especially when dealing with messy or constantly changing pages, but it comes with less transparency.</p>
<p>In practice, most real-world workflows are starting to combine both.</p>
<p>We're also beginning to see AI scraping tools integrate into larger systems, especially with AI agents and MCP-style setups, where scraping becomes something that can be triggered on demand rather than built from scratch each time.</p>
<p>The key takeaway is simple. Traditional scraping tells the system where the data is. AI scraping tells the system what the data means.</p>
<p>Knowing when to use each is what actually matters.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Format a Date with JavaScript – Date Formatting in JS ]]>
                </title>
                <description>
                    <![CDATA[ Dates are a fundamental part of many JavaScript applications, whether it's displaying the current date on a webpage or handling user input for scheduling events. But displaying dates in a clear and consistent format is crucial for a positive user exp... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-format-a-date-with-javascript-date-formatting-in-js/</link>
                <guid isPermaLink="false">66d45f9b36c45a88f96b7cf9</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joel Olawanle ]]>
                </dc:creator>
                <pubDate>Wed, 31 May 2023 17:48:04 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/cover-template.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Dates are a fundamental part of many JavaScript applications, whether it's displaying the current date on a webpage or handling user input for scheduling events.</p>
<p>But displaying dates in a clear and consistent format is crucial for a positive user experience.</p>
<p>In the past, I have written two articles on Date formatting. The first explained solely <a target="_blank" href="https://www.freecodecamp.org/news/how-to-format-dates-in-javascript/">how to use the <code>toLocaleDateString()</code> method to format dates</a>, while the second explained <a target="_blank" href="https://www.freecodecamp.org/news/javascript-date-format-how-to-format-a-date-in-js/">custom date formatting with the <code>getFullYear()</code>, <code>getMonth()</code>, and <code>getDate()</code> methods</a>.</p>
<p>In this article, we'll explore various techniques to format dates in JavaScript, enabling you to present dates in your desired format for your application.</p>
<h2 id="heading-how-to-use-the-javascript-date-object">How to Use the JavaScript Date Object</h2>
<p>Before we dive into date formatting, let's get familiar with the JavaScript <code>Date</code> object. It provides methods to work with dates and times effectively.</p>
<p>To create a new date instance, you can use the <code>new Date()</code> constructor.</p>
<p>For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> currentDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
<span class="hljs-built_in">console</span>.log(currentDate); <span class="hljs-comment">// Wed May 31 2023 08:26:18 GMT+0100 (West Africa Standard Time)</span>
</code></pre>
<p>The above code will output the current date and time in the default format. However, this format is not suitable for all use cases.</p>
<p>This is why we need to format dates so we can extract what we need from this date object.</p>
<p>In JavaScript, there is no direct syntax that provides you with your expected format because date format varies based on location, circumstance, and so on.</p>
<h2 id="heading-basic-javascript-date-formatting-methods">Basic JavaScript Date Formatting Methods</h2>
<p>JavaScript provides a few built-in methods to format dates conveniently. Let's take a look at some of these methods:</p>
<ol>
<li><strong>toDateString()</strong>: This method converts the date portion of a <code>Date</code> object into a human-readable string format.</li>
</ol>
<p>For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> date = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
<span class="hljs-built_in">console</span>.log(date.toDateString());
</code></pre>
<p>Output: <code>Wed May 30 2023</code></p>
<ol start="2">
<li><strong>toISOString()</strong>: This method converts a <code>Date</code> object into a string representation following the ISO 8601 format.</li>
</ol>
<p>For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> date = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
<span class="hljs-built_in">console</span>.log(date.toISOString());
</code></pre>
<p>Output: <code>2023-05-30T00:00:00.000Z</code></p>
<ol start="3">
<li><strong>toLocaleDateString()</strong>: This method returns a string representing the date portion of a <code>Date</code> object using the system's local conventions.</li>
</ol>
<p>For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> date = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
<span class="hljs-built_in">console</span>.log(date.toLocaleDateString());
</code></pre>
<p>Output: <code>5/30/2023</code>. This Format may vary based on the system's locale. For more explanation on how this method works, <a target="_blank" href="https://www.freecodecamp.org/news/how-to-format-dates-in-javascript/">read this article</a>.</p>
<h2 id="heading-custom-date-formatting-in-javascript">Custom Date Formatting in JavaScript</h2>
<p>While the basic formatting methods can be useful in certain scenarios, you might often need more control over the date format.</p>
<p>JavaScript provides a couple ways to achieve custom date formatting:</p>
<ol>
<li><strong>String Concatenation</strong>: One approach is to manually concatenate the different components of a date using string manipulation.</li>
</ol>
<p>For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> date = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
<span class="hljs-keyword">const</span> formattedDate = <span class="hljs-string">`<span class="hljs-subst">${date.getDate()}</span>-<span class="hljs-subst">${date.getMonth() + <span class="hljs-number">1</span>}</span>-<span class="hljs-subst">${date.getFullYear()}</span>`</span>;
<span class="hljs-built_in">console</span>.log(formattedDate);
</code></pre>
<p>Output: <code>**30-5-2023**</code>.</p>
<p>You can manipulate this however you like and come up with more creative ways of representing dates. You can read this article to understand custom date formatting in detail and <a target="_blank" href="https://www.freecodecamp.org/news/javascript-date-format-how-to-format-a-date-in-js/">this article</a> on <a target="_blank" href="https://www.freecodecamp.org/news/format-dates-with-ordinal-number-suffixes-javascript/">how to format dates with ordinal number suffixes (-st, -nd, -rd, -th) in JavaScript</a>.</p>
<ol start="2">
<li><strong>Intl.DateTimeFormat</strong>: JavaScript's <code>Intl</code> object offers powerful formatting capabilities through the <code>DateTimeFormat</code> object. It provides localization support and various options to format dates and times.</li>
</ol>
<p>Here's an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> date = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
<span class="hljs-keyword">const</span> formatter = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Intl</span>.DateTimeFormat(<span class="hljs-string">'en-US'</span>, { <span class="hljs-attr">dateStyle</span>: <span class="hljs-string">'short'</span> });
<span class="hljs-keyword">const</span> formattedDate = formatter.format(date);
<span class="hljs-built_in">console</span>.log(formattedDate);
</code></pre>
<p>Output: <code>5/30/23</code></p>
<p>Using <code>Intl.DateTimeFormat</code>, you can specify the desired locale and various options to format dates precisely as needed. There are more options you can use in the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat">official documentation</a>.</p>
<h2 id="heading-how-to-handle-time-zones-when-working-with-dates">How to Handle Time Zones When Working with Dates</h2>
<p>When working with dates, it's essential to consider time zones, especially when dealing with global applications or time-sensitive information.</p>
<p>JavaScript provides methods to handle time zones effectively:</p>
<ol>
<li><p><strong>Time Zone Offset</strong>: The <code>getTimezoneOffset()</code> method of the <code>Date</code> object returns the difference in minutes between the local time zone and UTC. You can use this offset to adjust dates for specific time zones.</p>
</li>
<li><p><strong>Displaying Time Zones</strong>: To display the time zone information alongside the date, you can use the <code>toLocaleString()</code> method with the appropriate options.</p>
</li>
</ol>
<p>For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> date = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
<span class="hljs-keyword">const</span> formattedDate = date.toLocaleString(<span class="hljs-string">'en-US'</span>, { <span class="hljs-attr">timeZoneName</span>: <span class="hljs-string">'short'</span> });
<span class="hljs-built_in">console</span>.log(formattedDate);
</code></pre>
<p>Output: <code>5/30/2023, 12:00:00 AM PDT</code>.</p>
<h2 id="heading-common-date-formatting-patterns">Common Date Formatting Patterns</h2>
<p>Certain date formatting patterns are commonly used. Here are a few examples:</p>
<ol>
<li><strong>Specific Date Format</strong>: To display a date in a specific format, such as <code>DD/MM/YYYY</code>, you can use <code>Intl.DateTimeFormat</code> with the appropriate options.</li>
</ol>
<p>For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> date = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
<span class="hljs-keyword">const</span> formatter = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Intl</span>.DateTimeFormat(<span class="hljs-string">'en-US'</span>, { <span class="hljs-attr">day</span>: <span class="hljs-string">'2-digit'</span>, <span class="hljs-attr">month</span>: <span class="hljs-string">'2-digit'</span>, <span class="hljs-attr">year</span>: <span class="hljs-string">'numeric'</span> });
<span class="hljs-keyword">const</span> formattedDate = formatter.format(date);
<span class="hljs-built_in">console</span>.log(formattedDate);
</code></pre>
<p>Output: <code>30/05/2023</code>.</p>
<ol start="2">
<li><strong>Time Format</strong>: To format the time portion of a date, you can use the <code>hour</code>, <code>minute</code>, and <code>second</code> options.</li>
</ol>
<p>For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> date = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
<span class="hljs-keyword">const</span> formatter = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Intl</span>.DateTimeFormat(<span class="hljs-string">'en-US'</span>, { <span class="hljs-attr">hour</span>: <span class="hljs-string">'2-digit'</span>, <span class="hljs-attr">minute</span>: <span class="hljs-string">'2-digit'</span>, <span class="hljs-attr">second</span>: <span class="hljs-string">'2-digit'</span> });
<span class="hljs-keyword">const</span> formattedTime = formatter.format(date);
<span class="hljs-built_in">console</span>.log(formattedTime);
</code></pre>
<p>Output: <code>12:00:00 AM</code></p>
<h2 id="heading-how-to-handle-date-input">How to Handle Date Input</h2>
<p>Apart from formatting dates for display, it's essential to handle user input for dates effectively. Here are a few considerations:</p>
<ol>
<li><p><strong>Parsing User Input</strong>: Use the <code>Date.parse()</code> method or external libraries like Moment.js or Luxon to parse user-provided dates into valid <code>Date</code> objects.</p>
</li>
<li><p><strong>Validating User Input</strong>: Implement validation mechanisms to ensure the user's input adheres to the expected date format. Regular expressions or external libraries can help with this.</p>
</li>
</ol>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>Formatting dates in JavaScript is an essential skill when building web applications. By utilizing the built-in date formatting methods, custom formatting techniques, and external libraries, you can ensure dates are presented clearly and accurately.</p>
<p>Experiment with different approaches and stay mindful of time zones for a seamless user experience with date formatting in JavaScript.</p>
<p>For further study on how to format dates, check these resources:</p>
<ul>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/javascript-date-format-how-to-format-a-date-in-js/">JavaScript Date Format – How to Format a Date in JS</a></p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/how-to-format-dates-in-javascript/">How to Format Dates in JavaScript with One Line of Code</a></p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/format-dates-with-ordinal-number-suffixes-javascript/">How to Format Dates with Ordinal Number Suffixes (-st, -nd, -rd, -th) in JavaScript</a></p>
</li>
</ul>
<p>Embark on a journey of learning! <a target="_blank" href="https://joelolawanle.com/contents">Browse 200+ expert articles on web development</a>. Check out <a target="_blank" href="https://joelolawanle.com/posts">my blog</a> for more captivating content from me.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Git Pull Remote Branch – How To Fetch Remote Branches in Git ]]>
                </title>
                <description>
                    <![CDATA[ Git is a popular version control system that's used by millions of developers to manage their codebases. One of the most powerful features of Git is its ability to work with remote repositories. When working on a project with multiple collaborators, ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/git-pull-remote-branch-how-to-fetch-remote-branches-in-git/</link>
                <guid isPermaLink="false">66d45f8038f2dc3808b790d3</guid>
                
                    <category>
                        <![CDATA[ Collaboration ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Git ]]>
                    </category>
                
                    <category>
                        <![CDATA[ version control ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joel Olawanle ]]>
                </dc:creator>
                <pubDate>Thu, 04 May 2023 14:27:39 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/cover-template--12-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Git is a popular version control system that's used by millions of developers to manage their codebases. One of the most powerful features of <a target="_blank" href="https://kinsta.com/knowledgebase/install-git/">Git</a> is its ability to work with remote repositories.</p>
<p>When working on a project with multiple collaborators, you must be able to fetch changes from the remote repository and merge them with your local repository. This article will teach you how to fetch remote branches in Git.</p>
<h2 id="heading-what-is-a-remote-branch">What is a Remote Branch?</h2>
<p>Before diving into how to fetch remote branches, let's define a remote branch.</p>
<p>A remote branch is a branch that exists on a remote repository, such as <a target="_blank" href="https://kinsta.com/knowledgebase/git-vs-github/">GitHub</a>, GitLab, or Bitbucket.</p>
<p>When you clone a repository, Git automatically creates a "<strong>remote</strong>" that points to the original repository. You can then use this remote to fetch changes made by other collaborators on the project.</p>
<h2 id="heading-how-to-fetch-remote-branches-in-git">How to Fetch Remote Branches in Git</h2>
<p>When you clone a repository, you can access all its remote branches. You can verify this using the <code>git branch</code> command alongside the <code>-r</code> option:</p>
<pre><code class="lang-bash">git branch -r
</code></pre>
<p><img src="https://paper-attachments.dropboxusercontent.com/s_4A23CAD3B56D51AD7DA85730E428F7A2E6F6289B6BB197975176BE233B3F0EA9_1682869187912_image.png" alt="s_4A23CAD3B56D51AD7DA85730E428F7A2E6F6289B6BB197975176BE233B3F0EA9_1682869187912_image" width="2074" height="188" loading="lazy"></p>
<p>You can checkout to any of these branches using the <code>git checkout</code> command.</p>
<p>When you are working with a group of people, one contributor creates a new branch remotely. You may need to fetch this remote branch into your project. You can do this with the <code>git fetch</code> command.</p>
<p>The <code>git fetch</code> command goes out to your remote project and pulls down all the data from that remote project that you don’t have yet. After you do this, you should have references to all the branches from that remote, which you can merge in or inspect at any time.</p>
<pre><code class="lang-bash">git fetch
</code></pre>
<p>You can attach the remote repository name, which by default is <code>origin</code>:</p>
<pre><code class="lang-bash">git fetch origin
</code></pre>
<p>It is important to understand that when you use the <code>git fetch</code> command, it only downloads the changes made in the remote repository to your local repository without automatically merging them with your work or modifying what you are currently working on. You will need to merge the changes manually when you are ready.</p>
<p>To access the fetched content, you need to use the <code>git checkout</code> command. This ensures that fetching is a safe way to review commits before integrating them into your local repository.</p>
<p>If you want to fetch remote branches and merge them with your work or modify your current work, you can use the <code>git pull</code> command. To achieve this, use the following command:</p>
<pre><code class="lang-bash">git pull --all
</code></pre>
<p>You can then run the <code>git branch -r</code> to verify if the remote repository has been added.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>Fetching remote branches in Git is a crucial aspect of collaboration in a development environment.</p>
<p>By following the steps outlined in this article, you can fetch changes made by other collaborators on remote branches and merge them with your local repository. This enables you to work on different branches of a Git repository and collaborate effectively with other developers.</p>
<p>Embark on a journey of learning! <a target="_blank" href="https://joelolawanle.com/contents">Browse 200+ expert articles on web development</a>. Check out <a target="_blank" href="https://joelolawanle.com/posts">my blog</a> for more captivating content from me.</p>
<p>Have fun coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Check if a String is Empty or Null in JavaScript – JS Tutorial ]]>
                </title>
                <description>
                    <![CDATA[ In JavaScript, it's important to check whether a string is empty or null before performing any operation. Trying to operate on an empty or null string can lead to errors, bugs, and unexpected results. In this tutorial, we'll explore the different way... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/check-if-string-is-empty-or-null-javascript/</link>
                <guid isPermaLink="false">66d45f6b706b9fb1c166b991</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joel Olawanle ]]>
                </dc:creator>
                <pubDate>Wed, 03 May 2023 17:26:58 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/cover-template--13-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In JavaScript, it's important to check whether a string is empty or null before performing any operation. Trying to operate on an empty or null string can lead to errors, bugs, and unexpected results.</p>
<p>In this tutorial, we'll explore the different ways of checking whether a string is empty or null in JavaScript and some best practices to follow when doing so.</p>
<h2 id="heading-what-are-empty-and-null-strings">What are Empty and Null Strings?</h2>
<p>An empty string is a string that has no characters, while a null string is a string that has no value assigned to it. It's important to differentiate between the two, as they are not the same.</p>
<p>For example, you have a form where a user can input their name. If the user doesn't input anything, the input field's value will be an empty string. However, the value will be null if the input field is not even created.</p>
<h2 id="heading-how-to-check-for-empty-or-null-strings">How to Check for Empty or Null Strings</h2>
<p>JavaScript has several ways to check whether a string is empty or null. Let's explore some of them.</p>
<h3 id="heading-using-the-if-statement-and-typeof-operator">Using the if Statement and typeof Operator</h3>
<p>One way to check for an empty or null string is to use the <code>if</code> statement and the <code>typeof</code> operator. Here's an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> str = <span class="hljs-string">""</span>;

<span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> str === <span class="hljs-string">"string"</span> &amp;&amp; str.length === <span class="hljs-number">0</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The string is empty"</span>);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (str === <span class="hljs-literal">null</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The string is null"</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The string is not empty or null"</span>);
}
</code></pre>
<p>In this example, we're checking whether the <code>str</code> variable is a string and whether its length is zero. If it is, then we know that it's an empty string. If the <code>str</code> variable is <code>null</code>, then we know that it's a null string. Otherwise, we know that the string is not empty or null.</p>
<h3 id="heading-using-the-length-property">Using the length Property</h3>
<p>Another way to check for an empty string is to use the <code>length</code> property. Here's an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> str = <span class="hljs-string">""</span>;

<span class="hljs-keyword">if</span> (str.length === <span class="hljs-number">0</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The string is empty"</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The string is not empty"</span>);
}
</code></pre>
<p>In this example, we're checking whether the <code>str</code> variable's length is zero. If it is, then we know that it's an empty string. Otherwise, we know that the string is not empty.</p>
<h3 id="heading-using-the-trim-method">Using the trim Method</h3>
<p>Sometimes, a string might contain whitespace characters that make it appear non-empty even when it is. In such cases, we can use the <code>trim</code> method to remove any leading or trailing whitespace characters before checking for emptiness. Here's an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> str = <span class="hljs-string">"   "</span>;

<span class="hljs-keyword">if</span> (str.trim().length === <span class="hljs-number">0</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The string is empty"</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The string is not empty"</span>);
}
</code></pre>
<p>In this example, we're first using the <code>trim</code> method to remove any leading or trailing whitespace characters from the <code>str</code> variable, then checking whether the resulting string has zero length. If it does, then we know that the string is empty. Otherwise, we know that the string is not empty.</p>
<h2 id="heading-best-practices-for-checking-empty-or-null-strings">Best Practices for Checking Empty or Null Strings</h2>
<p>Here are some best practices to follow when checking for empty or null strings in JavaScript:</p>
<ul>
<li><p>Always use triple equals (<code>===</code>) when comparing a string to <code>null</code>. This ensures that the types are checked, and you don't accidentally compare a string to the number <code>0</code> or <code>false</code>.</p>
</li>
<li><p>Use strict equality (<code>===</code>) when checking for an empty string. This ensures you don't compare an empty string to a string containing only whitespace characters.</p>
</li>
<li><p>Use the <code>trim</code> method to remove leading and trailing whitespace characters before checking for an empty string. This ensures that strings with only whitespace characters are also considered empty.</p>
</li>
<li><p>Use regular expressions for more complex checks, such as checking for a string that only contains digits or checking for a string that matches a certain pattern.</p>
</li>
</ul>
<p>For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> str = <span class="hljs-string">"12345"</span>;
<span class="hljs-keyword">let</span> digitRegExp = <span class="hljs-regexp">/^\d+$/</span>;

<span class="hljs-keyword">if</span> (digitRegExp.test(str)) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The string contains only digits"</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The string does not contain only digits"</span>);
}
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we've learned how to check whether a string is empty or null in JavaScript. We've explored different methods for doing so, such as using the <code>if</code> statement and <code>typeof</code> operator, the <code>length</code> property, and the <code>trim</code> method.</p>
<p>If you would like to learn more about JavaScript and web development, <a target="_blank" href="https://joelolawanle.com/contents">browse 200+ expert articles on web development</a> written by me, and also check out <a target="_blank" href="https://joelolawanle.com/posts">my blog</a> for more captivating content.</p>
<p>Have fun coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Insert into a JavaScript Array at a Specific Index – JS Push ]]>
                </title>
                <description>
                    <![CDATA[ JavaScript arrays are an important part of the language. They allow you to store and manipulate collections of data. Sometimes, you may need to insert a new element into an array at a specific index. To accomplish this task, you can use the push() me... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/insert-into-javascript-array-at-specific-index/</link>
                <guid isPermaLink="false">66d45fc5d1ffc3d3eb89de08</guid>
                
                    <category>
                        <![CDATA[ arrays ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joel Olawanle ]]>
                </dc:creator>
                <pubDate>Tue, 25 Apr 2023 18:14:43 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/cover-template--11-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JavaScript arrays are an important part of the language. They allow you to store and manipulate collections of data.</p>
<p>Sometimes, you may need to insert a new element into an array at a specific index. To accomplish this task, you can use the <code>push()</code> method or the <code>splice()</code> method.</p>
<p>In this article, you will learn how to use both techniques in detail.</p>
<h2 id="heading-how-javascript-arrays-work">How JavaScript Arrays Work</h2>
<p>Before we dive into the insertion methods, let's briefly review arrays in JavaScript.</p>
<p>An array is a collection of data values of any data type. You can create arrays using either the array constructor or the literal notation.</p>
<p>Here's an example of an array created using the array constructor:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> arrayConstructor = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Array</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>);
<span class="hljs-built_in">console</span>.log(arrayConstructor); <span class="hljs-comment">// Output: [1, 2, 3]</span>
</code></pre>
<p>And here's an example of an array created using literal notation:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> literalArray = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-built_in">console</span>.log(literalArray); <span class="hljs-comment">// Output: [1, 2, 3]</span>
</code></pre>
<p>In both cases, you have an array with three elements: <code>1</code>, <code>2</code>, and <code>3</code>.</p>
<h2 id="heading-how-to-insert-into-a-javascript-array-at-a-specific-index-with-the-push-method">How to Insert into a JavaScript Array at a Specific Index With the <code>push()</code> Method</h2>
<p>The <a target="_blank" href="https://www.freecodecamp.org/news/how-to-insert-an-element-into-an-array-in-javascript/"><code>push()</code></a> <a target="_blank" href="https://www.freecodecamp.org/news/how-to-insert-an-element-into-an-array-in-javascript/">method in JavaScript arrays</a> is used to add one or more elements to the end of an array.</p>
<p>Let's look at the syntax of the <code>push()</code> method:</p>
<pre><code class="lang-js">array.push(element1, element2, ..., elementN);
</code></pre>
<p>Here, <code>array</code> is the array that you want to add elements to, and <code>element1</code>, <code>element2</code>, and so on, are the elements you want to add to the end of the array.</p>
<p>For example, let's say you have an array of fruit, and you want to add an element to the end of it:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fruits = [<span class="hljs-string">'apple'</span>, <span class="hljs-string">'banana'</span>, <span class="hljs-string">'cherry'</span>];
fruits.push(<span class="hljs-string">'date'</span>);
<span class="hljs-built_in">console</span>.log(fruits); <span class="hljs-comment">// Output: ['apple', 'banana', 'cherry', 'date']</span>
</code></pre>
<p>In this code, <code>'date'</code> is added to the end of the <code>fruits</code> array using the <code>push()</code> method.</p>
<p>There may be times when you need to insert an element at a specific index in an array. In such a scenario, you can use the <code>push()</code> method in combination with array slicing.</p>
<p>Here are the steps to insert an element at a specific index in an array:</p>
<ol>
<li><p>Create a new empty array.</p>
</li>
<li><p>Copy the elements before the specific index from the original array to the new array.</p>
</li>
<li><p>Add the new element to the new array.</p>
</li>
<li><p>Copy the elements after the specific index from the original array to the new array.</p>
</li>
</ol>
<p>Let's illustrate these steps with an example. Suppose you have an array of numbers:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
</code></pre>
<p>And you want to insert the number <code>3</code> at index <code>2</code> (remember that JavaScript uses zero-based indexing). Here's how you can accomplish this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> index = <span class="hljs-number">2</span>;
<span class="hljs-keyword">const</span> newNumbers = [
    ...numbers.slice(<span class="hljs-number">0</span>, index),
    <span class="hljs-number">3</span>,
    ...numbers.slice(index)
];
<span class="hljs-built_in">console</span>.log(newNumbers); <span class="hljs-comment">// Output: [1, 2, 3, 4, 5]</span>
</code></pre>
<p>In this example, a new array <code>newNumbers</code> is created by copying the elements before index <code>2</code> using the <code>slice()</code> method. That's followed by the new element <code>3</code>, and finally you copy the remaining elements after index <code>2</code> using the <code>slice()</code> method again. The result is the new array <code>[1, 2, 3, 4, 5]</code>.</p>
<p>The spread operator (<code>...</code>) in the example above is used to concatenate the arrays.</p>
<p>But this is not a best approach because you end up using another method (<code>slice</code>), making the code difficult for a beginner to understand. Let’s explore how to use the splice method which is more straightfoward.</p>
<h2 id="heading-how-to-use-the-splice-method-to-insert-into-a-javascript-array-at-a-specific-index">How to Use the <code>splice()</code> Method to Insert into a JavaScript Array at a Specific Index</h2>
<p>The <code>splice()</code> method in JavaScript arrays is used to add or remove elements from an array. You can use the <code>splice()</code> method to insert elements at a specific index in an array.</p>
<p>Here's the syntax of <a target="_blank" href="https://joelolawanle.com/posts/slice-vs-splice-javascript-understanding-differences-use">the <code>splice()</code> method</a>:</p>
<pre><code class="lang-js">array.splice(start, deleteCount, item1, item2, ..., itemN);
</code></pre>
<ul>
<li><p><code>array</code> is the array that you want to modify.</p>
</li>
<li><p><code>start</code> is the index where you want to start modifying the array.</p>
</li>
<li><p><code>deleteCount</code> is the number of elements you want to remove from the array, starting at the <code>start</code> index.</p>
</li>
<li><p><code>item1</code>, <code>item2</code>, and so on are the elements you want to add to the array at the <code>start</code> index.</p>
</li>
</ul>
<p>For example, let's say you have an array of numbers:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
</code></pre>
<p>And you want to insert the number <code>3</code> at index <code>2</code>. Here's how you can accomplish this using the <code>splice()</code> method:</p>
<pre><code class="lang-js">numbers.splice(<span class="hljs-number">2</span>, <span class="hljs-number">0</span>, <span class="hljs-number">3</span>);
<span class="hljs-built_in">console</span>.log(numbers); <span class="hljs-comment">// Output: [1, 2, 3, 4, 5]</span>
</code></pre>
<p>In this code, the <code>splice()</code> method is called on the <code>numbers</code> array, starting at index <code>2</code>, with a <code>deleteCount</code> of <code>0</code>. You then add the new element <code>3</code> to the array at the <code>start</code> index. The result is the modified array <code>[1, 2, 3, 4, 5]</code>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you have learned the two major techniques for inserting elements into a JavaScript array at a specific index.</p>
<p>The <code>splice()</code> method should be your preferred option as it has a better and more straightforward syntax. Knowing these techniques will allow you to manipulate JavaScript arrays more effectively.</p>
<p>Embark on a journey of learning! <a target="_blank" href="https://joelolawanle.com/contents">Browse 200+ expert articles on web development</a>. Check out <a target="_blank" href="https://joelolawanle.com/posts">my blog</a> for more captivating content from me.</p>
<p>Have fun coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Get the Current URL with JavaScript – JS Location Tutorial ]]>
                </title>
                <description>
                    <![CDATA[ If you're a web developer, you'll work with JavaScript when building dynamic and interactive web applications. One common task that you'll need to perform is getting the current URL of a web page. In this article, you will learn how to get the curren... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-get-the-current-url-with-javascript/</link>
                <guid isPermaLink="false">66d45fa2868774922c884ff0</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joel Olawanle ]]>
                </dc:creator>
                <pubDate>Tue, 25 Apr 2023 00:34:45 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/cover-template--10-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you're a web developer, you'll work with JavaScript when building dynamic and interactive web applications. One common task that you'll need to perform is getting the current URL of a web page.</p>
<p>In this article, you will learn how to get the current URL using JavaScript's Location object. I'll show you some examples alongside some best practices.</p>
<h2 id="heading-how-to-use-the-location-object">How to Use the Location Object</h2>
<p>The Location object is a built-in JavaScript object that provides information about the current URL of a web page. It contains various properties allowing you to access and modify different parts of a URL.</p>
<p>To access the Location object, you can use the <code>window.location</code> property. This returns the Location object for the current web page. This object contains many data, such as the URL, pathname, origin, host, search data, and more.</p>
<p>For example:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"ancestorOrigins"</span>: {
    <span class="hljs-attr">"0"</span>: <span class="hljs-string">"https://codepen.io"</span>
  },
  <span class="hljs-attr">"href"</span>: <span class="hljs-string">"https://cdpn.io/cpe/boomboom/index.html?editors=0012&amp;key=index.html-f1981af8-7dc2-f8b6-669a-8980d4a8d02a"</span>,
  <span class="hljs-attr">"origin"</span>: <span class="hljs-string">"https://cdpn.io"</span>,
  <span class="hljs-attr">"protocol"</span>: <span class="hljs-string">"https:"</span>,
  <span class="hljs-attr">"host"</span>: <span class="hljs-string">"cdpn.io"</span>,
  <span class="hljs-attr">"hostname"</span>: <span class="hljs-string">"cdpn.io"</span>,
  <span class="hljs-attr">"port"</span>: <span class="hljs-string">""</span>,
  <span class="hljs-attr">"pathname"</span>: <span class="hljs-string">"/cpe/boomboom/index.html"</span>,
  <span class="hljs-attr">"search"</span>: <span class="hljs-string">"?editors=0012&amp;key=index.html-f1981af8-7dc2-f8b6-669a-8980d4a8d02a"</span>,
  <span class="hljs-attr">"hash"</span>: <span class="hljs-string">""</span>
}
</code></pre>
<h2 id="heading-how-to-access-the-current-url-with-javascript">How to Access the Current URL With JavaScript</h2>
<p>One common use case for the Location object is to get the current URL of a web page. You can do this by accessing the <code>href</code> property of the Location object.</p>
<p>The <code>href</code> property contains the complete URL of the current web page:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> currentUrl = <span class="hljs-built_in">window</span>.location.href;
<span class="hljs-built_in">console</span>.log(currentUrl);
</code></pre>
<p>This will log the current URL of the web page to the console.</p>
<h2 id="heading-how-to-parse-the-current-url-with-javascript">How to Parse the Current URL With JavaScript</h2>
<p>In addition to getting the current URL, you may need to parse it to extract specific parts. For example, you may want to extract the protocol, host, or path from the URL.</p>
<p>To parse the current URL, you can use the various properties of the Location object. For example, you can use the <code>protocol</code> property to get the protocol of the current URL:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> protocol = <span class="hljs-built_in">window</span>.location.protocol;
<span class="hljs-built_in">console</span>.log(protocol);
</code></pre>
<p>This will log the protocol of the current URL (for example, "http:" or "https:") to the console.</p>
<p>Other properties of the Location object that you can use to extract parts of the current URL include <code>host</code>, <code>hostname</code>, <code>port</code>, <code>pathname</code>, <code>search</code>, and <code>hash</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> host = <span class="hljs-built_in">window</span>.location.host;
<span class="hljs-keyword">const</span> pathname = <span class="hljs-built_in">window</span>.location.pathname;
<span class="hljs-keyword">const</span> search = <span class="hljs-built_in">window</span>.location.search;
<span class="hljs-keyword">const</span> hash = <span class="hljs-built_in">window</span>.location.hash;
</code></pre>
<p>Using these properties, you can extract various parts of the current URL.</p>
<h2 id="heading-how-to-update-the-current-url-with-javascript">How to Update the Current URL With JavaScript</h2>
<p>In addition to getting and parsing the current URL, you may need to update it. For example, you may need to redirect the user to a different URL or modify the current URL dynamically.</p>
<p>To update the current URL, you can use the various methods of the Location object. For example, you can use the <code>replace()</code> method to replace the current URL with a new URL:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> newUrl = <span class="hljs-string">"https://example.com/new-page.html"</span>;
<span class="hljs-built_in">window</span>.location.replace(newUrl);
</code></pre>
<p>This will replace the current URL with the new one, redirecting the user to the new page.</p>
<h2 id="heading-best-practices-when-working-with-the-location-object">Best Practices When Working With the Location Object</h2>
<p>When working with the Location object, there are some best practices that you should follow to avoid potential pitfalls. For example, you should always check if the Location object is available before using it.</p>
<pre><code class="lang-js"><span class="hljs-keyword">if</span> (<span class="hljs-built_in">window</span>.location) {
  <span class="hljs-comment">// Access or modify the Location object</span>
}
</code></pre>
<p>You should also be careful when modifying the current URL, as it can affect the user's browsing experience. For example, you should avoid modifying the URL's protocol, host, or port unless absolutely necessary.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you have learned how to get the current URL of a web page using JavaScript's Location object. By understanding how to work with the Location object, you can build more dynamic and interactive web applications that provide a better user experience.</p>
<p>Thank you for reading, and I hope you have found this article informative and helpful. You can read this article on <a target="_blank" href="https://www.freecodecamp.org/news/javascript-refresh-page-how-to-reload-a-page-in-js/">how to refresh a page with JavaScript</a> for more information on working with URLs in JavaScript.</p>
<p>If you would like to learn more about JavaScript and web development, <a target="_blank" href="https://joelolawanle.com/contents">Browse 200+ expert articles on web development</a> written by me, and also check out <a target="_blank" href="https://joelolawanle.com/posts">my blog</a> for more captivating content.</p>
<p>Have fun coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What Does $ Mean in JavaScript? Dollar Sign Operator in JS ]]>
                </title>
                <description>
                    <![CDATA[ As you dive into JavaScript code, you may come across the use of a dollar sign ($) in various contexts. In this article, we will explore what the dollar sign means in JavaScript, commonly known as the "dollar sign operator," and how it is used in Jav... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-does-the-dollar-sign-mean-in-javascript/</link>
                <guid isPermaLink="false">66d46003d14641365a050905</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joel Olawanle ]]>
                </dc:creator>
                <pubDate>Fri, 14 Apr 2023 15:10:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/cover-template--9-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>As you dive into JavaScript code, you may come across the use of a dollar sign ($) in various contexts.</p>
<p>In this article, we will explore what the dollar sign means in JavaScript, commonly known as the "dollar sign operator," and how it is used in JavaScript programming.</p>
<h2 id="heading-understanding-the-dollar-sign-operator">Understanding the Dollar Sign Operator</h2>
<p>In JavaScript, the dollar sign is not a built-in operator or syntax. It does not have any predefined meaning or functionality in the JavaScript language itself.</p>
<p>Instead, it is often used as a convention in libraries, frameworks, and other JavaScript code written by developers for various purposes. Let's take a closer look at some common use cases of the dollar sign in JavaScript.</p>
<h3 id="heading-1-using-the-in-the-jquery-library">1. Using the <code>$</code> in the jQuery Library</h3>
<p>One of the most well-known uses of the dollar sign in JavaScript is with the jQuery library.</p>
<p>In jQuery, the dollar sign is used as a shorthand alias for the <code>jQuery</code> object. jQuery is a powerful JavaScript library that simplifies DOM manipulation and provides a wide range of utility functions for web development.</p>
<p>For example, you may see code like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Using the $ alias to select elements with jQuery</span>
$(<span class="hljs-string">'#myElement'</span>).addClass(<span class="hljs-string">'active'</span>);
</code></pre>
<p>In this example, <code>$</code> is used as a shorthand for the <code>jQuery</code> object, which allows you to select an element with the ID <code>myElement</code> and add the CSS class <code>active</code> to it.</p>
<p>But it's important to note that the use of the dollar sign as an alias for <code>jQuery</code> is not mandatory, and you can also use the <code>jQuery</code> keyword instead.</p>
<h3 id="heading-2-using-the-in-other-javascript-libraries-and-frameworks">2. Using the <code>$</code> in Other JavaScript Libraries and Frameworks</h3>
<p>Apart from jQuery, some other JavaScript libraries and frameworks may also use the dollar sign as a convention for their own specific purposes.</p>
<p>For example, in AngularJS, you may see code like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Using the $scope object in AngularJS</span>
$scope.name = <span class="hljs-string">'John'</span>;
</code></pre>
<p>In this example, <code>$scope</code> is a predefined object in AngularJS that is used to bind data between the view and the controller.</p>
<p>It's important to note that the use of the dollar sign in these libraries and frameworks is specific to their respective syntax and APIs, and may not have the same meaning or functionality in other contexts.</p>
<h3 id="heading-3-using-the-in-template-literals">3. Using the <code>$</code> in Template Literals</h3>
<p>In addition to these use cases, the dollar sign is also used in template literals. This was introduced in ECMAScript 6 (ES6) for more convenient string interpolation and multiline strings in JavaScript.</p>
<p>Template literals are enclosed in backticks (<code>` </code>) instead of single or double quotes. They allow you to embed expressions directly within the string using placeholders, denoted by <code>${expression}</code>. The dollar sign followed by curly braces <code>${}</code> is used to evaluate and embed expressions dynamically in template literals.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> name = <span class="hljs-string">'John Doe'</span>;
<span class="hljs-keyword">const</span> age = <span class="hljs-number">20</span>;

<span class="hljs-comment">// Using template literals for string interpolation</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`My name is <span class="hljs-subst">${name}</span> and I'm <span class="hljs-subst">${age}</span> years old.`</span>);
</code></pre>
<p>In this example, the expressions <code>${name}</code> and <code>${age}</code> are evaluated and replaced with their corresponding values in the resulting string. This allows for easy and readable string concatenation with variables.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>In JavaScript, the dollar sign is not a predefined operator or syntax, but it is commonly used as a convention in libraries, frameworks, and custom code for various purposes.</p>
<p>It is used as a shorthand alias for objects or functions in some libraries and frameworks, and it is also used in template literals for string interpolation and multiline strings.</p>
<p>It's important to understand that the use of the dollar sign may have different meanings or functionalities in different contexts, and it's always recommended to follow coding standards and best practices for writing clean, maintainable, and readable JavaScript code.</p>
<p>Have fun coding!</p>
<p>Embark on a journey of learning! <a target="_blank" href="https://joelolawanle.com/contents">Browse 200+ expert articles on web development</a>. Check out <a target="_blank" href="https://joelolawanle.com/posts">my blog</a> for more captivating content from me!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Refresh Page – How to Reload a Page in JS ]]>
                </title>
                <description>
                    <![CDATA[ JavaScript is a versatile programming language that allows developers to create dynamic and interactive web applications. One common task in web development is to refresh or reload a web page, either to update its content or to trigger certain action... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-refresh-page-how-to-reload-a-page-in-js/</link>
                <guid isPermaLink="false">66d45fe151f567b42d9f848b</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joel Olawanle ]]>
                </dc:creator>
                <pubDate>Fri, 14 Apr 2023 15:01:42 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/cover-template--8-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JavaScript is a versatile programming language that allows developers to create dynamic and interactive web applications. One common task in web development is to refresh or reload a web page, either to update its content or to trigger certain actions.</p>
<p>In this article, we will explore different ways to refresh a page in JavaScript and understand the pros and cons of each approach.</p>
<h2 id="heading-why-refresh-a-page-in-javascript">Why Refresh a Page in JavaScript?</h2>
<p>Refreshing a web page can be useful in various scenarios. For example:</p>
<ol>
<li><p><strong>Content Update:</strong> If the content on a web page is dynamic and changes frequently, you may need to refresh the page to display the latest data or information. This is commonly seen in news websites, stock market trackers, weather apps, and so on.</p>
</li>
<li><p><strong>Form Submission:</strong> After submitting a form on a web page, you may want to refresh the page to show a success message or reset the form for a new submission.</p>
</li>
<li><p><strong>State Reset:</strong> In some cases, you may want to reset the state of a web page or clear certain data to start fresh. Refreshing the page can help achieve this.</p>
</li>
</ol>
<p>Now, let's explore different ways to refresh a page in JavaScript.</p>
<h2 id="heading-method-1-how-to-refresh-the-page-using-locationreload">Method 1: How to Refresh the Page Using <code>location.reload()</code></h2>
<p>The simplest way to refresh a page in JavaScript is to use the <code>location.reload()</code> method. This method reloads the current web page from the server, discarding the current content and loading the latest content.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Refresh the page</span>
location.reload();
</code></pre>
<h3 id="heading-pros-of-using-locationreload">Pros of Using location.reload()</h3>
<ul>
<li><p>It's straightforward and easy to use.</p>
</li>
<li><p>It reloads the entire page from the server, ensuring that you get the latest content.</p>
</li>
</ul>
<h3 id="heading-cons-of-using-locationreload">Cons of Using location.reload()</h3>
<ul>
<li><p>It discards the current content of the page, which can result in loss of user input or data.</p>
</li>
<li><p>It may cause a flickering effect as the page reloads, which can impact user experience.</p>
</li>
</ul>
<h2 id="heading-method-2-how-to-refresh-the-page-using-locationreplace">Method 2: How to Refresh the Page Using <code>location.replace()</code></h2>
<p>Another way to refresh a page in JavaScript is to use the <code>location.replace()</code> method. This method replaces the current URL of the web page with a new URL, effectively reloading the page with the new content.</p>
<p>When you try this in your console, you will notice it displays your current URL:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(location.href)
</code></pre>
<p>This means, when you use the <code>location.replace()</code> method to replace the current URL of the web page with a new URL (same URL), your page will refresh.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Refresh the page by replacing the URL with itself</span>
location.replace(location.href);
</code></pre>
<h3 id="heading-pros-of-using-locationreplace">Pros of Using location.replace()</h3>
<ul>
<li><p>It's a quick way to reload the page with new content.</p>
</li>
<li><p>It preserves the current content of the page and replaces only the URL, avoiding loss of user input or data.</p>
</li>
</ul>
<h3 id="heading-cons-of-using-locationreplace">Cons of Using location.replace()</h3>
<ul>
<li><p>It replaces the entire URL of the page, which may result in the loss of the current browsing history.</p>
</li>
<li><p>It may not work in some scenarios, such as when the web page was opened in a new window or tab.</p>
</li>
</ul>
<h2 id="heading-method-3-how-to-refresh-the-page-using-locationreloadtrue">Method 3: How to Refresh the Page Using <code>location.reload(true)</code></h2>
<p>The <code>location.reload()</code> method also accepts a boolean parameter <code>forceGet</code> which, when set to <code>true</code>, forces the web page to reload from the server, bypassing the cache.</p>
<p>This can be useful when you want to ensure that you get the latest content from the server, even if the page is cached.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Refresh the page and bypass the cache</span>
location.reload(<span class="hljs-literal">true</span>);
</code></pre>
<h3 id="heading-pros-of-using-locationreloadtrue">Pros of Using location.reload(true)</h3>
<ul>
<li>It ensures that you get the latest content from the server, even if the page is cached.</li>
</ul>
<h3 id="heading-cons-of-using-locationreloadtrue">Cons of Using location.reload(true)</h3>
<ul>
<li><p>It discards the current content of the page, which can result in loss of user input or data.</p>
</li>
<li><p>It may cause a flickering effect as the page reloads, which can impact user experience.</p>
</li>
</ul>
<h2 id="heading-method-4-how-to-refresh-the-page-using-locationhref">Method 4: How to Refresh the Page Using <code>location.href</code></h2>
<p>Another way to refresh a page in JavaScript is to use the <code>location.href</code> property to set the URL of the web page to itself. This effectively reloads the page with the new URL, triggering a page refresh.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Refresh the page by setting the URL to itself</span>
location.href = location.href;
</code></pre>
<h3 id="heading-pros-of-using-locationhref">Pros of Using location.href</h3>
<ul>
<li><p>It's a simple and effective way to refresh the page.</p>
</li>
<li><p>It preserves the current content of the page and only updates the URL, avoiding loss of user input or data.</p>
</li>
</ul>
<h3 id="heading-cons-of-using-locationhref">Cons of Using location.href</h3>
<ul>
<li><p>It replaces the entire URL of the page, which may result in the loss of the current browsing history.</p>
</li>
<li><p>It may not work in some scenarios, such as when the web page was opened in a new window or tab.</p>
</li>
</ul>
<h2 id="heading-method-5-how-to-refresh-the-page-using-locationreload-with-a-delay">Method 5: How to Refresh the Page Using <code>location.reload()</code> with a Delay</h2>
<p>If you want to add a delay before refreshing the page, you can use the <code>setTimeout()</code> function in combination with the <code>location.reload()</code> method.</p>
<p>This allows you to specify a time interval in milliseconds before the page is reloaded, giving you control over the timing of the refresh.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Refresh the page after a delay of 3 seconds</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    location.reload();
}, <span class="hljs-number">3000</span>); <span class="hljs-comment">// 3000 milliseconds = 3 seconds</span>
</code></pre>
<h3 id="heading-pros-of-using-locationreload-with-a-delay">Pros of Using location.reload() with a Delay</h3>
<ul>
<li><p>It allows you to control the timing of the page refresh by adding a delay.</p>
</li>
<li><p>It provides flexibility in scenarios where you want to refresh the page after a certain event or action.</p>
</li>
</ul>
<h3 id="heading-cons-of-using-locationreload-with-a-delay">Cons of Using location.reload() with a Delay</h3>
<ul>
<li><p>It may cause a delay in the page refresh, which can impact user experience.</p>
</li>
<li><p>It may not work as expected in scenarios with unstable or slow network connections.</p>
</li>
</ul>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>In this article, you have learned the different ways to refresh a page in JavaScript. Each method has its pros and cons, which should make it easier for you to choose the best method for your web development project.</p>
<p>When using any of these methods to refresh a page, it's important to consider the impact on user experience, data loss, and browsing history.</p>
<p>I hope this article helps you understand how to reload a web page in JavaScript and choose the appropriate method for your specific use case.</p>
<p>Happy coding!</p>
<p>Embark on a journey of learning! <a target="_blank" href="https://joelolawanle.com/contents">Browse 200+ expert articles on web development</a>. Check out <a target="_blank" href="https://joelolawanle.com/posts">my blog</a> for more captivating content from me!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Call vs Put vs Post – HTTP Request Methods Explained ]]>
                </title>
                <description>
                    <![CDATA[ The HTTP (Hypertext Transfer Protocol) is the foundation of communication between clients (such as web browsers) and servers (such as web servers) on the World Wide Web. One crucial aspect of HTTP is the request method, which indicates the type of op... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/call-vs-put-vs-post-http-request-methods-explained/</link>
                <guid isPermaLink="false">66d45f67ffe6b1f641b5f9f9</guid>
                
                    <category>
                        <![CDATA[ http ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joel Olawanle ]]>
                </dc:creator>
                <pubDate>Thu, 13 Apr 2023 14:59:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/cover-template--7-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The HTTP (Hypertext Transfer Protocol) is the foundation of communication between clients (such as web browsers) and servers (such as web servers) on the World Wide Web.</p>
<p>One crucial aspect of HTTP is the request method, which indicates the type of operation the client wants to perform on a resource.</p>
<p>This article will explore three common HTTP request methods — Call, Put, and Post — and their applications in JavaScript web development.</p>
<h2 id="heading-how-http-works">How HTTP Works</h2>
<p>HTTP (Hypertext Transfer Protocol) is the foundation of communication on the World Wide Web. It is a protocol that governs how data is transmitted and received between clients (web browsers) and servers (web servers) over the internet.</p>
<p>When you enter a URL (Uniform Resource Locator) in your web browser and hit enter, your browser sends an HTTP request to the server hosting the website associated with that URL. The server then processes the request and sends back an HTTP response containing the requested data, such as a webpage, an image, or other resources.</p>
<p>HTTP uses a client-server model, where the client (typically a web browser) sends requests to the server, and the server responds with the requested data. One important aspect of HTTP is the concept of request methods, also known as HTTP verbs or methods.</p>
<p>Request methods are used to indicate the type of operation the client wants to perform on a resource on the server. HTTP defines several request methods, including Call, Put, Post, Delete, and more, each with its specific purpose and behavior.</p>
<p>These request methods are used to communicate the client's intention to the server and determine how the server should handle the request. Let's focus on three common request methods: Call, Put, and Post.</p>
<h2 id="heading-how-to-use-the-call-method">How to Use the Call Method</h2>
<p>In the context of an HTTP Request, the call method is called the <a target="_blank" href="https://www.freecodecamp.org/news/javascript-get-request-tutorial/">GET method</a>. It is used to retrieve data from a resource on the server. When you make a Call request, you ask the server to provide you with the data of a particular resource.</p>
<p>The Call method is considered "safe" and "idempotent." This means it should not have any side effects on the server and can be repeated multiple times without changing the outcome. In other words, making the same Call request multiple times should not result in any changes on the server.</p>
<p>In JavaScript web development, you often use the Call method to fetch data from APIs or retrieve resources from the server.</p>
<p>For example, you may use the Fetch API in JavaScript to request a Call to an API and retrieve data in JSON format:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">"https://jsonplaceholder.typicode.com/posts?_limit=5"</span>)
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response.json())
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(data))
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(error));
</code></pre>
<p>In this example, the Call request is made to the URL ‘https://jsonplaceholder.typicode.com/posts’ to fetch data from the server (<code>?_limit=5</code> is added to reduce the data fetched from 100 to 5). The response from the server is then parsed as JSON, and the retrieved data is logged to the console. You can now make use of the data within your application.</p>
<h2 id="heading-how-to-use-the-put-method">How to Use the Put Method</h2>
<p>The Put method is used to update data on the server or create a new resource if it does not already exist.</p>
<p>When you make a Put request, you ask the server to update the data of a particular resource or create a new resource with the provided data.</p>
<p>The Put method is considered "idempotent" but not "safe." This means that making the same Put request multiple times will not result in different outcomes but may have side effects on the server.</p>
<p>In JavaScript, you can use the Put method to send data to the server to update resources. For example, you may use the Fetch API to make a Put request with updated data to update a user's profile information on the server:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> dataToUpdate = {
  <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
  <span class="hljs-attr">title</span>: <span class="hljs-string">"Hello freeCodeCamp"</span>,
  <span class="hljs-attr">body</span>: <span class="hljs-string">"Welcome to freeCodeCamp"</span>,
  <span class="hljs-attr">userId</span>: <span class="hljs-number">1</span>
};

fetch(<span class="hljs-string">"https://jsonplaceholder.typicode.com/posts/1"</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">"PUT"</span>,
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">"Content-type"</span>: <span class="hljs-string">"application/json; charset=UTF-8"</span>
  },
  <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(dataToUpdate)
})
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response.json())
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(data))
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(error));
</code></pre>
<p>In this example, the Put request is made to the URL ‘https://jsonplaceholder.typicode.com/posts/1’ with the updated data in the request body. The server will then update the resource's data with ID 1 based on the provided data in the request body.</p>
<p>The response from the server, containing the updated data, is then parsed as JSON and logged to the console.</p>
<pre><code class="lang-js">{
  <span class="hljs-string">"id"</span>: <span class="hljs-number">1</span>,
  <span class="hljs-string">"title"</span>: <span class="hljs-string">"Hello freeCodeCamp"</span>,
  <span class="hljs-string">"body"</span>: <span class="hljs-string">"Welcome to freeCodeCamp"</span>,
  <span class="hljs-string">"userId"</span>: <span class="hljs-number">1</span>
}
</code></pre>
<p><strong>Note:</strong> The PUT method is used to update data. The post of id 1 was updated.</p>
<h2 id="heading-how-to-use-the-post-method">How to Use the Post Method</h2>
<p>The <a target="_blank" href="https://www.freecodecamp.org/news/javascript-post-request-how-to-send-an-http-post-request-in-js/">POST method</a> is used to submit data to the server to create a new resource.</p>
<p>When you make a Post request, you ask the server to create a new resource with the data provided in the request body. The Post method is not considered "idempotent" or "safe," as making the same Post request multiple times may create multiple resources with different outcomes.</p>
<p>In JavaScript, you can use the Post method to send data to the server to create new resources. For example, you may use the Fetch API to make a Post request with new data to create a new user account on the server:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> newData = {
  <span class="hljs-attr">title</span>: <span class="hljs-string">"Hello freeCodeCamp"</span>,
  <span class="hljs-attr">body</span>: <span class="hljs-string">"Welcome to freeCodeCamp"</span>,
  <span class="hljs-attr">userId</span>: <span class="hljs-number">1</span>
};

fetch(<span class="hljs-string">"https://jsonplaceholder.typicode.com/posts"</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">"POST"</span>,
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">"Content-type"</span>: <span class="hljs-string">"application/json; charset=UTF-8"</span>
  },
  <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(newData)
})
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response.json())
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(data))
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(error));
</code></pre>
<p>In this example, the Post request is made to the URL ‘https://jsonplaceholder.typicode.com/posts’ with the new data in the request body. The server will then create a new resource with the provided data, and the response from the server, containing the newly created resource data, is parsed as JSON and logged to the console.</p>
<pre><code class="lang-js">{
  <span class="hljs-string">"title"</span>: <span class="hljs-string">"Hello freeCodeCamp"</span>,
  <span class="hljs-string">"body"</span>: <span class="hljs-string">"Welcome to freeCodeCamp"</span>,
  <span class="hljs-string">"userId"</span>: <span class="hljs-number">1</span>,
  <span class="hljs-string">"id"</span>: <span class="hljs-number">101</span>
}
</code></pre>
<p><strong>Note:</strong> A new <code>id</code> of 101 is created because this is new data that does not exist before, so a unique ID is assigned to it.</p>
<h2 id="heading-best-practices-and-considerations">Best Practices and Considerations</h2>
<ol>
<li><p><strong>Use appropriate request methods:</strong> It's important to choose the appropriate one based on the intended operation on the server-side resource. Use Call for custom actions or functions, Put for updating existing resources, and Post for creating new ones.</p>
</li>
<li><p><strong>Follow RESTful principles:</strong> If you're building a RESTful API, it's important to follow the principles of Representational State Transfer (REST), which includes using standard HTTP request methods for CRUD operations. Use Get for retrieving resource data, Put for updating, Post for creating new resources, and Delete for deleting resources.</p>
</li>
<li><p><strong>Consider idempotency and safety:</strong> Put requests are idempotent, meaning making the same request multiple times will have the same outcome as making it once. Post requests are not idempotent, and making the same request multiple times may create multiple resources with different outcomes. Consider your operation's idempotency and safety requirements when choosing the appropriate request method.</p>
</li>
</ol>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>HTTP is a crucial protocol that governs how data is transmitted and received between clients and servers on the World Wide Web. Request methods in HTTP, such as Call, Put, and Post, indicate the type of operation the client wants to perform on a resource on the server.</p>
<p>Understanding how these request methods work is essential in web development, as they determine how the server will handle the requests and what actions will be taken on the resources.</p>
<p>By utilizing the appropriate request methods in your web applications, you can effectively communicate with servers and manage resources reliably and efficiently.</p>
<p>Have fun coding!</p>
<p>Embark on a journey of learning! <a target="_blank" href="https://joelolawanle.com/contents">Browse 200+ expert articles on web development</a>. Search 'request' for a deep dive into POST, GET, and making HTTP requests with React and JavaScript. Check out <a target="_blank" href="https://joelolawanle.com/posts">my blog</a> for more captivating content from me.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Bubble Sort Algorithm - Most Asked Questions About Bubble Sort ]]>
                </title>
                <description>
                    <![CDATA[ Bubble sort is a simple sorting algorithm that repeatedly loops through a list, compares adjacent elements, and swaps them if they are in the wrong order. The bubble sort algorithm is not the most efficient sorting algorithm when it comes to time com... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/most-asked-questions-about-bubble-sort/</link>
                <guid isPermaLink="false">66d45fe8d1ffc3d3eb89de12</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ bubble ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joel Olawanle ]]>
                </dc:creator>
                <pubDate>Wed, 05 Apr 2023 21:40:48 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/cover-template--6-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Bubble sort is a simple sorting algorithm that repeatedly loops through a list, compares adjacent elements, and swaps them if they are in the wrong order.</p>
<p>The bubble sort algorithm is not the most efficient sorting algorithm when it comes to time complexity. But it is still often used as a starting point for learning and understanding the basic principles of sorting algorithms.</p>
<p>In this article, you will explore the most commonly asked questions about the bubble sort algorithm, including its time and space complexity, best-case and worst-case runtime, implementation in JavaScript, and more.</p>
<h2 id="heading-what-is-bubble-sort-algorithm">What is Bubble Sort Algorithm?</h2>
<p>Bubble sorting is a way of sorting a list of things, like numbers or words, into a specific order. It works by looking at pairs of adjacent items in the list and swapping them if they are in the wrong order.</p>
<p>For example, if you have a list of [3, 1, 4, 2], bubble sort would compare 3 and 1, seeing that they are in the wrong order, it swaps them to get [1, 3, 4, 2]. It then compares 3 and 4, seeing that they are in the correct order, it moves on to the next pair.</p>
<p>Bubble sort continues to compare adjacent pairs and swap them if necessary until the list is completely sorted. As the algorithm progresses, smaller items "bubble" to the top of the list. This is why it's called bubble sort.</p>
<p>While bubble sort is a simple and easy-to-understand algorithm, it's not the most efficient. In fact, it has a worst-case time complexity of O(n^2), which means that it's not a good choice for sorting very large lists.</p>
<p>But it's still useful for teaching and learning about sorting algorithms and their basic principles.</p>
<h2 id="heading-implementation-of-bubble-sort-algorithm-with-javascript">Implementation of Bubble Sort Algorithm With JavaScript</h2>
<p>Here's an example implementation of the bubble sort algorithm in JavaScript:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> bubbleSort = <span class="hljs-function">(<span class="hljs-params">arr</span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> swapped;

  <span class="hljs-keyword">do</span> {
    swapped = <span class="hljs-literal">false</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; arr.length - <span class="hljs-number">1</span>; i++) {
      <span class="hljs-keyword">if</span> (arr[i] &gt; arr[i + <span class="hljs-number">1</span>]) {
        [myArray[i], myArray[i + <span class="hljs-number">1</span>]] = [myArray[i + <span class="hljs-number">1</span>], myArray[i]];
        swapped = <span class="hljs-literal">true</span>;
      }
    }
  } <span class="hljs-keyword">while</span> (swapped);

  <span class="hljs-keyword">return</span> arr;
};

<span class="hljs-keyword">let</span> myArray = [<span class="hljs-number">12</span>, <span class="hljs-number">10</span>, <span class="hljs-number">3</span>, <span class="hljs-number">7</span>, <span class="hljs-number">4</span>];
<span class="hljs-built_in">console</span>.log(bubbleSort(myArray)); <span class="hljs-comment">// returns [3, 4, 7, 10, 12]</span>
</code></pre>
<p>In this implementation, you define a function that takes an array as its input. The function uses two nested loops to iterate over the array and compares adjacent elements.</p>
<p>You can read more on <a target="_blank" href="https://www.freecodecamp.org/news/how-to-implement-bubble-sort-algorithm-with-javascript/">how to write the bubble sort algorithm in this detailed article</a>.</p>
<h2 id="heading-most-asked-questions-about-bubble-sort-algorithm">Most Asked Questions About Bubble Sort Algorithm</h2>
<p>Let’s now explore some of the most common questions you would ask about the bubble sort algorithm to give you clarity.</p>
<h3 id="heading-1-what-is-the-best-case-runtime-complexity-of-standard-bubble-sort">1. What is the best-case runtime complexity of standard bubble sort?</h3>
<p>The best-case runtime complexity of standard bubble sort is O(n) when the input array is already sorted, and no element swap is needed.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myArray = [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">7</span>, <span class="hljs-number">10</span>, <span class="hljs-number">12</span>];
<span class="hljs-built_in">console</span>.log(bubbleSort(myArray)); <span class="hljs-comment">// returns [3, 4, 7, 10, 12]</span>
</code></pre>
<h3 id="heading-2-what-is-the-time-and-space-complexity-of-bubble-sort">2. What is the time and space complexity of bubble sort?</h3>
<p>The time complexity of bubble sort is O(n^2), where n is the number of elements in the array. The space complexity of bubble sort is O(1) because it uses only a constant amount of extra memory.</p>
<h3 id="heading-3-what-type-of-algorithm-is-bubble-sort">3. What type of algorithm is bubble sort?</h3>
<p>Bubble sort is a simple sorting algorithm that repeatedly loops through a list, compares adjacent elements, and swaps them if they are in the wrong order.</p>
<h3 id="heading-4-what-is-the-best-case-time-complexity-of-bubble-sort">4. What is the best-case time complexity of bubble sort?</h3>
<p>The best-case time complexity of bubble sort is O(n), where n is the number of elements in the array. This occurs when the input array is already sorted, and no element swap is needed.</p>
<h3 id="heading-5-what-is-the-average-case-complexity-of-bubble-sort">5. What is the average case complexity of bubble sort?</h3>
<p>The average case complexity of bubble sort is O(n^2), where n is the number of elements in the array. This occurs when the input array is unsorted, and multiple elements have to be swapped.</p>
<h3 id="heading-6-what-is-the-worst-time-complexity-of-bubble-sort">6. What is the worst time complexity of bubble sort?</h3>
<p>The worst time complexity of bubble sort is O(n^2), where n is the number of elements in the array. This occurs when the input array is reverse sorted, and every element has to be swapped.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>In this article, we've covered several frequently asked questions about bubble sort, including its time and space complexity, best and worst-case runtime, and how to implement it in JavaScript.</p>
<p>Hopefully, this article has given you a better understanding of bubble sort and its limitations. Remember that while bubble sort is a good starting point for learning about sorting algorithms, more efficient algorithms are available for sorting larger datasets.</p>
<p>Have fun coding!</p>
<p>You can access over 200 of my articles by <a target="_blank" href="https://joelolawanle.com/contents">visiting my website</a>. You can also use the search field to see if I've written a specific article.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Insertion Sort Algorithm - Most Asked Questions About Insertion Sort ]]>
                </title>
                <description>
                    <![CDATA[ Sorting algorithms are an essential part of computer science. There are many sorting algorithms used to sort data. The insertion sort algorithm is one of the most basic and simple sorting algorithms. It is an efficient algorithm for small input sizes... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/most-asked-questions-about-insertion-sort-algorithm/</link>
                <guid isPermaLink="false">66d45fea264384a65d5a9584</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joel Olawanle ]]>
                </dc:creator>
                <pubDate>Fri, 31 Mar 2023 19:26:33 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/cover-template--3-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Sorting algorithms are an essential part of computer science. There are many sorting algorithms used to sort data.</p>
<p>The insertion sort algorithm is one of the most basic and simple sorting algorithms. It is an efficient algorithm for small input sizes or for partially sorted data. The algorithm works by sorting elements one at a time, starting with the first element in the list.</p>
<p>In this article, you'll learn about the insertion sort algorithm and how it works. You'll also learn how to implement the algorithm in JavaScript. This article will also answer some common questions about the insertion sort algorithm.</p>
<h2 id="heading-what-is-insertion-sort">What is Insertion Sort?</h2>
<p>Insertion sort is a sorting algorithm that sorts an array by inserting each element in its correct position in a sorted sub-list. It is called an in-place comparison sorting algorithm because it sorts the input list in place without requiring any extra memory.</p>
<p>It works by comparing each element with the previous elements and then moving the element to its correct position by shifting the larger elements to the right.</p>
<h2 id="heading-implementation-of-insertion-sort-with-javascript">Implementation of Insertion Sort With JavaScript</h2>
<p>Here's an implementation of the Insertion Sort algorithm in JavaScript:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> insertionSort = <span class="hljs-function">(<span class="hljs-params">arr</span>) =&gt;</span> {
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">1</span>; i &lt; arr.length; i++) {
    <span class="hljs-keyword">let</span> currentValue = arr[i];
    <span class="hljs-keyword">let</span> j = i - <span class="hljs-number">1</span>;
    <span class="hljs-keyword">while</span> (j &gt;= <span class="hljs-number">0</span> &amp;&amp; arr[j] &gt; currentValue) {
      arr[j + <span class="hljs-number">1</span>] = arr[j];
      j--;
    }
    arr[j + <span class="hljs-number">1</span>] = currentValue;
  }
  <span class="hljs-keyword">return</span> arr;
};
</code></pre>
<p>The function takes an array as input and performs the insertion sort algorithm. It loops through the array starting from the second element and compares it with the elements before it.</p>
<p>If an element is greater than the current value, it shifts the element to the right until it finds its proper position.</p>
<p>Once the element is placed properly, the loop moves on to the next element until the array is completely sorted. The function returns the sorted array.</p>
<p>You can call the function with an array as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myArray = [<span class="hljs-number">3</span>, <span class="hljs-number">7</span>, <span class="hljs-number">4</span>, <span class="hljs-number">10</span>, <span class="hljs-number">12</span>];
<span class="hljs-built_in">console</span>.log(insertionSort(myArray)); <span class="hljs-comment">// returns [3, 4, 7, 10, 12]</span>
</code></pre>
<p>This is just one way to implement the insertion sort algorithm in JavaScript. There are many other ways to write it, but this should give you an idea of how it works.</p>
<h2 id="heading-is-insertion-sort-stable">Is Insertion Sort Stable?</h2>
<p>Yes, insertion sort is a stable sorting algorithm.</p>
<p>A stable sorting algorithm is one that maintains the relative order of equal elements in the sorted output.</p>
<p>In other words, if two elements have the same value, their relative order in the input array should be preserved in the sorted array.</p>
<h2 id="heading-what-kind-of-algorithm-is-insertion-sort">What Kind of Algorithm is Insertion Sort?</h2>
<p>Insertion sort is a comparison-based algorithm.</p>
<p>It compares the current and previous elements to determine their correct position in the sorted list. It is a simple and efficient algorithm that is easy to implement.</p>
<h2 id="heading-is-insertion-sort-a-greedy-algorithm">Is Insertion Sort a Greedy Algorithm?</h2>
<p>No, insertion sort is not a greedy algorithm.</p>
<p>A greedy algorithm is an algorithm that makes a locally optimal choice at each step with the hope of finding a global optimum.</p>
<p>Insertion sort does not make any locally optimal choice but instead inserts each element in its correct position to achieve the global optimum.</p>
<h2 id="heading-time-complexity-of-insertion-sort-algorithm">Time Complexity of Insertion Sort Algorithm</h2>
<p>The time complexity of the insertion sort algorithm is O(n^2) in the worst case and O(n) in the best case.</p>
<h3 id="heading-best-case-running-time-of-an-insertion-sort-algorithm">Best Case Running Time of an Insertion Sort Algorithm</h3>
<p>The best-case running time of an insertion sort algorithm is O(n). This occurs when the input array is sorted, and no elements must be moved.</p>
<p>This results in n-1 comparisons, which is approximately equal to n. Therefore, the time complexity is O(n).</p>
<h3 id="heading-best-case-time-efficiency-of-insertion-sort">Best Case Time Efficiency of Insertion Sort</h3>
<p>The best-case time efficiency of an insertion sort algorithm is Ω(n), which is the lower bound of the running time. This occurs when the input array is sorted and no elements need to be moved.</p>
<h3 id="heading-worst-time-complexity-of-insertion-sort">Worst Time Complexity of Insertion Sort</h3>
<p>The worst-case time complexity of an insertion sort algorithm is O(n^2).</p>
<p>This occurs when the input array is in reverse order, and each element must be moved to its correct position by shifting all the larger elements to the right.</p>
<p>The input array is in reverse order. Every element has to be compared and swapped with every other element in the array. This results in n*(n-1)/2 comparisons and swaps, approximately equal to n^2/2. Therefore, the time complexity is O(n^2).</p>
<h3 id="heading-average-case-running-time-of-an-insertion-sort-algorithm">Average Case Running Time of an Insertion Sort Algorithm</h3>
<p>The average case running time of an insertion sort algorithm is O(n^2).</p>
<p>This occurs when the input array is randomly ordered, and each element must be moved to its correct position by shifting all the larger elements to the right.</p>
<h3 id="heading-typical-runtime-for-insertion-sort-for-singly-linked-lists">Typical Runtime for Insertion Sort for Singly Linked Lists</h3>
<p>Insertion sort can also be used to sort singly-linked lists.</p>
<p>The typical runtime for insertion sort for singly linked lists is also O(n^2), the same for arrays. However, the space complexity may differ due to the data structure difference.</p>
<h2 id="heading-does-insertion-sort-use-divide-and-conquer">Does Insertion Sort Use Divide and Conquer?</h2>
<p>No, insertion sort does not use the Divide and Conquer approach.</p>
<p>Divide and Conquer is an algorithmic paradigm that involves breaking a problem into sub-problems, solving them independently, and then combining their solutions to solve the original problem.</p>
<p>Insertion sort works by sorting the elements individually without breaking the problem into sub-problems.</p>
<h2 id="heading-why-is-insertion-sort-slow">Why is Insertion Sort Slow?</h2>
<p>Insertion sort is slow because it has a time complexity of O(n^2) in the worst case.</p>
<p>This means that as the input size increases, the algorithm's running time also increases rapidly. Insertion sort is not the best choice for large input sizes, but it can be very efficient for small input sizes or for partially sorted data.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>Insertion sort is a simple and efficient algorithm for small input sizes or partially sorted data. It has a time complexity of O(n^2) in the worst case and O(n) in the best case.</p>
<p>It is a stable sorting algorithm that maintains the relative order of equal elements. Although it may be slow for large input sizes, it can be very efficient for small input sizes or for partially sorted data.</p>
<p>Have fun coding!</p>
<p>You can access over 200 of my articles by <a target="_blank" href="https://joelolawanle.com/contents">visiting my website</a>. You can also use the search field to see if I've written a specific article.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Comments Inside JSON – Commenting in a JSON File ]]>
                </title>
                <description>
                    <![CDATA[ JSON (JavaScript Object Notation) is a popular data interchange format used in web development and mobile applications due to its simplicity and flexibility. But JSON files do not officially support comments. This makes providing additional context o... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/comments-in-json/</link>
                <guid isPermaLink="false">66d45f6f9f2bec37e2da0624</guid>
                
                    <category>
                        <![CDATA[ json ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joel Olawanle ]]>
                </dc:creator>
                <pubDate>Fri, 31 Mar 2023 15:10:51 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/cover-template--1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JSON (JavaScript Object Notation) is a popular data interchange format used in web development and mobile applications due to its simplicity and flexibility.</p>
<p>But JSON files do not officially support comments. This makes providing additional context or explanation for the data challenging.</p>
<p>This article will show you how to include comments in JSON files and why JSON does not natively support comments.</p>
<h2 id="heading-why-json-does-not-support-comments">Why JSON Does Not Support Comments?</h2>
<p>According to the JSON specification, a JSON document should only contain data structures like arrays and objects and not include comments. This is because JSON is intended to be a simple, easily parsable data format that can be quickly and efficiently processed.</p>
<p>Comments, while useful for providing additional context or explanation for human readers, can add complexity to the parsing process. This slows down performance and increases the risk of errors.</p>
<p>The primary reason why JSON does not support comments is that its creator, <a target="_blank" href="https://en.wikipedia.org/wiki/Douglas_Crockford">Douglas Crockford</a>, deliberately removed them from the format to prevent misuse and keep it as a pure data-only format.</p>
<p>Crockford observed that some people were using comments to store parsing directives, which could break compatibility between different systems. Hence, the decision to remove comments to maintain the simplicity and consistency of the format across various programming languages and environments.</p>
<p>As a result, the only option for adding comments to a JSON file is to use a workaround, such as using custom elements to store comments.</p>
<h2 id="heading-how-to-add-comments-inside-json">How to Add Comments Inside JSON</h2>
<p>When you add comments in the form <code>//</code>, <code>#</code>, or <code>/* */</code>, which are used in popular programming languages, you will notice the error “Comments are not permitted in JSON”.</p>
<p><img src="https://paper-attachments.dropboxusercontent.com/s_7788E690364D593F2C3E31F8D1CF26EB90DAC0141414EE29BD5F57C061BD4347_1680020901125_image.png" alt="s_7788E690364D593F2C3E31F8D1CF26EB90DAC0141414EE29BD5F57C061BD4347_1680020901125_image" width="1774" height="354" loading="lazy"></p>
<p>Then, how can you add comments to a JSON file?</p>
<p>The only way this can be done is to include comments as data pairs in a JSON file. It is not a commonly used or recommended practice, but technically it’s the best way to add comments to your JSON file.</p>
<p>Create a custom element within your JSON object, such as "_comment", to distinguish them from the rest of the data.</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"_comment"</span>: <span class="hljs-string">"Put your JSON comment here"</span>
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"John Doe"</span>,
    <span class="hljs-attr">"age"</span>: <span class="hljs-number">35</span>,
    <span class="hljs-attr">"city"</span>: <span class="hljs-string">"New York City"</span>,
    <span class="hljs-attr">"isMarried"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"occupation"</span>: <span class="hljs-string">"Software Engineer"</span>,
}
</code></pre>
<p><strong>Note:</strong> It's not compulsory that you use underscores. You can decide to use two slash such as “//comment” or any other allowed character. <strong>The goal is to make it clear that it’s a comment</strong>.</p>
<p>It's important to note that this approach may make the JSON file more complex and harder to parse. But if comments are added as custom elements, they will be received and processed like any other data in JSON on the server-side.</p>
<p>You now know how to add comments to your JSON file technically. But how can you add multiple comments? This is possible, but you should remember that JSON does not allow duplicate object keys. You must include unique letters or numbers in the comment element, ensuring it is valid and distinguishable from other elements in the JSON file.</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"_comment1"</span>: <span class="hljs-string">"This is the basic data"</span>,
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"John Doe"</span>,
    <span class="hljs-attr">"age"</span>: <span class="hljs-number">35</span>,
    <span class="hljs-attr">"city"</span>: <span class="hljs-string">"New York City"</span>,
    <span class="hljs-attr">"_comment2"</span>: <span class="hljs-string">"Marital information"</span>,
    <span class="hljs-attr">"isMarried"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"wifeName"</span>: <span class="hljs-string">"Jane Doe"</span>
}
</code></pre>
<p>When you have nested JSON objects, you can use similar object keys:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"_comment"</span>: <span class="hljs-string">"This is the basic data"</span>,
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"John Doe"</span>,
    <span class="hljs-attr">"age"</span>: <span class="hljs-number">35</span>,
    <span class="hljs-attr">"city"</span>: <span class="hljs-string">"New York City"</span>,
    <span class="hljs-attr">"maritalInfo"</span>: {
        <span class="hljs-attr">"_comment"</span>: <span class="hljs-string">"Marital information"</span>,
        <span class="hljs-attr">"isMarried"</span>: <span class="hljs-literal">true</span>,
        <span class="hljs-attr">"wifeName"</span>: <span class="hljs-string">"Jane Doe"</span>
    }
}
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>You now know how to add comments to your JSON file. But because these comments are also processed and can be accessed, you need to be careful when adding comments to JSON files using custom elements.</p>
<p>Thanks for reading. Have fun coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How To Implement Bubble Sort Algorithm With JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ Sorting is an essential task in programming, and the bubble sort algorithm is one of the simplest and most commonly used methods. As a beginner in solving algorithm questions or preparing for an interview, you might wonder how to implement this algor... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-implement-bubble-sort-algorithm-with-javascript/</link>
                <guid isPermaLink="false">66d45fa3d7a4e35e38434979</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joel Olawanle ]]>
                </dc:creator>
                <pubDate>Thu, 30 Mar 2023 15:34:25 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/cover-template--2-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Sorting is an essential task in programming, and the bubble sort algorithm is one of the simplest and most commonly used methods.</p>
<p>As a beginner in solving algorithm questions or preparing for an interview, you might wonder how to implement this algorithm effectively.</p>
<p>Don't worry; in this article, I will guide you step by step on how to implement the bubble sort algorithm with JavaScript. By the end of this tutorial, you will have a solid understanding of how this algorithm works and be able to apply it to your own projects.</p>
<h2 id="heading-what-is-bubble-sort-algorithm">What is Bubble Sort Algorithm?</h2>
<p>Bubble sort algorithm is a simple sorting technique that compares two adjacent elements in an array and swaps them if they are in the wrong order. It keeps repeating this process until the array is sorted.</p>
<p>For example, the diagram below illustrates the different swaps/bubble that happens when the element on the left is greater than the element on the right.</p>
<p>Also, at the end of the array iteration, it checks to see if any swaps occurred; if so, the process is repeated; otherwise, the array is sorted.</p>
<p><img src="https://paper-attachments.dropboxusercontent.com/s_AA89D639F731C302D3BEA2FB06F0908D85A1AFFFF9C777BBB48943CB5F4958DF_1680155344777_Untitled.drawio.png" alt="s_AA89D639F731C302D3BEA2FB06F0908D85A1AFFFF9C777BBB48943CB5F4958DF_1680155344777_Untitled.drawio" width="701" height="586" loading="lazy"></p>
<p>Imagine bubbles in a glass of soda where the bubbles rise to the top one by one. That's similar to how this algorithm works.</p>
<p>Bubble sort is easy to understand and implement but can be slow for large data sets.</p>
<h2 id="heading-how-to-implement-bubble-sort-algorithm-with-javascript">How to Implement Bubble Sort Algorithm With Javascript</h2>
<p>With the illustration in the previous section, you should have an idea of how the bubble sort algorithm is supposed to work. But how can you write this algorithm with JavaScript?</p>
<p>Here are 5 steps to make the process easy for you:</p>
<ol>
<li><p>Create a boolean variable to track the swapping of elements in the current iteration.</p>
</li>
<li><p>Create a "do-while" loop that iterates through the array until it is sorted.</p>
</li>
<li><p>At the start of each iteration, set the boolean variable to false.</p>
</li>
<li><p>Use a "for" loop to compare adjacent elements. Swap them if they are not in the correct order, and set the boolean variable to true if any element is swapped.</p>
</li>
<li><p>Repeat the loop until there are no more elements to swap in the current iteration.</p>
</li>
</ol>
<p>Using the steps above, let's implement the algorithm in JavaScript.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> bubbleSort = <span class="hljs-function">(<span class="hljs-params">arr</span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> swapped;

  <span class="hljs-keyword">do</span> {
    swapped = <span class="hljs-literal">false</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; arr.length - <span class="hljs-number">1</span>; i++) {
      <span class="hljs-keyword">if</span> (arr[i] &gt; arr[i + <span class="hljs-number">1</span>]) {
        <span class="hljs-keyword">let</span> temp = arr[i];
        arr[i] = arr[i + <span class="hljs-number">1</span>];
        arr[i + <span class="hljs-number">1</span>] = temp;
        swapped = <span class="hljs-literal">true</span>;
      }
    }
  } <span class="hljs-keyword">while</span> (swapped);

  <span class="hljs-keyword">return</span> arr;
};
</code></pre>
<p>Let's walk through this implementation step by step. First, we create a function to handle the bubble sort operation and hold the algorithm.</p>
<h3 id="heading-step-1-create-a-boolean-variable">Step 1: Create a boolean variable</h3>
<p>You will need to track whether any swap has been made in the current iteration of the array. To do this, create a boolean variable named "swapped" for this purpose.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> swapped;
</code></pre>
<h3 id="heading-step-2-create-a-do-while-loop-to-iterate-until-the-array-is-sorted">Step 2: Create a "do-while" loop to iterate until the array is sorted</h3>
<p>Let’s use the "do-while" loop to iterate through the array until it is sorted. The loop executes at least once, even if the array is already sorted — which is why it’s best used for this.</p>
<p>You will also use the "swapped" variable to check whether any swap has been made in the current iteration.</p>
<pre><code class="lang-js"><span class="hljs-keyword">do</span> {
  <span class="hljs-comment">// code to be executed</span>
} <span class="hljs-keyword">while</span> (swapped);
</code></pre>
<h3 id="heading-step-3-set-the-boolean-variable-to-false-at-the-start-of-each-iteration">Step 3: Set the boolean variable to false at the start of each iteration</h3>
<p>At the beginning of each iteration, you need to set the "swapped" variable to false. This is because you have not made any swap yet in the current iteration.</p>
<pre><code class="lang-js"><span class="hljs-keyword">do</span> {
  swapped = <span class="hljs-literal">false</span>;
  <span class="hljs-comment">// code to be executed</span>
} <span class="hljs-keyword">while</span> (swapped);
</code></pre>
<h3 id="heading-step-4-use-a-for-loop-to-compare-adjacent-elements">Step 4: Use a "for" loop to compare adjacent elements</h3>
<p>Within the "do-while" loop, we use a "for" loop to compare each array element with the element next to it. If the current element is greater than the next element, they are swapped.</p>
<p>We also set the "swapped" variable to true if a swap is made, indicating that the array is not yet sorted.</p>
<pre><code class="lang-js"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; arr.length - <span class="hljs-number">1</span>; i++) {
    <span class="hljs-keyword">if</span> (arr[i] &gt; arr[i + <span class="hljs-number">1</span>]) {
      <span class="hljs-keyword">let</span> temp = arr[i];
      arr[i] = arr[i + <span class="hljs-number">1</span>];
      arr[i + <span class="hljs-number">1</span>] = temp;
      swapped = <span class="hljs-literal">true</span>;
    }
  }
} <span class="hljs-keyword">while</span> (swapped);
</code></pre>
<h3 id="heading-step-5-repeat-the-loop-until-no-more-swaps-are-made">Step 5: Repeat the loop until no more swaps are made</h3>
<p>If no swap is made in the current iteration, the "swapped" variable remains false. This means the array is sorted, and we can exit the loop.</p>
<p>If elements have been swapped, the "swapped" variable is set to true, and the loop continues to iterate until the array is sorted.</p>
<h2 id="heading-testing-the-bubble-sort-algorithm">Testing the Bubble Sort Algorithm</h2>
<p>To test the bubble sort algorithm, you can create an array of random numbers and pass it to the <code>bubbleSort()</code> function.</p>
<p>Here's an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myArray = [<span class="hljs-number">12</span>, <span class="hljs-number">10</span>, <span class="hljs-number">3</span>, <span class="hljs-number">7</span>, <span class="hljs-number">4</span>];
<span class="hljs-built_in">console</span>.log(bubbleSort(myArray)); <span class="hljs-comment">// Output: [3, 4, 7, 10, 12]</span>
</code></pre>
<h2 id="heading-worst-case-time-complexity-of-bubble-sort-algorithm">Worst Case Time Complexity of Bubble Sort Algorithm</h2>
<p>The worst-case time complexity of an algorithm refers to the maximum amount of time the algorithm can take to complete, given the worst possible input.</p>
<p>For bubble sort, the worst-case time complexity occurs when the array is in reverse order. This means that every element needs to be swapped with every other element.</p>
<p>In this case, the algorithm's time complexity is O(n^2), where n is the number of elements in the array.</p>
<p>This makes bubble sort inefficient for large arrays, as the time required to sort the array grows quadratically with the size of the array.</p>
<p>However, bubble sort can be useful for small arrays or in cases where the array is nearly sorted, as it has a simple implementation and requires only constant space.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>In this article, you have learned what the bubble sort algorithm means and how you can create the algorithm.</p>
<p>Finally, let’s tweak the algorithm to arrive at a shorter one by swapping each element by destructuring:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> bubbleSort = <span class="hljs-function">(<span class="hljs-params">arr</span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> swapped;

  <span class="hljs-keyword">do</span> {
    swapped = <span class="hljs-literal">false</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; arr.length - <span class="hljs-number">1</span>; i++) {
      <span class="hljs-keyword">if</span> (arr[i] &gt; arr[i + <span class="hljs-number">1</span>]) {
        [myArray[i], myArray[i + <span class="hljs-number">1</span>]] = [myArray[i + <span class="hljs-number">1</span>], myArray[i]];
        swapped = <span class="hljs-literal">true</span>;
      }
    }
  } <span class="hljs-keyword">while</span> (swapped);

  <span class="hljs-keyword">return</span> arr;
};

<span class="hljs-keyword">let</span> myArray = [<span class="hljs-number">12</span>, <span class="hljs-number">10</span>, <span class="hljs-number">3</span>, <span class="hljs-number">7</span>, <span class="hljs-number">4</span>];
<span class="hljs-built_in">console</span>.log(bubbleSort(myArray)); <span class="hljs-comment">// returns [3, 4, 7, 10, 12]</span>
</code></pre>
<p>You can read more on <a target="_blank" href="https://www.freecodecamp.org/news/swap-two-array-elements-in-javascript/">how to swap two array elements in JavaScript</a>.</p>
<p>Have fun coding!</p>
<p>You can access over 200 of my articles by <a target="_blank" href="https://joelolawanle.com/contents">visiting my website</a>. You can also use the search field to see if I've written a specific article.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Undo Git Add – How to Remove Added Files in Git ]]>
                </title>
                <description>
                    <![CDATA[ Git is a powerful version control and collaboration tool. It allows developers to work together seamlessly on projects. But even the most experienced developers can make mistakes while using Git, such as accidentally adding files that were not meant ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/undo-git-add-how-to-remove-added-files-in-git/</link>
                <guid isPermaLink="false">66d46000f855545810e9348f</guid>
                
                    <category>
                        <![CDATA[ Git ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joel Olawanle ]]>
                </dc:creator>
                <pubDate>Thu, 23 Mar 2023 18:27:08 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/cover-template.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Git is a powerful version control and collaboration tool. It allows developers to work together seamlessly on projects.</p>
<p>But even the most experienced developers can make mistakes while using Git, such as accidentally adding files that were not meant to be committed. This can be a problem, especially if the added files contain sensitive or confidential information.</p>
<p>In this article, you will learn how to undo the “Git add” command, which means removing files from the staging area and preventing them from being committed.</p>
<h2 id="heading-how-to-add-files-in-git-and-confirm">How to Add Files in Git and Confirm</h2>
<p>You probably know how to add files to the staging area using the <code>git add</code> command. When you want to add all files, you use the dot(.), but when you want to add specific file(s), you attach the file names/path:</p>
<pre><code class="lang-bash">// stage all files <span class="hljs-keyword">in</span> current directory
git add .

// stage single file
git add &lt;file&gt;

// stage multiple files
git add &lt;file1&gt; &lt;file2&gt; &lt;file3&gt; ...
</code></pre>
<p>When you stage files, you can confirm using the <code>git status</code> commands, which shows a list of all staged files:</p>
<p><img src="https://paper-attachments.dropboxusercontent.com/s_4E8AA27FDBD6E92188ADA8CF7AE76BB35CFED775D18B77141314D06FC8C13ADB_1679558784394_image.png" alt="s_4E8AA27FDBD6E92188ADA8CF7AE76BB35CFED775D18B77141314D06FC8C13ADB_1679558784394_image" width="1564" height="334" loading="lazy"></p>
<h2 id="heading-how-to-remove-added-files-in-git">How to Remove Added Files in Git</h2>
<p>There are two major commands that you can use to undo “git add” or remove added files in Git. In other words, you can use two major commands to remove staged files from the staging area.</p>
<p>These are the <code>git reset</code> and <code>git rm --cached</code> commands. But these commands are quite different from each other.</p>
<h3 id="heading-how-to-remove-added-files-in-git-with-git-reset">How to Remove Added Files in Git with <code>git reset</code></h3>
<p><code>git reset</code> is used to unstage changes that have been added to the staging area. This means it will remove the files from the staging area but keep the changes in your “working directory”.</p>
<p>To remove <strong>a single file</strong> from the staging area, you can use the following command:</p>
<pre><code class="lang-bash">git reset &lt;file&gt;
</code></pre>
<p>To remove <strong>all files</strong> from the staging area, you can use the following command:</p>
<pre><code class="lang-bash">git reset
</code></pre>
<p>So you are not confused, let me explain what the working directory means. The working directory is where you make changes to your code, while the staging area is an intermediate step where you prepare changes for committing to your repository.</p>
<p>When you use <code>git reset</code> to unstage changes from the staging area, Git will remove them but keep them in your working directory. This means that the changes you made to the files will still be visible in your local files, and you can continue to make further changes if needed.</p>
<h3 id="heading-how-to-remove-added-files-in-git-with-git-rm-cached">How to Remove Added Files in Git with <code>git rm --cached</code></h3>
<p>On the other hand, <code>git rm</code> is used to remove a file from the staging area and the working directory. This means that it will permanently delete the file from your repository.</p>
<p>To remove a file from the repository, you can use the following command:</p>
<pre><code class="lang-bash">git rm &lt;file&gt;
</code></pre>
<p>But you only want to “unstage” your files (that is, undo the <code>git add</code> command) and not “remove” them from your working repository. This is where you use the <code>--cached</code> flag. The cached option specifies that the removal should happen only on the staging index. Working directory files will be left alone.</p>
<pre><code class="lang-bash">git rm --cached &lt;file&gt;
</code></pre>
<p>It's important to note that using <code>git rm --cached</code> is not a complete solution for keeping files in the repository. The file can still be deleted from the working directory accidentally or intentionally.</p>
<p>Because of this, it's recommended to use this command with caution and to make sure you are intentionally removing files you no longer need to track in Git.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>One advantage of having multiple Git commands that can achieve similar results, such as <code>git rm</code> and <code>git reset</code>, is that they provide users with flexibility and choice. Different users may have different preferences or workflows, and having multiple options allows you to choose the best method.</p>
<p>However, having too many similar commands can also lead to confusion and mistakes, especially for new users who may not understand their subtle differences. This can result in the accidental deletion of files or other unintended consequences.</p>
<p>So just make sure you understand the Git commands and their differences carefully so you can deliberately use them. It's also helpful to consult the documentation or seek assistance from more experienced users if you are unsure how to use a particular command.</p>
<p>Have fun coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How To Write Quick Sort Algorithm With JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ Quick sort is a widely used sorting algorithm that efficiently sorts an array of elements by dividing it into smaller subarrays based on a chosen pivot element. In this article, we will walk through how to write a quick sort algorithm using JavaScrip... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-write-quick-sort-algorithm-with-javascript/</link>
                <guid isPermaLink="false">66d45fba264384a65d5a957e</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joel Olawanle ]]>
                </dc:creator>
                <pubDate>Wed, 15 Mar 2023 09:27:48 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/cover-template--6-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Quick sort is a widely used sorting algorithm that efficiently sorts an array of elements by dividing it into smaller subarrays based on a chosen pivot element.</p>
<p>In this article, we will walk through how to write a quick sort algorithm using JavaScript and explore the key concepts behind the algorithm.</p>
<h2 id="heading-what-is-the-quick-sort-algorithm">What Is the Quick Sort Algorithm?</h2>
<p>Sorting is a common task in computer programming, and there are many sorting algorithms available that can be used in different ways. One of the most popular and efficient sorting algorithms is quick sort.</p>
<p>Quick sort is a divide-and-conquer algorithm that sorts an array by choosing a pivot element and partitioning the array into two subarrays, one containing elements smaller than the pivot, and the other containing elements larger than the pivot. The two subarrays are then recursively sorted until the entire array is sorted.</p>
<p><strong>Note:</strong> In quick sort algorithm, the pivot is a selected element from the array that is used as a reference point for partitioning the array into two smaller sub-arrays.</p>
<p>The pivot is usually selected as the first or last element of the array, although there are other methods for selecting the pivot.</p>
<h2 id="heading-implementing-quick-sort-algorithm-with-javascript">Implementing Quick Sort Algorithm With Javascript</h2>
<p>Before we start implementing the quick sort algorithm, let's first understand its basic concepts. As we mentioned earlier, quick sort is a divide-and-conquer algorithm. The algorithm can be broken down into three main steps:</p>
<ol>
<li><p>Choose a pivot element from the array.</p>
</li>
<li><p>Partition the array into two subarrays, one containing elements smaller than the pivot, and the other containing elements larger than the pivot.</p>
</li>
<li><p>Recursively apply the quick sort algorithm to the two subarrays until the entire array is sorted.</p>
</li>
</ol>
<p>With this understanding, let's move on to implementing the algorithm in JavaScript.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> quickSort = <span class="hljs-function">(<span class="hljs-params">arr</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (arr.length &lt;= <span class="hljs-number">1</span>) {
    <span class="hljs-keyword">return</span> arr;
  }

  <span class="hljs-keyword">let</span> pivot = arr[<span class="hljs-number">0</span>];
  <span class="hljs-keyword">let</span> leftArr = [];
  <span class="hljs-keyword">let</span> rightArr = [];

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">1</span>; i &lt; arr.length; i++) {
    <span class="hljs-keyword">if</span> (arr[i] &lt; pivot) {
      leftArr.push(arr[i]);
    } <span class="hljs-keyword">else</span> {
      rightArr.push(arr[i]);
    }
  }

  <span class="hljs-keyword">return</span> [...quickSort(leftArr), pivot, ...quickSort(rightArr)];
};
</code></pre>
<p>Let's walk through this implementation step by step. First, we create a function to handle the quick sort operation and hold the algorithm.</p>
<h3 id="heading-step-1-choose-a-pivot-element">Step 1: Choose a Pivot Element</h3>
<p>We start by choosing a pivot element from the array. In this implementation, we will use the first element of the array as the pivot.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> pivot = arr[<span class="hljs-number">0</span>];
</code></pre>
<h3 id="heading-step-2-partition-the-array">Step 2: Partition the Array</h3>
<p>After choosing the pivot element, the next step is to partition the array into two subarrays — one containing elements smaller than the pivot, and the other containing elements larger than the pivot.</p>
<p>We can achieve this by iterating through the array, comparing each element to the pivot and pushing it into the appropriate subarray.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> leftArr = [];
<span class="hljs-keyword">let</span> rightArr = [];

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">1</span>; i &lt; arr.length; i++) {
  <span class="hljs-keyword">if</span> (arr[i] &lt; pivot) {
    leftArr.push(arr[i]);
  } <span class="hljs-keyword">else</span> {
    rightArr.push(arr[i]);
  }
}
</code></pre>
<h3 id="heading-step-3-recursively-sort-the-subarrays">Step 3: Recursively Sort the Subarrays</h3>
<p>Next, we recursively apply the quick sort algorithm to the two subarrays until the entire array is sorted. We then use the spread operator to concatenate the sorted left subarray, pivot, and sorted right subarray.</p>
<pre><code class="lang-js"><span class="hljs-keyword">return</span> [...quickSort(leftArr), pivot, ...quickSort(rightArr)];
</code></pre>
<p>But for this not to continue over and over, there has to be a base case to stop the <a target="_blank" href="https://joelolawanle.com/posts/recursion-in-javascript-explained-for-beginners">recursion</a>.</p>
<h3 id="heading-step-4-define-a-base-case">Step 4: Define a Base Case</h3>
<p>The final step is to define a base case for the recursive function. This is used when the array has a length of 0 or 1, as an array with one element is already sorted.</p>
<pre><code class="lang-js"><span class="hljs-keyword">if</span> (arr.length &lt;= <span class="hljs-number">1</span>) {
  <span class="hljs-keyword">return</span> arr;
}
</code></pre>
<h2 id="heading-testing-the-quick-sort-algorithm">Testing the Quick Sort Algorithm</h2>
<p>To test the quick sort algorithm, we can create an array of random numbers and pass it to the <code>quickSort()</code> function.</p>
<p>Here's an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myArray = [<span class="hljs-number">3</span>, <span class="hljs-number">7</span>, <span class="hljs-number">2</span>, <span class="hljs-number">5</span>, <span class="hljs-number">1</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">8</span>];
<span class="hljs-built_in">console</span>.log(quicksort(myArray)); <span class="hljs-comment">// Output: [1,2,3,4,5,6,7,8]</span>
</code></pre>
<h2 id="heading-wrapping-up">Wrapping Up ✨</h2>
<p>In this article, you have learned what the quick sort algorithm means and how you can create the algorithm.</p>
<p>You can use any value as your pivot number by tweaking the code a little.</p>
<p>Have fun coding!</p>
<p>You can access over 195 of my articles by <a target="_blank" href="https://joelolawanle.com/contents">visiting my website</a>. You can also use the search field to see if I've written a specific article.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
