<?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[ Chinwendu Enyinna - 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[ Chinwendu Enyinna - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 29 Oct 2026 21:38:02 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/chicoder/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Cloud Service Models Explained: IaaS vs PaaS vs SaaS ]]>
                </title>
                <description>
                    <![CDATA[ You likely use cloud services every day. When you check Gmail, join a Zoom meeting, or message your team on Slack, you use cloud-hosted software. But you don't manage the servers it runs on or maintai ]]>
                </description>
                <link>https://www.freecodecamp.org/news/cloud-service-models-explained-iaas-vs-paas-vs-saas/</link>
                <guid isPermaLink="false">6ae368ce7483e3ea0090cfe2</guid>
                
                    <category>
                        <![CDATA[ Cloud Computing ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Cloud Engineering  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Chinwendu Enyinna ]]>
                </dc:creator>
                <pubDate>Thu, 29 Oct 2026 15:39:58 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/e9e06980-6916-4ded-9079-e007e85ff32b.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>You likely use cloud services every day. When you check Gmail, join a Zoom meeting, or message your team on Slack, you use cloud-hosted software.</p>
<p>But you don't manage the servers it runs on or maintain the underlying infrastructure. You simply sign in and get to work. This is called <strong>Software as a Service (SaaS)</strong>, and many people use it for years without knowing the term.</p>
<p>SaaS is just one of three major cloud service models. The other two, <strong>Infrastructure as a Service (IaaS)</strong> and <strong>Platform as a Service (PaaS)</strong>, give you different levels of control over the infrastructure and software you build. Understanding how these models differ will help you make sense of cloud engineering concepts and choose the right approach for your projects.</p>
<p>In this article, we'll break down IaaS, PaaS, and SaaS, explain what you manage and what the cloud provider handles in each model, and learn how to choose between them for a real project.</p>
<h3 id="heading-what-youll-learn">What You'll&nbsp;Learn</h3>
<p>By the end of this article, you'll be able to:</p>
<ul>
<li>Explain what IaaS, PaaS, and SaaS are and what each one manages for you</li>
<li>Use the shared responsibility model to see where your job starts and ends</li>
<li>Recognise real products in each category</li>
<li>Choose the right model for a given project</li>
</ul>
<h3 id="heading-table-of-contents">Table of&nbsp;Contents</h3>
<ul>
<li><a href="#heading-prerequisites">Prerequisites</a></li>
<li><a href="#heading-what-is-cloud-computing">What Is Cloud Computing?</a></li>
<li><a href="#heading-the-shared-responsibility-model">The Shared Responsibility Model</a></li>
<li><a href="#heading-infrastructure-as-a-service-iaas">Infrastructure as a Service (IaaS)</a></li>
<li><a href="#heading-platform-as-a-service-paas">Platform as a Service (PaaS)</a></li>
<li><a href="#heading-software-as-a-service-saas">Software as a Service (SaaS)</a></li>
<li><a href="#heading-beyond-the-big-three-caas-faas-and-serverless">Beyond the Big Three: CaaS, FaaS, and Serverless</a></li>
<li><a href="#heading-how-to-choose-the-right-service-model">How to Choose the Right Service Model</a></li>
<li><a href="#heading-conclusion">Conclusion</a></li>
</ul>
<h3 id="heading-prerequisites">Prerequisites</h3>
<p>You don't need any cloud experience to follow this article. If you know what a computer, a server, and the internet are, you have everything you need.</p>
<p>If you're new to the cloud, read my article <a href="https://chinwendu.medium.com/what-is-the-cloud-and-cloud-computing-49c1260862b5">What is the Cloud and Cloud Computing?</a> first. It explains what the cloud is and how it differs from running your own hardware, and this article builds on that foundation.</p>
<h2 id="heading-what-is-cloud-computing">What Is Cloud Computing?</h2>
<p>Cloud computing is a model that lets you use computing resources, such as servers, storage, and networking, on demand over the internet. YOu pay only for what you use.</p>
<p>These resources sit in data centres that are owned and run by cloud service providers, or CSPs for short. The best-known CSPs are Amazon Web Services (AWS), Microsoft Azure, and Google Cloud.</p>
<p>This is just a short recap to make sure you understand the key concepts. My article above covers it in full if you want or need more info.</p>
<h3 id="heading-what-does-on-premises-mean">What Does On-Premises Mean?</h3>
<p>Before the cloud, most organisations ran their systems on-premises. On-premises means the hardware sits in a building the organisation owns or rents. This could be a server room in their office, with its own staff looking after it.</p>
<p>In this setup, you're responsible for everything. This includes buying servers, setting up the network, installing and updating software, and keeping the room powered and cool.</p>
<p>For example, if a small business wanted to launch an online shop, it would need to buy a server, install the software, and pay someone to keep it running. If the shop grew faster than expected, it would need to buy more hardware.</p>
<h3 id="heading-what-changes-when-you-move-to-the-cloud">What Changes When You Move to the&nbsp;Cloud?</h3>
<p>The cloud moves some of that work to the provider. The physical servers still exist, but someone else owns and maintains them, and you rent what you need.</p>
<p>What differs from one cloud service to the next is <strong>how much of the work the provider takes on for you</strong>. The cloud service models describe this, and there are three main ones:</p>
<ul>
<li><strong>Infrastructure as a Service (or IaaS):</strong> Here the provider gives you virtual servers, storage, and networking. Then you manage everything you put on them.</li>
<li><strong>Platform as a Service (or PaaS):</strong> Here, the provider also manages the operating system and the tools your code needs to run. You bring your application and your data.</li>
<li><strong>Software as a Service (or SaaS)</strong>: In this model, the provider gives you a finished application. You sign in, use it, and manage your users and data.</li>
</ul>
<p>So a cloud service model describes how the work is split between you, the customer, and the provider, that is which parts of the system you manage and which parts the provider manages for you.</p>
<h2 id="heading-the-shared-responsibility-model">The Shared Responsibility Model</h2>
<p>The shared responsibility model defines which parts of a cloud system the provider manages and which parts you, as the customer, manage. To understand it, you first need to see the parts that make up a running application.</p>
<h3 id="heading-the-layers-of-a-computing-stack">The Layers of a Computing Stack</h3>
<p>A computing stack is the set of layers that work together to run an application. Each layer depends on the ones beneath it. From the bottom up, we have:</p>
<ul>
<li>Networking: the physical cables, switches, and routers that connect servers to each other and to the internet.</li>
<li>Storage: the physical drives where files and databases are saved.</li>
<li>Servers: the physical computers that provide processing power (CPU) and memory (RAM).</li>
<li>Virtualisation: software that splits one physical server into several virtual machines, or VMs for short. A VM behaves like a separate computer even though it shares hardware with other VMs.</li>
<li>Operating system: the base software, such as Linux or Windows, that manages the hardware and lets other programs run.</li>
<li>Middleware: software that connects your application to the outside world and to other services, such as a web server that receives requests from browsers.</li>
<li>Runtime: the environment your code needs to run, such as Node.js for JavaScript or the Python interpreter for Python.</li>
<li>Application: the software itself, such as an online shop or an email client.</li>
<li>Data: the information the application stores and processes, such as customer records, orders, and emails.</li>
</ul>
<h3 id="heading-who-manages-what-in-each-model">Who Manages What in Each&nbsp;Model</h3>
<p>AWS describes the split as security “of” the cloud and security “in” the cloud. The provider manages the security of the cloud. This covers the data centres, physical hardware, physical network, and the virtualisation layer.</p>
<p>But security <strong>in</strong> the cloud is the customer's job. It covers what you put into the cloud and how you configure it. This includes your data, your users and their permissions, and the settings of the services you use.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6181007bb368d91070197eba/f1fdda02-613c-447b-9a9e-4cdc8706c969.png" alt="Overview of the cloud service models showing who manages what" style="display: block;" width="1187" height="1068" loading="lazy">

<h2 id="heading-infrastructure-as-a-service-iaas">Infrastructure as a Service&nbsp;(IaaS)</h2>
<p>Infrastructure as a Service is a cloud model where the provider gives you the basic building blocks of computing. This includes virtual servers, storage, and networking.</p>
<h3 id="heading-how-iaas-works">How IaaS&nbsp;Works</h3>
<p>With IaaS, you request a virtual machine from the provider. You choose how many CPUs and how much memory it has, which operating system it runs, and which network it connects to. Within minutes, the VM is running, and you can connect to it.</p>
<p>From that point, the server is yours to manage. You install your software, apply operating system updates, configure the firewall, and keep your application running.</p>
<p>Before IaaS, getting a new server meant ordering hardware and waiting weeks for installation. With IaaS, the same server is ready in minutes, and you can delete it when you no longer need it.</p>
<p>Just remember: <strong>IaaS removes the hardware burden, but it doesn't remove the server burden.</strong></p>
<p>With IaaS, you usually pay for each hour or second a server is running, plus the storage you keep and outbound data transfer.</p>
<h3 id="heading-real-world-examples-include">Real-World Examples include:</h3>
<ul>
<li>Amazon EC2 (Elastic Compute Cloud) on AWS</li>
<li>Google Compute Engine on Google Cloud</li>
<li>Azure Virtual Machines on Microsoft Azure</li>
</ul>
<p>Each of these gives you virtual machines. They work alongside other IaaS building blocks, such as virtual disks (Amazon EBS), storage for files and backups (Amazon S3), and private networks (Amazon VPC).</p>
<h3 id="heading-when-to-use-iaas">When to Use&nbsp;IaaS</h3>
<p>IaaS is the right choice when you need control over the operating system and everything on it, especially when:</p>
<ul>
<li>You need a specific operating system version or software that a managed platform doesn't support.</li>
<li>You need to meet security or compliance rules that require you to configure and audit the server yourself.</li>
<li>You're moving an existing application from your own servers to the cloud without rewriting it. This is often called “lift and shift”.</li>
<li>You need development and test environments that you create and delete often.</li>
</ul>
<h3 id="heading-tradeoffs">Tradeoffs</h3>
<p>As with any system, there are some tradeoffs you should be aware of before selecting this model.</p>
<p>First, you manage the operating system. You handle patching, security updates, and backups, and a missed update can create a security gap.</p>
<p>You also need to plan for scaling. The provider gives you tools to add servers automatically, but you have to set them up and test them.</p>
<p>In addition, you may need to acquire some new skills. Running servers well requires knowledge of Linux or Windows administration, networking, and security.</p>
<p>And you also pay for idle time. A server that runs all night with no traffic still costs money.</p>
<h2 id="heading-platform-as-a-service-paas">Platform as a Service&nbsp;(PaaS)</h2>
<p>Platform as a Service is a cloud model where the provider gives you a ready environment to run your code. The provider manages the servers, operating system, middleware, and runtime. The customer brings the application code and data.</p>
<h3 id="heading-how-paas-works">How PaaS&nbsp;Works</h3>
<p>With IaaS, you still have to prepare a server before your application can run. This includes updating the operating system, setting up a web server, installing the right language version, and keeping it all maintained.</p>
<p>PaaS removes this burden. With PaaS, you tell the platform which language your application uses, then send your code, usually by pushing to Git or uploading a package. The platform builds your application, runs it on managed servers, and gives you a web address. When traffic grows, it can run more copies of your application based on rules you set.</p>
<p>You still decide how much memory your application gets, which settings it uses, and who can deploy it. You just no longer have to log in to servers to patch and maintain them.</p>
<p>With PaaS, you usually pay for the resources your application uses, such as the size and number of running instances, billed by the hour or month.</p>
<h3 id="heading-real-world-examples-include">Real-World Examples include:</h3>
<ul>
<li>Heroku</li>
<li>AWS Elastic Beanstalk</li>
<li>Google App Engine</li>
<li>Azure App Service</li>
</ul>
<p>There are some products that sit between categories. For example, Firebase from Google is often called a PaaS, but it's more accurately a Backend as a Service, or BaaS. A BaaS gives you ready-made backend features, such as a database, user authentication flow, and file storage, that your app calls directly. You don't deploy a whole application to it the way you would on Heroku, for example.</p>
<p>Another is Amazon RDS (Relational Database Service), which is a managed database. AWS runs the database software and backups, while you manage the tables, data, and access. It works like PaaS, but for databases.</p>
<h3 id="heading-when-to-use-paas">When to Use&nbsp;PaaS</h3>
<ul>
<li>You want to launch a web application or API quickly and focus on code.</li>
<li>Your team is small and has nobody dedicated to managing servers.</li>
<li>Your application uses a common language the platform supports, such as Node.js, Python, Java, or&nbsp;.NET.</li>
<li>You want deployments, scaling, and monitoring without building them yourself.</li>
</ul>
<h3 id="heading-tradeoffs">Tradeoffs</h3>
<p>The first tradeoff here is that you have less control. You can't install just any software you want or change operating system settings. Also, if the platform doesn't support something, you have to work around it.</p>
<p>You also risk vendor lock-in. Vendor lock-in means that moving to another provider becomes hard because your application depends on features only one platform offers.</p>
<p>Also, you may pay more at scale. As traffic grows, PaaS can cost more than running the same workload on servers you manage because you pay for the convenience.</p>
<p>And you need to work within platform limits, such as maximum request times or supported language versions.</p>
<p>Finally, you still own your code’s security, including the third-party libraries it uses (and all the risks that come with that).</p>
<h2 id="heading-software-as-a-service-saas">Software as a Service&nbsp;(SaaS)</h2>
<p>Software as a Service is a cloud model where the provider delivers a complete application over the internet. You access it through a web browser or an app, and the provider manages everything needed to keep it running.</p>
<h3 id="heading-how-saas-works">How SaaS&nbsp;Works</h3>
<p>Before SaaS, using business software meant buying a license, installing it on every computer, and updating each one for every new version. For example, if an organisation wanted its own email system, it would need its own email server, someone to run it, and a backup plan.</p>
<p>This is different with SaaS. The provider runs the application on its own infrastructure, and every customer uses the same centrally updated version. You create an account, add your users, and start working. New features and security fixes arrive without you installing anything.</p>
<p>Your work moves from running software to configuring it. You decide who gets an account, what each person can access, and how files are shared.</p>
<p>With SaaS, you usually pay per user per month or per year, often in tiers with more features at higher levels.</p>
<h3 id="heading-real-world-examples-include">Real-World Examples include:</h3>
<ul>
<li>Gmail and Google Workspace, for email, documents, and file storage</li>
<li>Microsoft 365, for Outlook, Word, Excel, and Teams</li>
<li>Slack, for team messaging</li>
<li>Zoom, for video meetings</li>
<li>Dropbox, for file storage and sharing</li>
<li>Salesforce, for managing customers and sales</li>
</ul>
<h3 id="heading-when-to-use-saas">When to Use&nbsp;SaaS</h3>
<ul>
<li>The software solves a common problem that many organisations share, such as email, documents, chat, or accounting.</li>
<li>You don't want to build or run the software yourself.</li>
<li>Your team needs access from anywhere, on any device.</li>
<li>You need the tool working this week, not in six months.</li>
</ul>
<p>For example, say a non-governmental organisation with twenty staff who need professional email, shared documents, and video calls. It has no IT team. With Google Workspace or Microsoft 365, one administrator can set up accounts for every staff member in a day, while the provider handles the servers, updates, and spam filtering.</p>
<h3 id="heading-tradeoffs">Tradeoffs</h3>
<p>With this option, you have the least control. You get the features the provider builds, and if you need something it doesn't offer, you wait or look elsewhere.</p>
<p>Also, your data lives with the provider. You depend on their security, so you need to know where your data is stored and how you can export it if you leave.</p>
<p>Your costs could also easily grow with your team.</p>
<p>Further, you depend on your internet connection. When connectivity is unreliable, a browser-based tool can become unavailable when you need it most.</p>
<p>And you have limited customisation options. Connecting the tool to your other systems depends on what the provider allows.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6181007bb368d91070197eba/3bc84cee-d5c3-4bb5-9dd4-4f9c8072b474.png" alt="Comparison of IaaS, PaaS, and SaaS by control, management effort, cost model, and flexibility." style="display: block;" width="1300" height="834" loading="lazy">

<h2 id="heading-beyond-the-big-three-caas-faas-and-serverless">Beyond the Big Three: CaaS, FaaS, and Serverless</h2>
<p>IaaS, PaaS, and SaaS are the main models, but there are also options like CaaS, FaaS, and serverless. Let’s look at what each means and how it works.</p>
<h3 id="heading-containers-as-a-service-caas">Containers as a Service&nbsp;(CaaS)</h3>
<p>A container packages your application with everything it needs to run, including its runtime, libraries, and settings. Because everything is inside the package, a container runs the same way on your laptop as it does on a server in the cloud. Docker is the most common tool for building containers.</p>
<p>Containers as a Service, or CaaS, is a model where the provider runs and manages containers for you. You give it your container images, and it starts them, restarts them when they fail, and spreads them across servers. The software that makes these decisions is called a container orchestrator, and Kubernetes is the most widely used one.</p>
<p>CaaS sits between IaaS and PaaS. You have more control than on a PaaS, because you decide exactly what goes into each container, but the provider handles much of the work of running them.</p>
<p>Some common examples include:</p>
<ul>
<li>Amazon ECS (Elastic Container Service), which is AWS’s own orchestrator</li>
<li>Amazon EKS (Elastic Kubernetes Service), which is managed Kubernetes on AWS</li>
<li>Google Kubernetes Engine (GKE), which is managed Kubernetes on Google Cloud</li>
</ul>
<p>With ECS and EKS, you may still manage the virtual machines your containers run on, unless you use AWS Fargate, which runs containers without you managing any servers.</p>
<h3 id="heading-functions-as-a-service-faas">Functions as a Service&nbsp;(FaaS)</h3>
<p>Functions as a Service, or FaaS, is a model where you upload small pieces of code called functions, and the provider runs each one only when an event triggers it. An event is something that happens, such as a web request arriving, a file being uploaded, or a scheduled time being reached.</p>
<p>You don't keep a server running while you wait for work. When the event happens, the provider starts your function, runs it, and stops it. You pay per request and for the compute time each run uses, so you pay nothing for compute when nothing happens.</p>
<p>For example, say that an online shop needs to create a small thumbnail every time a seller uploads a product photo. With IaaS, you keep a server running all day to watch for uploads, even at 3 a.m. when nobody is uploading. With FaaS, the upload itself triggers a function that creates the thumbnail, and you pay only for the seconds it runs.</p>
<p>Some common examples include:</p>
<ul>
<li>AWS Lambda</li>
<li>Azure Functions</li>
<li>Google Cloud Run functions, previously called Google Cloud Functions</li>
</ul>
<p>FaaS has trade-offs, too. Each run has a time limit, and an idle function can take a moment longer to start. This is called a cold start.</p>
<h3 id="heading-where-serverless-fits">Where Serverless Fits</h3>
<p>Serverless describes cloud services where you never set up or manage servers, the service scales automatically with demand, and you pay only for what you use rather than for idle capacity.</p>
<p>Serverless isn't a fourth model on the stack. It describes how a service is operated and billed, not which layers you manage. FaaS is serverless, but so are many other managed services, such as Amazon S3 for file storage, Amazon DynamoDB for databases, and AWS Fargate for containers.</p>
<p>Google Cloud Run functions, which are CaaS, also fit into the serverless category.</p>
<h2 id="heading-how-to-choose-the-right-service-model">How to Choose the Right Service&nbsp;Model</h2>
<p>No single model is best for every project. The right choice depends on what you're building, who's building it, and how much control you need.</p>
<p>To help you decide, you can work through these questions in order:</p>
<ul>
<li>Does software that does this job already exist? If yes, start with SaaS.</li>
<li>Are you building your own application in a common language? If yes, look at PaaS first, or FaaS for small tasks that run in response to events.</li>
<li>Is your application already packaged in containers? If yes, CaaS or a serverless container platform may suit you.</li>
<li>Do you need control over the operating system, custom software, or a strict compliance setup? If yes, choose IaaS.</li>
<li>Is your traffic steady or unpredictable? Unpredictable traffic often suits serverless pay-per-use pricing.</li>
</ul>
<p>Start with the most managed model that meets your needs, and move down the stack only when you have a clear reason.</p>
<p>Most production systems combine multiple cloud service models, each serving a different purpose.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>Each service model draws the line between your work and the provider’s at a different point on the stack. IaaS gives you virtual infrastructure, and you manage the operating system and everything above it. PaaS gives you a platform, and you manage your code and data. SaaS gives you a finished application, and you manage your users, data, and settings.</p>
<p>CaaS and FaaS sit between these models, and serverless describes how you operate and pay. In all of them, you (the customer) remain responsible for your data and who can access it.<br><br>Thank you for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Communication Design Patterns for Backend Development ]]>
                </title>
                <description>
                    <![CDATA[ When you’re building the backend of an application, you’ve got to figure out how all the different components are going to talk to each other. It’s like setting up a communication network for your app ]]>
                </description>
                <link>https://www.freecodecamp.org/news/communication-design-patterns-for-backend-development/</link>
                <guid isPermaLink="false">66d45e01bc9760a197a10370</guid>
                
                    <category>
                        <![CDATA[ backend ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Backend Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ design patterns ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Chinwendu Enyinna ]]>
                </dc:creator>
                <pubDate>Tue, 12 Sep 2023 16:25:03 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/09/comm-design-patterns.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When you’re building the backend of an application, you’ve got to figure out how all the different components are going to talk to each other.</p>
<p>It’s like setting up a communication network for your app’s brain, and the way you do it can seriously impact how well your app performs.</p>
<p>But here’s the fun part: there’s no one-size-fits-all answer. The communication pattern you choose depends on what your application needs to do.</p>
<p>So, in this tutorial, we’re going to take a look at five different ways backend systems like to chat it up. We’ll explore what they’re good at and when you should invite them to the conversation. Let’s dive right in!</p>
<h2 id="heading-what-is-a-design-pattern">What is a Design Pattern?</h2>
<p>Before we get into all the cool patterns, let’s talk about what a design pattern is, shall we?</p>
<p><strong>Design patterns</strong> are nifty, tried-and-true reusable solutions to common problems encountered during software design and development. You can call them the cheat codes of software design and development.</p>
<p>They can help provide a structured approach to solving recurring challenges, offering a set of guidelines and best practices that can be adapted for various scenarios.</p>
<p>Now that we’ve got that down, let’s explore five of these emerging design patterns used for backend communication.</p>
<h2 id="heading-request-response-pattern">Request-Response Pattern</h2>
<p>The request-response pattern is a fundamental building block for how the front-end and back-end of web applications chat with each other. This pattern is like a conversation between the client (say your browser) and the server, where they take turns speaking. Imagine it as a “ping-pong” of data.</p>
<p>Here's a diagram illustrating what that looks like:</p>
<img src="https://www.freecodecamp.org/news/content/images/2023/09/Untitled-2023-08-13-1619.png" alt="Image" style="display: block;" width="600" height="400" loading="lazy">

<p><em>request/response communication model</em></p>
<img src="https://cdn-images-1.medium.com/max/800/1*SQDgiDS9Ouqi7tksE9744w.png" alt="Image" style="display: block;" width="600" height="400" loading="lazy">

<h3 id="heading-how-does-the-request-response-pattern-work">How does the Request-Response pattern work?</h3>
<p>This pattern is all about synchronization. The client sends a request to the server, kind of like raising your hand to ask a question in class. Then it patiently waits for the server to respond before it can move on.</p>
<p>It’s like a polite conversation — one speaks, the other listens, and then they swap roles.</p>
<p>You’ve probably heard of RESTful APIs, right? Well, they’re a prime example of the request-response model in action.</p>
<p>When your app needs some data or wants to do something on the server, it crafts an HTTP request — say GET, POST, PUT, or DELETE (like asking nicely for a page), and sends it to specific endpoints (URLs) on the server. The server then processes your request and replies with the data you need or performs the requested action.</p>
<p>It’s like ordering your favorite dish from a menu — you ask, and the kitchen (server) cooks it up for you.</p>
<p>Interestingly, there’s more than one way to have this conversation. Besides REST, there’s GraphQL, an alternative that lets you ask for exactly the data you want. It’s like customizing your order at a restaurant — you get to pick and choose your ingredients.</p>
<p>It’s important to note that this pattern isn’t just limited to web applications. You’ll spot it in Remote Procedure Calls (RPCs), database queries (with the server being the client and the database, the server), and network protocols (HTTP, SMTP, FTP) to name a few. It’s like the language of communication for the web.</p>
<h3 id="heading-benefits-of-the-request-response-pattern">Benefits of the Request-Response pattern</h3>
<p><strong>Ease of Implementation and Simplicity:</strong> The way communication flows in this model is pretty straightforward, making it a go-to choice for many developers, especially when they’re building apps with basic interaction needs.</p>
<p><strong>Flexibility and Adaptability</strong> (One Size Fits Many): The request-response pattern seamlessly fits into a wide range of contexts. You can use it for making API calls, rendering web pages on the server, fetching data from databases, and more.</p>
<p><strong>Scalability:</strong> Each request from the client is handled individually, so the server can easily manage multiple requests at once. This is highly beneficial for high-traffic websites, APIs that get tons of calls, or cloud-based services.</p>
<p><strong>Reliability:</strong> Since the server always sends back a response, the client can be sure its request is received and processed. This helps maintain data consistency and ensures that actions have been executed as intended even during high-traffic scenarios.</p>
<p><strong>Ease of Debugging:</strong> If something goes wrong, the server kindly sends an error message with a status code stating what happened. This makes error handling easy.</p>
<h3 id="heading-limitations-of-the-request-response-pattern">Limitations of the Request-Response Pattern</h3>
<p><strong>Latency Problem:</strong> Because it’s a back-and-forth conversation, there’s often a waiting period. This amounts to idle periods and amplifies latency, especially when the request requires the server to perform time-consuming computing tasks.</p>
<p><strong>Data Inconsistency in Case of Failures:</strong> If a failure occurs after the server has processed the request but before the response is delivered to the client, data inconsistency may result.</p>
<p><strong>Complexity in Real-Time Communication:</strong> For applications that need lightning-fast real-time communication (like live streaming, gaming, or chat apps), this pattern can introduce delays and is therefore unsuitable for these use-cases.</p>
<p><strong>Inefficiency in Broadcasting:</strong> In scenarios where you need to send the same data to multiple clients at once (broadcast), this pattern can be a bit inefficient. It’s like mailing individual letters instead of sending one group message.</p>
<p>Here’s a code example that shows the request-response pattern using Nodejs.</p>
<p>First, we have the <code>server.js</code> file. Here we’ve set up the server to listen for incoming requests from the client.</p>
<pre><code class="language-javascript">const http = require("http");

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

 //check request method and receive data from client
 if (req.method === "POST") {
  let incomingMessage = "";
  req.on("data", (chunk) =&gt; {
   incomingMessage += chunk;
  });

  //write back message received from the client on the console
  req.on("end", () =&gt; {
   console.log(`Message from client: ${incomingMessage}`);
   res.end(`Hello client, message received!`);
  });
 } else {
  res.end("Hey there,  Client!\n");
 }
});

const PORT = 3030;
server.listen(PORT, () =&gt; {
 console.log(
  `Server is listening for incoming request from client on port:${PORT}`
 );
});
</code></pre>
<p>And here's the <code>client.js file</code>:</p>
<pre><code class="language-javascript">const http = require("http");

const options = {
 method: "POST",
 hostname: "localhost",
 port: 3030,
 path: "/",
};

//message to server
let messageToServer = "Hey there, server!";

//send a http request to the server
const req = http.request(options, (res) =&gt; {
 let incomingData = "";

 res.on("data", (chunk) =&gt; {
  incomingData += chunk;
 });

 res.on("end", () =&gt; {
  console.log(`Response from the server: ${incomingData}`);
 });
});

req.on("error", (error) =&gt; {
 console.log(`Error message: ${error.message}`);
});

//send message to the server
req.write(messageToServer);

//end your request
req.end();
</code></pre>
<p>Here's the output:</p>
<img src="https://www.freecodecamp.org/news/content/images/2023/09/Screenshot--173-.png" alt="Image" style="display: block;" width="600" height="400" loading="lazy">

<p><em>code output on the terminal</em></p>
<h2 id="heading-the-publishsubscribe-pattern">The Publish/Subscribe Pattern</h2>
<p>Publish/Subscribe is another communication design pattern you may see on the backend. It is used in distributed systems for asynchronous communication between several (usually decoupled) components. It’s perfect for when you’ve got a bunch of components that need to work together but want to keep their distance.</p>
<p>Here's a diagram showing how it works:</p>
<img src="https://www.freecodecamp.org/news/content/images/2023/09/Untitled-2023-08-13-1619-9.png" alt="Image" style="display: block;" width="600" height="400" loading="lazy">

<p><em>Pub/Sub communication model</em></p>
<h3 id="heading-how-does-the-publishsubscribe-pattern-work">How does the Publish/Subscribe pattern work?</h3>
<p>This pattern involves the use of message queues (often called message brokers) which serve as intermediaries between the publishers and subscribers. These message brokers group messages into something called channels (or topics).</p>
<p>Publishers are the components that create and send messages while subscribers are the components that receive and consume the messages.</p>
<p>The publishers simply toss messages (or events) into specific channels/topics within the message broker. These channels act as the distribution point for the messages. The subscribers then indicate interest by subscribing to those channels within the message broker and whenever a message or event is published to that channel, they receive a copy.</p>
<p>Message queuing tools like Apache Kafka and MQTT use the publish/subscribe communication pattern under the hood.</p>
<h3 id="heading-benefits-of-the-publishsubscribe-pattern">Benefits of the Publish/Subscribe pattern</h3>
<p><strong>Asynchronous Communication:</strong> Unlike the request-response model, pub/sub is designed to be asynchronous by nature. This makes it ideal for building real-time applications with reduced latency bottlenecks.</p>
<p><strong>Loose Coupling of Components:</strong> The components in a publish/subscribe model are loosely coupled. This means that they are not tied together and can freely interact by triggering and responding to events.</p>
<p><strong>Highly Scalable:</strong> There is no limit to the number of subscribers a publisher can publish events to. Also, there’s no limit to the number of publishers subscribers can subscribe to.</p>
<p><strong>Independent of Language and Protocol:</strong> The Pub/Sub model can be easily integrated into any tech stack because it is language-agnostic. Also, it often supports a wide range of environments and platforms making it cross-platform compatible.</p>
<p><strong>Load Balancing:</strong> In cases where multiple subscribers subscribe to a particular event, the pub/sub model can distribute the events evenly among the subscribers, providing load-balancing capabilities out of the box.</p>
<h3 id="heading-limitations-of-the-publishsubscribe-pattern">Limitations of the Publish/Subscribe pattern</h3>
<p><strong>Complexity in Implementation:</strong> Setting up a Pub/Sub system can be more complex than simpler communication models like the request-response pattern. You need to configure and manage message brokers, channels, and subscriptions, which can add overhead to your system.</p>
<p><strong>Message Duplication:</strong> Depending on the configuration and network issues, messages can be duplicated. Subscribers might receive the same message more than once, which can lead to redundancy and extra processing.</p>
<p><strong>Scalability Challenges:</strong> While Pub/Sub is highly scalable, managing extremely high volumes of messages and subscribers can become complex. You might need to consider how to distribute messages efficiently and handle massive numbers of subscribers.</p>
<p><strong>Complex Error Handling:</strong> Dealing with errors in a Pub/Sub system can be challenging. Handling situations like message delivery failures or subscriber errors requires careful consideration and design.</p>
<h3 id="heading-when-should-you-use-it">When should you use it?</h3>
<ul>
<li>In building features that require real-time and low latency responsiveness for the end-users, for example live chat or gaming applications for multiple players.</li>
<li>In event notification systems</li>
<li>In building distributed systems that rely on logging and caching</li>
</ul>
<p>Here’s a code snippet showing a simple pub/sub implementation using the npm package <code>pubsub-js</code><strong>.</strong></p>
<p>Here are the contents of the <code>pubsub.js</code> file:</p>
<pre><code class="language-javascript">const PubSub = require("pubsub-js");

/*
create  a topic of choice.
Any subscriber that subscribes to this topic
receives the published messages
*/
const TOPIC = "chat";

//a function to publish a messgae to subscribers
function publishMessageToSubscribers(message) {
 PubSub.publish(TOPIC, message);
 console.log(`Message Published: ${message}`);
}

let subscriber1 = function (msg, data) {
 console.log(msg, data);
 console.log("subscriber1 received: ", data);
};

let subscriber2 = function (msg, data) {
 console.log(msg, data);
 console.log("subscriber2 received: ", data);
};

// Subscriber1 subscribes to the topic
PubSub.subscribe(TOPIC, subscriber1);

//subscriber2 subscribes to topic
PubSub.subscribe(TOPIC, subscriber2);

publishMessageToSubscribers("Hello subscriber!");

console.log("Subscriber 1 is listening....");

console.log("Subscriber 2 is listening....");
</code></pre>
<p>Here's the output:</p>
<img src="https://www.freecodecamp.org/news/content/images/2023/09/Screenshot--180-.png" alt="Image" style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-the-short-polling-pattern">The Short Polling Pattern</h2>
<p>Short polling is another communication pattern that facilitates data exchange between client and server. It uses the <strong>pull-based</strong> communication mechanism (which is basically the client pulling data from the backend) to continuously poll the server for new updates.</p>
<h3 id="heading-how-does-short-polling-work">How does Short Polling work?</h3>
<p>Imagine you’re waiting for a message from a friend, and you don’t want to miss it. What do you do? You keep asking, “Got a message for me yet?”</p>
<p>So, the client makes a request to the server at regular (fixed) intervals (say every x unit of time) to check for new data or updates. The server sends back a response and if there’s new available data or an update, the server includes the data in the response.</p>
<p>Here’s what the client-server communication would look like:</p>
<ul>
<li>Client: “Hey, server, any new messages?”</li>
<li>Server: “Nah, nothing yet.”</li>
<li>Client: “Alright, I’ll check back later.”</li>
<li>[Some time passes…]</li>
<li>Client: “Hey, server, any new messages?”</li>
<li>Server: “Bingo! Here they are!”</li>
</ul>
<p>Although polling has some similarities with the request-response model we discussed earlier, a key difference between them is <strong>timing</strong>.</p>
<p>While polling occurs at regular, predefined intervals regardless of whether updates are available, the request-response model allows clients to request data or actions on-demand when needed, reducing unnecessary communication.</p>
<h3 id="heading-benefits-of-polling">Benefits of Polling</h3>
<p><strong>Simplicity:</strong> Polling is easy to understand and implement and it’s completely stateless between the client and server. This makes it perfect for scenarios where the complexities need to be minimized.</p>
<p><strong>Compatibility:</strong> It can be used with a wide range of technologies and protocols which makes it highly compatible with a number of platforms and environments.</p>
<p>Some example use cases of polling pattern includes simple dashboards, weather apps that require periodic updates, resource monitoring, or in cases where you’re considering cross-platform compatibility.</p>
<h3 id="heading-limitations-of-polling">Limitations of Polling</h3>
<p><strong>Latency:</strong> Polling introduces latency, as clients must wait for predefined intervals before receiving updates. This can lead to delays in accessing real-time data or receiving notifications.</p>
<p><strong>Inefficiency:</strong> Constantly polling the server for updates can be inefficient and can result in unnecessary network and server overhead.</p>
<p><strong>Scaling:</strong> Handling a large number of simultaneous clients using polling can be resource-intensive for the server. It may require significant server resources to manage numerous concurrent polling requests.</p>
<p>Here's a code snippet to illustrate short polling. Here, the client sends a periodic request(polls ) to the server to check for upload progress.</p>
<p>The <code>app.js</code> file:</p>
<pre><code class="language-javascript">const express = require("express");

const app = express();

//create a dictionary to store the upload progress
const uploadStatus = {};

//simulate upload of file
app.post("/upload", (req, res) =&gt; {
 //create a unique request id for incoming request
 const requestId = Math.floor(Math.random() * 1000000);
 uploadStatus[requestId] = 0;

 simulateUploadProgress(requestId);

 res.json({ requestId });
});

//endpoint to check upload progress
app.get("/status/:requestId", (req, res) =&gt; {
 const requestId = parseInt(req.params.requestId);

 if (!isNaN(requestId) &amp;&amp; uploadStatus[requestId] !== undefined) {
  if (uploadStatus[requestId] === 100) {
   //upload completed
   res.json({ progress: 100, message: "UPLOAD COMPLETED!" });
  } else {
   // upload still in progress
   res.json({ progress: uploadStatus[requestId] });
  }
 } else {
  res.status(404).json({ error: "Request ID not found" });
 }
});

//update upload progress by 10% every 5 secs
function simulateUploadProgress(requestId) {
 if (uploadStatus[requestId] &lt; 100) {
  setTimeout(() =&gt; {
   uploadStatus[requestId] += 10;
   simulateUploadProgress(requestId);
  }, 5000);
 }
}
const PORT = 4000;

app.listen(PORT, () =&gt; {
 console.log(`Server is running on port ${PORT}`);
});
</code></pre>
<p>Here's the output in the terminal</p>
<img src="https://www.freecodecamp.org/news/content/images/2023/09/Screenshot--189--1.png" alt="Image" style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-the-long-polling-pattern">The Long Polling Pattern</h2>
<p>Long polling is like polling but uses a <strong>push-based</strong> communication mechanism. In long polling, instead of the client asking the server, “Any updates?” all the time, it says, “Let me know when something’s up.”</p>
<h3 id="heading-heres-how-long-polling-works">Here’s how Long Polling works:</h3>
<p>The client pings the server, just like in regular polling, but this time, the server doesn’t immediately answer. It holds the connection open, like keeping a phone line on hold. When there’s something to share, it responds. It’s like the server’s saying, “Hey, I’ll call you when I have news.”</p>
<p>It is used in web applications to achieve real-time or near-real-time updates between a client and a server.</p>
<h3 id="heading-benefits-of-the-long-polling-pattern">Benefits of the Long Polling Pattern</h3>
<p><strong>Low Latency:</strong> Long polling provides low latency when compared to traditional polling as data is immediately sent back to clients as soon as they are available.</p>
<p><strong>Real-Time Updates:</strong> With the long polling technique, applications can achieve real-time updates without the need for constantly polling the server.</p>
<h3 id="heading-limitations-of-the-long-polling-pattern">Limitations of the Long Polling Pattern</h3>
<p><strong>Resource Intensive:</strong> Long polling requires keeping many connections open. As a result, it can be resource-consuming on both the server and client side.</p>
<p><strong>Increased Latency:</strong> Although long polling helps cut down on frequent polling, it can still introduce latency when compared to other real-time communication protocols like Web Socket. Clients may experience delays between updates since they have to wait for the server to respond.</p>
<p><strong>Difficult to Scale:</strong> When dealing with a large number of concurrent clients, long polling can strain server resources. As more clients establish long-polling connections, the server may struggle to manage and respond to all these connections efficiently.</p>
<p>Typical use cases of long polling include real-time updates, event-driven applications, and event notification systems.</p>
<p>Here's a code snippet to illustrate the concept of long polling where the client waits for updates from the server.</p>
<pre><code class="language-javascript">const express = require("express");
const app = express();

const uploadStatus = {};

app.post("/upload", (req, res) =&gt; {
 const requestId = Math.floor(Math.random() * 1000000);
 uploadStatus[requestId] = 0;

 updateUploadProgress(requestId, uploadStatus[requestId]);

 res.json({ requestId });
});

app.get("/status/:requestId", async (req, res) =&gt; {
 const requestId = parseInt(req.params.requestId);

 //simulate long polling (the server will not respond until done)
 while ((await checkUploadComplete(requestId)) === false);
 res.end("\n\n Upload status: completed " + uploadStatus[requestId]);
});

//update progress by 20% after every 5 seconds
function updateUploadProgress(requestId, progress) {
 uploadStatus[requestId] = progress;
 console.log(`Updated progress to ${progress}`);
 if (progress === 100) return;
 this.setTimeout(() =&gt; updateUploadProgress(requestId, progress + 20), 5000);
}

//check upload status
function checkUploadComplete(requestId) {
 return new Promise((resolve, reject) =&gt; {
  if (uploadStatus[requestId] &lt; 100) {
   this.setTimeout(() =&gt; resolve(false), 1000);
  } else {
   resolve(true);
  }
 });
}
const PORT = 4000;

app.listen(PORT, () =&gt; {
 console.log(`Server is running on port ${PORT}`);
});
</code></pre>
<p>And here's the output in the terminal.</p>
<img src="https://www.freecodecamp.org/news/content/images/2023/09/Screenshot--188-.png" alt="Image" style="display: block;" width="600" height="400" loading="lazy">

<p><em>code output</em></p>
<div class="embed-wrapper"><iframe width="560" height="315" src="https://www.youtube.com/embed/QDvSPKZzf1s" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>

<h2 id="heading-the-push-pattern">The Push Pattern</h2>
<p>Push is a communication model that is used to deliver real-time updates to connected clients.</p>
<p>In this model, the client opens a connection to the server and awaits messages or updates from the server. Whenever there is a new update or message, the server immediately <strong>pushes</strong> that update to the client without the client explicitly requesting it — as long it is connected.</p>
<p>This model allows for bidirectional communication between the client and server. Web sockets, a popular protocol, uses the push model as its underlying data exchange method.</p>
<p>The Push model provides the most real-time or near real-time end-user experience when compared to other closely related paradigms such as polling and long polling.</p>
<p>To explain how the push pattern works, imagine a chat room with multiple connected users as an example. The client and server conversation will look like this:</p>
<ul>
<li>user1 (client): “Hello…”</li>
<li>Server: “Oh, user1 has a message!” <em>Instantly sends it to everyone else in the room.</em></li>
<li>User2 (client): <em>Gets the message from user1 without doing anything.</em></li>
<li>User3 (client): <em>Also receives the message from user1 — no need to refresh or ask for it.</em></li>
</ul>
<p>In the example above, the push pattern enables real-time communication such that whenever there’s a message from a client in the chat room, it pushes the message to all other connected clients in that room without them having to continuously poll or request updates.</p>
<p>Popular technologies that uses the push pattern are RabbitMQ and WebSocket.</p>
<h3 id="heading-benefits-of-push-pattern">Benefits of Push Pattern</h3>
<p><strong>Real-Time Updates:</strong> The push model allows clients to receive updates from the server as soon as they are available. This is key, especially in applications where real-time updates are crucial.</p>
<p><strong>Reduced Latency:</strong> Since the server pushes updates to the client as soon as they are available, it potentially reduces the latency.</p>
<p><strong>Efficiency:</strong> Because there is no need for continuous polling or frequent client requests, there is efficient use of network resources and reduced server load.</p>
<p>While the push model is widely adopted as the best fit for providing real-time updates, it does have its own disadvantages.</p>
<h3 id="heading-limitations-of-push-pattern">Limitations of Push Pattern</h3>
<p><strong>Scalability:</strong> It can become difficult to scale as the number of connected clients increases. At this point, it becomes resource-intensive, especially on the server side since the server needs to maintain open connections with multiple clients.</p>
<p><strong>Client support:</strong> Some clients might not be able to handle pushed messages as not all client platforms support push technologies. This may lead to compatibility issues and may need some sort of fallback mechanism for unsupported clients.</p>
<p>Some example use cases of the push pattern include chat and messaging apps, notification systems, IoT data streaming, and online gaming, to name a few.</p>
<p>Here’s a simple Node.js code example to illustrate the push pattern using Web Sockets. To run the code, you have to install the <code>ws</code> library using <code>npm</code>.</p>
<pre><code class="language-javascript">//create a server - this server will push updates to the clients at intervals
const WebSocket = require("ws");
const server = new WebSocket.Server({ port: 8080 });

server.on("connection", (client) =&gt; {
 console.log("Client connected to server");

 //Simulate client to receive real-time updates from the server every 2 seconds
 const interval = setInterval(() =&gt; {
  const message = `Message received at: ${new Date().toLocaleTimeString()}`;
  client.send(message);
 }, 2000);

 // Handle client disconnection
 client.on("close", () =&gt; {
  clearInterval(interval);
  console.log("Client disconnected");
 });
});

// Client (listens for updates from server)
const clientSocket = new WebSocket("ws://localhost:8080");

clientSocket.onmessage = (event) =&gt; {
 console.log(`Message from server: "${event.data}"`);
};
</code></pre>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>In this tutorial, we explored five key communication design patterns: Request-Response, Publish/Subscribe, Short Polling, Long Polling, and Push.</p>
<p>Each pattern has its unique strengths and limitations which makes them suitable for various use cases.</p>
<p>Depending on your application’s goal, understanding these patterns will help you design efficient backend systems.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Regular Expressions in JavaScript – Tutorial for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ Regular expressions (regex) are a useful programming tool. They are key to efficient text processing. Knowing how to solve problems using regex is helpful to you as a developer and improves your produ ]]>
                </description>
                <link>https://www.freecodecamp.org/news/regular-expressions-for-beginners/</link>
                <guid isPermaLink="false">66d45e03f855545810e93419</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Regex ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Regular Expressions ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Chinwendu Enyinna ]]>
                </dc:creator>
                <pubDate>Tue, 16 Aug 2022 17:51:48 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/08/regex-image-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Regular expressions (regex) are a useful programming tool. They are key to efficient text processing. Knowing how to solve problems using regex is helpful to you as a developer and improves your productivity.</p>
<p>In this article, you will learn about the fundamentals of regular expressions, regular expression pattern notation, how you can interpret a simple regex pattern, and how to write your own regex pattern. Let’s get to it!</p>
<h2 id="heading-what-are-regular-expressions">What Are Regular Expressions?</h2>
<p>Regular expressions are patterns that allow you to describe, match, or parse text. With regular expressions, you can do things like find and replace text, verify that input data follows the format required, and and other similar things.</p>
<p>Here's a scenario: you want to verify that the telephone number entered by a user on a form matches a format, say, ###-###-#### (where # represents a number). One way to solve this could be:</p>
<pre><code class="language-js">function isPattern(userInput) {
  if (typeof userInput !== 'string' || userInput.length !== 12) {
    return false;
  }
  for (let i = 0; i &lt; userInput.length; i++) {
    let c = userInput[i];
    switch (i) {
      case 0:
      case 1:
      case 2:
      case 4:
      case 5:
      case 6:
      case 8:
      case 9:
      case 10:
      case 11:
        if (c &lt; 0 || c &gt; 9) return false;
        break;
      case 3:
      case 7:
        if (c !== '-') return false;
        break;
    }
  }
  return true;
}
</code></pre>
<p>Alternatively, we can use a regular expression here like this:</p>
<pre><code class="language-js">function isPattern(userInput) {
  return /^\d{3}-\d{3}-\d{4}$/.test(userInput);
}
</code></pre>
<p>Notice how we’ve refactored the code using regex. Amazing right? That is the power of regular expressions.</p>
<h2 id="heading-how-to-create-a-regular-expression">How to Create A Regular Expression</h2>
<p>In JavaScript, you can create a regular expression in either of two ways:</p>
<ul>
<li>Method #1: using a regular expression literal. This consists of a pattern enclosed in forward slashes. You can write this with or without a flag (we will see what flag means shortly). The syntax is as follows:</li>
</ul>
<pre><code class="language-js">const regExpLiteral = /pattern/;          // Without flags

const regExpLiteralWithFlags = /pattern/; // With flags
</code></pre>
<p>The forward slashes <code>/…/</code> indicate that we are creating a regular expression pattern, just the same way you use quotes <code>“ ”</code> to create a string.</p>
<ul>
<li>Method #2: using the RegExp constructor function. The syntax is as follows:</li>
</ul>
<pre><code class="language-js">new RegExp(pattern [, flags])
</code></pre>
<p>Here, the pattern is enclosed in quotes, the same as the flag parameter, which is optional.</p>
<p>So when do you use each of these pattern?</p>
<p>You should use a regex literal when you know the regular expression pattern at the time of writing the code.</p>
<p>On the other hand, use the Regex constructor if the regex pattern is to be created dynamically. Also, the regex constructor lets you write a pattern using a template literal, but this is not possible with the regex literal syntax.</p>
<h3 id="heading-what-are-regular-expression-flags">What are Regular Expression Flags?</h3>
<p>Flags or modifiers are characters that enable advanced search features including case-insensitive and global searching. You can use them individually or collectively. Some commonly used ones are:</p>
<ul>
<li><code>g</code> is used for global search which means the search will not return after the first match.</li>
<li><code>i</code> is used for case-insensitive search meaning that a match can occur regardless of the casing.</li>
<li><code>m</code> is used for multiline search.</li>
<li><code>u</code> is used for Unicode search.</li>
</ul>
<p>Let’s look at some regular expression patterns using both syntaxes.</p>
<h4 id="heading-how-to-use-a-regular-expression-literal">How to use a regular expression literal:</h4>
<pre><code class="language-js">// Syntax: /pattern/flags

const regExpStr = 'Hello world! hello there';

const regExpLiteral = /Hello/gi;

console.log(regExpStr.match(regExpLiteral));

// Output: ['Hello', 'hello']
</code></pre>
<p>Note that if we did not flag the pattern with <code>i</code>, only <code>Hello</code> will be returned.</p>
<p>The pattern <code>/Hello/</code> is an example of a simple pattern. A simple pattern consists of characters that must appear literally in the target text. For a match to occur, the target text must follow the same sequence as the pattern.</p>
<p>For example, if you re-write the text in the previous example and try to match it:</p>
<pre><code class="language-js">const regExpLiteral = /Hello/gi;

const regExpStr = 'oHell world, ohell there!';

console.log(regExpStr.match(regExpLiteral));

// Output: null
</code></pre>
<p>We get <em>null</em> because the characters in the string do not appear as specified in the pattern. So a literal pattern such as <code>/hello/</code>, means <em>h</em> followed by <em>e</em> followed by <em>l</em> followed by <em>l</em> followed by <em>o</em>, exactly like that.</p>
<h4 id="heading-how-to-use-a-regex-constructor">How to use a regex constructor:</h4>
<pre><code class="language-js">// Syntax: RegExp(pattern [, flags])

const regExpConstructor = new RegExp('xyz', 'g'); // With flag -g

const str = 'xyz xyz';

console.log(str.match(regExpConstructor));

// Output: ['xyz', 'xyz']
</code></pre>
<p>Here, the pattern <code>xyz</code> is passed in as a string same as the flag. Also both occurrences of <code>xyz</code> got matched because we passed in the -g flag. Without it, only the first match will be returned.</p>
<p>We can also pass in dynamically created patterns as template literals using the constructor function. For example:</p>
<pre><code class="language-js">const pattern = prompt('Enter a pattern');
// Suppose the user enters 'xyz'

const regExpConst = new RegExp(`${pattern}`, 'gi');

const str = 'xyz XYZ';

console.log(str.match(regExpConst)); // Output: ['xyz', 'XYZ']
</code></pre>
<h2 id="heading-how-to-use-regular-expression-special-characters">How to Use Regular Expression Special Characters</h2>
<p>A <strong>special</strong> <strong>character</strong> in a regular expression is a character with a reserved meaning. Using special characters, you can do more than just find a direct match.</p>
<p>For example, if you want to match a character in a string that may or may not appear once or multiple times, you can do this with special characters. These characters fit into different subgroups that perform similar functions.</p>
<p>Let's take a look at each subgroup and the characters that go with them.</p>
<h3 id="heading-anchors-and-boundaries">Anchors and Boundaries:</h3>
<p><strong>Anchors</strong> are metacharacters that match the start and end of a line of text they are examining. You use them to assert where a boundary should be.</p>
<p>The two characters used are <code>^</code> and <code>$</code>.</p>
<ul>
<li><code>^</code> matches the start of a line and anchors a literal at the beginning of that line. For example:</li>
</ul>
<pre><code class="language-js">const regexPattern1 = /^cat/;

console.log(regexPattern1.test('cat and mouse')); // Output: true

console.log(regexPattern1.test('The cat and mouse')); // Output: false because the line does not start with cat

// Without the ^ in the pattern, the output will return true
// because we did not assert a boundary.

const regexPattern2 = /cat/;

console.log(regexPattern2.test('The cat and mouse')); // Output: true
</code></pre>
<ul>
<li><code>$</code> matches the end of a line and anchors a literal at the end of that line. For example:</li>
</ul>
<pre><code class="language-js">const regexPattern = /cat$/;

console.log(regexPattern.test('The mouse and the cat')); // Output: true

console.log(regexPattern.test('The cat and mouse')); // Output: false
</code></pre>
<p>Note that anchors characters <code>^</code> and <code>$</code> <strong>match just the position of the characters in the pattern</strong> and not the actual characters themselves.</p>
<p><strong>Word Boundaries</strong> are metacharacters that match the start and end position of a word – a sequence of alphanumeric characters. You can think of them as a word-based version of <code>^</code> and <code>$</code>. You use the metacharacters <code>b</code> and <code>B</code> to assert a word boundary.</p>
<ul>
<li><code>\b</code> matches the start or end of a word. The word is matched according to the position of the metacharacter. Here's an example:</li>
</ul>
<pre><code class="language-js">// Syntax 1: /\b.../ where .... represents a word.

// Search for a word that begins with the pattern ward
const regexPattern1 = /\bward/gi;

const text1 = 'backward Wardrobe Ward';

console.log(text1.match(regexPattern1)); // Output: ['Ward', 'Ward']

// Syntax 2: /...\b/

// Search for a word that ends with the pattern ward
const regexPattern2 = /ward\b/gi;

const text2 = 'backward Wardrobe Ward';

console.log(text2.match(regexPattern2)); // Output: ['ward', 'Ward']

// Syntax 3: /\b....\b/

// Search for a stand-alone word that begins and end with the pattern ward
const regexPattern3 = /\bward\b/gi;

const text3 = 'backward Wardrobe Ward';

console.log(text3.match(regexPattern3)); // Output: ['Ward']
</code></pre>
<ul>
<li><code>\B</code> is opposite of <code>\b</code> . It matches every position <code>\b</code> doesn't.</li>
</ul>
<h3 id="heading-shortcodes-for-other-metacharacters">Shortcodes for Other Metacharacters:</h3>
<p>In addition to the metacharacters we have looked at, here are some of the most commonly used ones:</p>
<ul>
<li><code>\d</code> – matches any decimal digit and is shorthand for [0-9].</li>
<li><code>\w</code> – matches any alphanumeric character which could be a letter, a digit, or an underscore. <code>\w</code> is shorthand for [A-Za-z0-9_].</li>
<li><code>\s</code> – matches any white space character.</li>
<li><code>\D</code> – matches any non-digit and is the same as [^0-9.]</li>
<li><code>\W</code> – matches any non-word (that is non-alphanumeric) character and is shorthand for [^A-Za-z0-9_].</li>
<li><code>\S</code> – matches a non-white space character.</li>
<li><code>.</code> – matches any character.</li>
</ul>
<h3 id="heading-what-is-a-character-class">What is a Character Class?</h3>
<p>A character class is used to match any one of several characters in a particular position. To denote a character class, you use square brackets <code>[]</code> and then list the characters you want to match inside the brackets.</p>
<p>Let's look at an example:</p>
<pre><code class="language-js">// Find and match a word with two alternative spellings

const regexPattern = /ambi[ea]nce/;

console.log(regexPattern.test('ambiance')); // Output: true

console.log(regexPattern.test('ambiance')); // Output: true

// The regex pattern interprets as:  find a followed by m, then b,
// then i, then either e or a, then n, then c, and then e.
</code></pre>
<h3 id="heading-what-is-a-negated-character-class">What is a Negated Character Class?</h3>
<p>If you add a caret symbol inside a character class like this <code>[^...]</code>, it will match any character that is not listed inside the square brackets. For example:</p>
<pre><code class="language-js">const regexPattern = /[^bc]at/;

console.log(regexPattern.test('bat')); // Output: false

console.log(regexPattern.test('cat')); // Output: false

console.log(regexPattern.test('mat')); // Output: true
</code></pre>
<h3 id="heading-what-is-a-range">What is a Range?</h3>
<p>A hyphen <code>-</code> indicates range when used inside a character class. Suppose you want to match a set of numbers, say [0123456789], or a set of characters, say[abcdefg]. You can write it as a range like this, [0-9] and [a-g], respectively.</p>
<h3 id="heading-what-is-alternation">What is Alternation?</h3>
<p>Alternation is yet another way you can specify a set of options. Here, you use the pipe character <code>|</code> to match any of several subexpressions. Either of the subexpressions is called an <strong>alternative</strong>.</p>
<p>The pipe symbol means ‘or’, so it matches a series of options. It allows you combine subexpressions as alternatives.</p>
<p>For example, <code>(x|y|z)a</code> will match <code>xa</code> or <code>ya</code>, or <code>za</code>. In order to limit the reach of the alternation, you can use parentheses to group the alternatives together.</p>
<p>Without the parentheses, <code>x|y|za</code> would mean <code>x</code> or <code>y</code> or <code>za</code>. For example:</p>
<pre><code class="language-js">const regexPattern = /(Bob|George)\sClan/;

console.log(regexPattern.test('Bob Clan')); // Output: true

console.log(regexPattern.test('George Clan')); // Output: true
</code></pre>
<h3 id="heading-what-are-quantifiers-and-greediness">What are Quantifiers and Greediness?</h3>
<p>Quantifiers denote how many times a character, a character class, or group should appear in the target text for a match to occur. Here are some peculiar ones:</p>
<ul>
<li><code>+</code> will match any character it is appended to if the character appears at least once. For example:</li>
</ul>
<pre><code class="language-js">const regexPattern = /hel+o/;

console.log(regexPattern.test('helo'));          // Output:true

console.log(regexPattern.test('hellllllllllo')); // Output: true

console.log(regexPattern.test('heo'));           // Output: false
</code></pre>
<ul>
<li><code>*</code> is similar to the + character but with a slight difference. When you append * to a character, it means you want to match any number of that character including none. Here’s an example:</li>
</ul>
<pre><code class="language-js">const regexPattern = /hel*o/;

console.log(regexPattern.test('helo'));    // Output: true

console.log(regexPattern.test('hellllo')); // Output: true

console.log(regexPattern.test('heo'));     // Output: true

// Here the * matches 0 or any number of 'l'
</code></pre>
<ul>
<li><code>?</code> implies "optional". When you append it to a character, it means the character may or may not appear. For example:</li>
</ul>
<pre><code class="language-js">const regexPattern = /colou?r/;

console.log(regexPattern.test('color'));  // Output: true

console.log(regexPattern.test('colour')); // Output: true

// The ? after the character u makes u optional
</code></pre>
<ul>
<li><code>{N}</code>, when appended to a character or character class, specifies how many of the character we want. For example <code>/\d{3}/</code> means match three consecutive digits.</li>
<li><code>{N,M}</code> is called the interval quantifier and is used to specify a range for the minimum and maximum possible match. For example <code>/\d{3, 6}/</code> means match a minimum of 3 and a maximum of 6 consecutive digits.</li>
<li><code>{N, }</code> denotes an open-ended range. For example <code>/\d{3, }/</code> means match any 3 or more consecutive digits.</li>
</ul>
<h3 id="heading-what-is-greediness-in-regex">What is Greediness in Regex?</h3>
<p>All quantifiers by default are <strong>greedy</strong>. This means that they will try to match all possible characters.</p>
<p>To remove this default state and make them non-greedy, you append a <code>?</code> to the operator like this <code>+?</code>, <code>*?</code>, <code>{N}?</code>, <code>{N,M}?</code>.....and so on.</p>
<h3 id="heading-what-are-grouping-and-backreferencing">What are Grouping and Backreferencing?</h3>
<p>We previously looked at how we can limit the scope of alternation using the parentheses.</p>
<p>What if you want to use a quantifier like <code>+</code> or <code>*</code> on more than one character at a time – say a character class or group? You can group them together as a whole using the parentheses before appending the quantifier, just like in this example:</p>
<pre><code class="language-js">const regExp = /abc+(xyz+)+/i;

console.log(regExp.test('abcxyzzzzXYZ')); // Output: true
</code></pre>
<p>Here's what the pattern means: The first + matches the c of abc, the second + matches the z of xyz, and the third + matches the subexpression xyz, which will match if the sequence repeats.</p>
<p><strong>Backreferencing</strong> allows you to match a new pattern that is the same as a previously matched pattern in a regular expression. You also use parentheses for backreferencing because it can remember a previously matched subexpression it encloses (that is, the captured group).</p>
<p>However, it is possible to have more than one captured group in a regular expression. So, to backreference any of the captured group, you use a number to identify the parentheses.</p>
<p>Suppose you have 3 captured groups in a regex and you want to backreference any of them. You use <code>\1</code>, <code>\2</code>, or <code>\3</code>, to refer to the first, second, or third parentheses. To number the parentheses, you start counting the open parentheses from the left.</p>
<p>Let's look at some examples:</p>
<p><code>(x)</code> matches x and remembers the match.</p>
<pre><code class="language-js">const regExp = /(abc)bar\1/i;

// abc is backreferenced and is anchored at the same position as \1
console.log(regExp.test('abcbarAbc')); // Output: true

console.log(regExp.test('abcbar')); // Output: false
</code></pre>
<p><code>(?:x)</code> matches x but does not recall the match. Also, \n (where n is a number) does not remember a previously captured group, and will match as a literal. Using an example:</p>
<pre><code class="language-js">const regExp = /(?:abc)bar\1/i;

console.log(regExp.test('abcbarabc')); // Output: false

console.log(regExp.test('abcbar\1')); // Output: true
</code></pre>
<h3 id="heading-the-escape-rule">The Escape Rule</h3>
<p>A metacharacter has to be escaped with a backslash if you want it to appear as a literal in your regular expression. By escaping a metacharacter in regex, the metacharacter loses its special meaning.</p>
<h2 id="heading-regular-expression-methods">Regular Expression Methods</h2>
<h3 id="heading-the-test-method">The <code>test()</code> method</h3>
<p>We have used this method a number of times in this article. The <code>test()</code> method compares the target text with the regex pattern and returns a boolean value accordingly. If there is a match, it returns true, otherwise it returns false.</p>
<pre><code class="language-js">const regExp = /abc/i;

console.log(regExp.test('abcdef')); // Output: true

console.log(regExp.test('bcadef')); // Output: false
</code></pre>
<h3 id="heading-the-exec-method">The <code>exec()</code> method</h3>
<p>The <code>exec()</code> method compares the target text with the regex pattern. If there's a match, it returns an array with the match – otherwise it returns null. For example:</p>
<pre><code class="language-js">const regExp = /abc/i;

console.log(regExp.exec('abcdef'));
// Output: ['abc', index: 0, input: 'abcdef', groups: undefined]

console.log(regExp.exec('bcadef'));
// Output: null
</code></pre>
<p>Also, there are string methods that accept regular expressions as a parameter like <code>[match()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match)</code>, <code>[replace()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)</code>, <code>[replaceAll()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll)</code>, <code>[matchAll()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll)</code>, <code>[search()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search)</code>, and <code>[split()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split)</code>.</p>
<h2 id="heading-regex-examples">Regex Examples</h2>
<p>Here are some examples to reinforce some of the concepts we've learned in this article.</p>
<p>First example: How to use a regex pattern to match an email address:</p>
<pre><code class="language-js">const regexPattern = /^[(\w\d\W)+]+@[\w+]+\.[\w+]+$/i;

console.log(regexPattern.test('abcdef123@gmailcom'));
// Output: false, missing dot

console.log(regexPattern.test('abcdef123gmail.'));
// Output: false, missing end literal 'com'

console.log(regexPattern.test('abcdef123@gmail.com'));
// Output: true, the input matches the pattern correctly
</code></pre>
<p>Let's interpret the pattern. Here's what's happening:</p>
<ul>
<li><code>/</code> represents the start of the regular expression pattern.</li>
<li><code>^</code> checks for the start of a line with the characters in the character class.</li>
<li><code>**[(\w\d\W)+ ]+**</code> matches any word, digit and non-word character in the character class at least once. Notice how the parentheses were used to group the characters before adding the quantifier. This is same as this <code>[\w+\d+\W+]+</code> .</li>
<li><code>**@**</code> matches the literal @ in the email format.</li>
<li><code>**[\w+]+**</code> matches any word character in this character class at least once.</li>
<li><code>**\.**</code> escapes the dot so it appears as a literal character.</li>
<li><code>**[\w+]+$**</code> matches any word character in this class. Also this character class is anchored at the end of the line.</li>
<li><code>**/**</code> - ends the pattern</li>
</ul>
<p>Alright, next example: how to match a URL with format <a href="http://example.com">http://example.com</a> or <a href="https://www.example.com">https://www.example.com</a>:</p>
<pre><code class="language-js">const pattern = /^[https?]+:\/\/((w{3}\.)?[\w+]+)\.[\w+]+$/i;

console.log(pattern.test('https://www.example.com'));
// Output: true

console.log(pattern.test('http://example.com'));
// Output: true

console.log(pattern.test('https://example'));
// Output: false
</code></pre>
<p>Let's also interpret this pattern. Here's what's happening:</p>
<ul>
<li><code>/...../</code> represents the start and end of the regex pattern</li>
<li><code>^</code> asserts for the start of the line</li>
<li><code>[https?]+</code> matches the characters listed at least once, however <code>?</code> makes 's' optional.</li>
<li><code>:</code> matches a literal semi-colon.</li>
<li><code>\/\/</code> escapes the two forward slashes.</li>
<li><code>(w{3}\.)</code> matches the character w 3 times and the dot that follows immediately. However, this group is optional.</li>
<li><code>[\w+]+</code> matches character in this class at least once.</li>
<li><code>\.</code> escapes the dot</li>
<li><code>[\w+]+$</code> matches any word character in this class. Also this character class is anchored at the end of the line.</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we looked at the fundamentals of regular expressions. We also explained some regular expression patterns, and practiced with a few examples.</p>
<p>There's more to regular expressions beyond this article. To help you learn more about regular expressions, here are some resources you can read through:</p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">Regular Expression</a></li>
<li><a href="https://www.freecodecamp.org/news/regular-expressions-crash-course/">Learn Regex crash course</a></li>
<li><a href="https://www.regular-expressions.info/tutorial.html">Regular Expression Tutorial</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Cheatsheet">Regular Expression Cheatsheet</a></li>
</ul>
<p>And that's all for this tutorial. Happy coding :)</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What are Functions in JavaScript? A Beginner's Guide ]]>
                </title>
                <description>
                    <![CDATA[ Functions are one of the fundamental concepts in programming. They let us write concise, modular, reusable, and maintainable code. They also help us obey the DRY principle when writing code. In this a ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-are-functions-in-javascript-a-beginners-guide/</link>
                <guid isPermaLink="false">66d45e04230dff01669057b5</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Chinwendu Enyinna ]]>
                </dc:creator>
                <pubDate>Thu, 30 Jun 2022 20:32:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/06/banner-image-for-functions-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Functions are one of the fundamental concepts in programming. They let us write concise, modular, reusable, and maintainable code. They also help us obey the DRY principle when writing code.</p>
<p>In this article, you will learn what functions are in JavaScript, how to write your own custom functions, and how to implement them.</p>
<p>As a prerequisite, you should be familiar with some fundamental JavaScript concepts such as variables, expressions, and conditional statements to follow along with this article.</p>
<h2 id="heading-what-is-a-function-in-javascript">What is a Function in JavaScript?</h2>
<p>A function is a block of reusable code written to perform a specific task.</p>
<p>You can think of a function as a sub-program within the main program. A function consists of a set of statements but executes as a single unit.</p>
<p>In JavaScript, we have some browser built-in functions like alert(), prompt(), and confirm(). You have probably used these in your project before, right? But you can still create your own custom functions.</p>
<p>There are several ways to define a function. Most commonly, we have function declaration and function expression.</p>
<h2 id="heading-how-to-define-a-function-using-function-declaration">How to Define a Function using Function Declaration</h2>
<p>You write a function declaration like this:</p>
<pre><code class="language-javascript">function nameOfFunction() {
	//some code here....
}
</code></pre>
<p>Basically, it consists of the following:</p>
<ul>
<li>Function keyword</li>
<li>The name of the function</li>
<li>Parentheses (which can take in parameters, or also be empty)</li>
<li>The body of the function (wrapped in curly braces).</li>
</ul>
<p>Here's an example:</p>
<pre><code class="language-javascript">function sayHello() {
	console.log("Hello world"); 
}
</code></pre>
<p>This function won't do a thing – in this case, output <em>Hello world</em> – unless you call it. The term for this is <em>invoking the function.</em></p>
<p>Here’s how to call the function:</p>
<pre><code class="language-javascript">sayHello();

//output: Hello world
</code></pre>
<p>Here’s another example:</p>
<pre><code class="language-javascript">function sum(num1, num2){
	return num1 + num2;
}
</code></pre>
<p>To invoke this function, we call it like this:</p>
<pre><code class="language-javascript">sum(1, 2);

//output: 3
</code></pre>
<p>You can see a slight difference between our first function example and the second.</p>
<p>If you guessed that it's the content within the parenthesis of the second function, then you’re right!</p>
<p>The function <code>sum()</code> took in two parameters when we defined it – <code>num1</code>, and <code>num2</code>. And when we call it, we passed in two values – the arguments, <code>1</code> and <code>2</code>. Let me explain what these two terms (parameters and arguments) mean.</p>
<p>A <strong>parameter</strong> is a variable you pass to a function when you declare it.</p>
<p>Suppose you want your function to be dynamic, so that it applies the function’s logic to different sets of data at different times. That’s where parameters come in handy. This way, your function doesn’t just output the same result repeatedly. Instead, its result is dependent on the data you pass in.</p>
<p>An <strong>argument</strong>, on the other hand, is the value equivalent to the parameter that you pass to the function when you call it.</p>
<p>So the syntax for declaring a function with parameters will look like this:</p>
<pre><code class="language-javascipt">function nameOfFunction(parameters){
	//function body.....
}
</code></pre>
<p>And to invoke it:</p>
<pre><code class="language-javascript">nameOfFunction(arguments)
</code></pre>
<h2 id="heading-how-to-define-a-function-using-a-function-expression">How to Define a Function using a Function Expression</h2>
<p>A function expression is another notation for defining a function. In terms of syntax, it is similar to the function declaration. But function expressions allow you to define a named function or omit the function name to create an anonymous function.</p>
<p>Let’s see what a function expression looks like:</p>
<pre><code class="language-javascript">let namedFunction = function myFunction(){
	//some code here...
}
</code></pre>
<p>Notice that in this example, the function has a name, <code>myFunction</code>. This is not the case with the anonymous function. When defining an anonymous function, you omit the function name just like in this example below:</p>
<pre><code class="language-javascript">let anonymousFunction = function(){
	//some code here...
}
</code></pre>
<p>You can see that both function examples are assigned to a variable, right?</p>
<p><strong>A function keyword creates a function value that can be assigned to a variable when it is used as an expression</strong>.</p>
<p>So, to invoke this function, we call it using the variable name which serves as the new function name.</p>
<p>One major difference between the function declaration and function expression is that, with function declaration, you can invoke the function even before defining it. This is not possible with function expressions.</p>
<p>For example:</p>
<pre><code class="language-javascript">console.log(greeting());

function greeting(){
  console.log("Hope you're are good?");

}
//output: Hope you're good?
</code></pre>
<p>This won’t work if the function is defined as a function expression because the function expression follows a top-to-bottom control flow sequence.</p>
<h2 id="heading-how-to-use-arrow-functions-in-javascript">How to Use Arrow Functions in JavaScript</h2>
<p>Arrow functions are yet another notation of a function expression but they have a shorter syntax. They were introduced in ES6 and help us write cleaner code.</p>
<p>Here, the function keyword is excluded and we use an arrow symbol (=&gt;) instead. The syntax looks like this:</p>
<pre><code class="language-javascript">let nameOfFunction = (parameters) =&gt; {
	//function body
}
</code></pre>
<p>If the function body within the curly braces contains only a single statement, then the braces can be omitted. An arrow function with curly braces must include the return keyword.</p>
<h2 id="heading-what-are-immediately-invoked-function-expressions-iifes"><strong>What are Immediately Invoked Function Expressions (IIFEs)?</strong></h2>
<p>IIFE is another function expression notation (explicitly an anonymous function) that works in isolation and is independent of any other code. It gets invoked immediately where it is defined.</p>
<p>The syntax is as follows:</p>
<pre><code class="language-javascript">(function (){
	//function body
})();
</code></pre>
<p>A use case of IIFE would be to enclose a variable that you may likely not use again inside your code. So, as soon as the function is executed, the variable ceases to exist.</p>
<h2 id="heading-how-to-use-the-return-keyword-in-a-function"><strong>How to Use the Return Keyword in a Function</strong></h2>
<p>To create a function that will resolve to a value after the function is invoked, you use the return keyword. You write this within the body of the function.</p>
<p><code>return</code> is a directive that returns a value to the function after the code within it has been executed.</p>
<p>Here’s an example of a function that returns a value, in this case, the sum of two numbers:</p>
<pre><code class="language-javascript">function sum(a, b){
	return  a + b;
}

sum(10, 20);

//output will be 30
</code></pre>
<p>Using <code>return</code> inside a function makes it easy to manipulate the data the function returns, by either passing it as a value to, say, another function, or performing additional operations on it.</p>
<h2 id="heading-how-do-function-scope-and-closures-work-in-javascript"><strong>How Do Function S</strong>cope and Closures** Work in JavaScript?**</h2>
<p>A scope is a nested namespace that localizes the names created within it such that these names don’t interfere with similar names created outside of that scope. There are certain scope rules that apply within a function.</p>
<p>Each new function you define creates a new scope known as the <strong>function scope</strong>. Variables created within the function scope are not visible or accessible outside of that scope.</p>
<p>Nevertheless, variables created outside the function scope but within the scope in which the function is defined can be accessed inside the function. Therefore, if you define a function in global scope, it can access all variables declared in that global scope.</p>
<p>Also, suppose you have a child function (that is, an inner function) nested inside a parent function (which is the outer function). The child function can access all variables and functions declared in its parent function as well as all variables and functions the parent function has access to – even when its parent function has finished executing and its variables are no longer accessible outside that function. This concept is known as closures in JavaScript.</p>
<p>However, the parent function cannot access the variables created inside the child function. In this way, the variables and functions inside the child function are confined to their own scope.</p>
<p>Let’s see a code example of this:</p>
<pre><code class="language-javascript">//variables defined in the global scope

let  a = 40;
let b = 20;

//this function is also defined in the global scope

function parentFunc(){
	//access variables a and b inside this function

	console.log(a + b); 
}

//output: 60
</code></pre>
<p>Suppose I nest an inner function inside the parent function, like this:</p>
<pre><code class="language-javascript">//variables defined in the global scope

let a = 40;
let b = 20;

//this function is also defined in the global scope

function parentFunc(){
	let  name = “Doe”;
    
    //this inner function is defined inside the parent function scope
    
	function childFunc(){
		console.log(`${name} is ${a - b} years old`); 
      }
    return childFunc();
}

parentFunc(); //ouput: Doe is 20 years old
</code></pre>
<p>Now, if I create a variable inside a function and try to access it from the global scope, we will get a reference error. This is because that variable is local to the function scope and is not visible to the global scope.</p>
<pre><code class="language-javascript">console.log(c);

function parentFunc(){
	let c = 30
} 

//output: reference error - c is not defined
</code></pre>
<p>Let’s try to access a variable created inside a nested function in the parent function:</p>
<pre><code class="language-javascript">function parentFunc(){
	console.log(age);
	function childFunc(){
		let  age = 20;
	} 
    return childFunc();
}

parentFunc(); //output: reference error - age is not defined.
</code></pre>
<h2 id="heading-how-do-default-parameters-work-in-javascript">How Do Default Parameters Work in JavaScript?</h2>
<p>Originally, function parameters are assigned <em>undefined</em> when no value is explicitly passed to them. Default parameters let you assign a default value to a parameter when you define a function. For example:</p>
<pre><code class="language-javascript">function greeting(name, message = ”Hello”){
	console. log(`${messgae}  ${name}`)
}

greeting(‘John’); //output: Hello John

//you can also assign a new value to the default parameter 
//when you call the function

greeting(‘Doe’, ‘Hi’); //output: Hi Doe
</code></pre>
<p>It is important to note that in declaring a default parameter, it must come after the regular parameter.</p>
<h2 id="heading-how-do-rest-parameters-work-in-javascript"><strong>How Do Rest Parameters Work in JavaScript?</strong></h2>
<p>With rest parameters, you can define a function to store multiple arguments in a single array. This is particularly useful when you're invoking your function with multiple arguments. Here's an example:</p>
<pre><code class="language-javascript">function sayHello(message, ...names){
  names.forEach(name =&gt; console.log(`${message} ${name}`));
}

sayHello('Hello', "John", "Smith", "Doe");

/*
output:

Hello John

Hello Smith

Hello Doe 

*/


</code></pre>
<p>The <code>...</code> is what makes <code>names</code> a rest parameter.</p>
<p>Just like default parameters, rest parameters should appear after any regular parameter in your function.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you learned what functions in JavaScript are all about and how you can write your own functions.</p>
<p>With functions, you can organize your code by grouping everything into separate blocks that perform different tasks.</p>
<p>I hope you enjoyed reading this article. To learn more about functions, here are some resources you can check out:</p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions">JavaScript Functions</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">Closures</a></li>
</ul>
<p>That's all for this piece. Happy coding :)</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
