<?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[ Flavio Copes - 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[ Flavio Copes - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Wed, 06 May 2026 11:21:27 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/flaviocopes/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Git Cheat Sheet – Helpful Git Commands with Examples ]]>
                </title>
                <description>
                    <![CDATA[ This Git Cheat Sheet will provide you with a handy list of common (and not so common) commands that will make your life easier when working with Git. You can also download the Git Cheat Sheet in PDF format (along with some other resources) for free b... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/git-cheat-sheet-helpful-git-commands-with-examples/</link>
                <guid isPermaLink="false">66c4ac87a052a51b9b7eb096</guid>
                
                    <category>
                        <![CDATA[ Git ]]>
                    </category>
                
                    <category>
                        <![CDATA[ GitHub ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Gitcommands ]]>
                    </category>
                
                    <category>
                        <![CDATA[ #codenewbies ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Programming Tips ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Flavio Copes ]]>
                </dc:creator>
                <pubDate>Tue, 20 Aug 2024 14:47:35 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723993272242/896730cc-3e03-43be-83d9-06d37ebab5a5.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>This Git Cheat Sheet will provide you with a handy list of common (and not so common) commands that will make your life easier when working with Git.</p>
<p>You can also download the Git Cheat Sheet in PDF format (along with some other resources) for free by joining my newsletter at <a target="_blank" href="https://flaviocopes.com/access/">flaviocopes.com/access</a>.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-preface"><strong>Preface</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-basic-git-commands"><strong>Basic Git Commands</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-working-directory-and-the-staging-area"><strong>The Working Directory and the Staging Area</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-working-with-branches"><strong>Working with Branches</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-merging-in-git"><strong>Merging in Git</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-git-remotes"><strong>Git Remotes</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-amending-commits"><strong>Amending Commits</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-stashing-in-git"><strong>Stashing in Git</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-git-tagging"><strong>Git Tagging</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-reverting-changes-in-git"><strong>Reverting Changes in Git</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-viewing-history-logs"><strong>Viewing History Logs</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-git-diffs"><strong>Git Diffs</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-git-flow"><strong>Git Flow</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-exploring-git-references"><strong>Exploring Git References</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-configure-git"><strong>How to Configure Git</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-git-security"><strong>Git Security</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-set-aliases-in-git"><strong>How to Set Aliases in Git</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-rebasing-in-git"><strong>Rebasing in Git</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-cherry-picking"><strong>What is Cherry-Picking?</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-patching-in-git"><strong>Patching in Git</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-relative-dates-in-git"><strong>Relative Dates in Git</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-git-blame"><strong>Git Blame</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-archiving-in-git"><strong>Archiving in Git</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-track-files-in-git"><strong>How to Track Files in Git</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-index-manipulation-in-git"><strong>Index Manipulation in Git</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-squashing-in-git"><strong>Squashing in Git</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-data-integrity-in-git"><strong>Data Integrity in Git</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-cleaning-up-in-git"><strong>Cleaning Up in Git</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-git-subtree"><strong>Git Subtree</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-search-in-git"><strong>How to Search in Git</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-bisecting-in-git"><strong>Bisecting in Git</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-git-attributes"><strong>Git Attributes</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-git-checkout-2"><strong>Git Checkout</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-git-reflog"><strong>Git Reflog</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-handle-untracked-files-in-git"><strong>How to Handle Untracked Files in Git</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-force-pushing-in-git"><strong>Force Pushing in Git</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-git-fetching-and-pulling"><strong>Git Fetching and Pulling</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-handle-merge-conflicts-in-git"><strong>How to Handle Merge Conflicts in Git</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-working-trees-in-git"><strong>Working Trees in Git</strong></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-submodules-in-git"><strong>Submodules in Git</strong></a></p>
</li>
</ul>
<h2 id="heading-preface">Preface</h2>
<p>Welcome to this Git Cheat Sheet! It's an extensive guide I created to help empower both novice and seasoned developers with the knowledge you need to effectively utilize Git, the most popular version control system in the software industry.</p>
<p>This cheat sheet is designed to be your go-to resource, whether you're managing a solo project or collaborating within a large team. By providing clear explanations and practical examples, it should help demystify Git's complexities and transform them into intuitive, actionable insights.</p>
<p>Throughout this guide, you will explore a wide array of Git commands and concepts that form the backbone of software version control. From fundamental operations like initializing repositories and committing changes, to more advanced techniques such as branching, merging, and rebasing, this cheat sheet covers it all.</p>
<p>You'll also delve into specialized topics like squashing commits, bisecting to debug, handling submodules, and implementing subtrees. All this will help ensure that you're well-prepared to tackle any challenge that arises in your development process.</p>
<p>As you progress, you'll learn how to maintain data integrity, manage multiple working trees, and resolve merge conflicts efficiently. By the end, you'll not only have a deeper understanding of Git but also the confidence to use it to streamline your workflow and enhance collaboration with peers.</p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<p>To fully benefit from this cheat sheet, you should have a foundational knowledge of command-line operations and general programming principles. You should also be familiar with using a terminal or command prompt so you can better understand and apply the examples provided. Finally, having a basic grasp of version control concepts will enhance your ability to navigate through this guide effectively.</p>
<h2 id="heading-basic-git-commands"><strong>Basic Git Commands</strong></h2>
<p>In this section, you'll learn the fundamental Git commands that serve as the building blocks for efficiently managing and navigating your Git repositories.</p>
<p>Git is a distributed version control system that's essential for tracking changes in your codebase, collaborating with other developers, and maintaining the integrity of your project history. Understanding these basic commands is crucial for anyone looking to leverage the full power of Git in their development workflow.</p>
<p>We'll explore a variety of commands that cover key aspects of Git usage, such as initializing new repositories, committing changes, branching, and merging.</p>
<p>Each command is explained with a short sentence that describes its purpose along with its syntax, so you can effectively use it in real-world scenarios. Whether you're setting up a new project or working on an existing codebase, these commands will help you keep your work organized and maintain a seamless workflow.</p>
<h3 id="heading-git-help"><code>git help</code></h3>
<p>The <code>git help</code> command prints Git help information. It provides a quick reference to Git's basic usage and the most commonly used Git commands. This command is useful when you need a quick reminder of Git's functionality or want to explore available commands.</p>
<p>You can also use <code>git help &lt;command&gt;</code> to display help information for any specific Git command. For example, <code>git help git</code> prints the Git help specifically for the Git command itself.</p>
<p>These help commands are valuable resources for both beginners and experienced users to quickly access information about Git's features and usage.</p>
<h3 id="heading-git-version"><code>git version</code></h3>
<p>The <code>git version</code> command displays the version of Git installed on your system. This command is useful for verifying which version of Git you are currently using, which can be important for compatibility with certain features or when troubleshooting issues.</p>
<h3 id="heading-git-init"><code>git init</code></h3>
<p>The command <code>git init</code> is used to initialize a new Git repository in the current directory. This command creates a new subdirectory named <code>.git</code> that contains all the necessary metadata for the new repository. It's typically the first command you run when starting a new project that you want to manage with Git.</p>
<p>After running this command, you can begin tracking files and making commits in your new Git repository.</p>
<h3 id="heading-git-clone"><code>git clone &lt;repository_url&gt;</code></h3>
<p>The <code>git clone &lt;repository_url&gt;</code> command creates a copy of a remote Git repository on your local machine. It downloads all the files, branches, and commit history, allowing you to start working with the project immediately.</p>
<h3 id="heading-git-status"><code>git status</code></h3>
<p>The <code>git status</code> command shows the current state of the Git repository's working directory and staging area. It displays information about which files have been modified, added, or deleted, and whether these changes are staged for the next commit.</p>
<h2 id="heading-the-working-directory-and-the-staging-area"><strong>The Working Directory and the Staging Area</strong></h2>
<p>The working directory and the staging area are fundamental concepts in Git that play crucial roles in the version control process.</p>
<p>The working directory is the environment where you actively make changes to your files, representing the current state of your project. It is essentially a sandbox where you can freely edit, delete, and create files as you develop your project. But these changes are local to your machine and not yet part of the version history.</p>
<p>On the other hand, the staging area, also known as the index, serves as an intermediary space between the working directory and the repository. It acts as a checkpoint where you can selectively organize changes before they are committed to the repository's history. This allows you to prepare a set of changes that are logically related, ensuring that each commit is meaningful and coherent.</p>
<p>The commands below will help you manage changes between the working directory and the staging area. They'll let you add files to the staging area, remove them, or modify the existing ones, giving you control over what will be included in the next commit.</p>
<p>By using these commands, you can ensure that only the intended updates are committed, making your project's history clear and organized. This process is essential for maintaining a clean and understandable history, as it allows you to track the evolution of your project with precision and clarity.</p>
<h3 id="heading-git-checkout"><code>git checkout .</code></h3>
<p>This command discards all changes in the working directory, reverting files to their last committed state. This command is useful for quickly undoing local modifications and restoring the working directory to a clean state.</p>
<h3 id="heading-git-reset-p"><code>git reset -p</code></h3>
<p>This command allows you to interactively reset changes in the working directory. It provides a way to selectively undo modifications, giving you fine-grained control over which changes to keep or discard.</p>
<h3 id="heading-git-add"><code>git add &lt;file&gt;</code></h3>
<p>This command adds a specific file to the staging area in Git. This prepares the file for inclusion in the next commit, allowing you to selectively choose which changes to include in your version history.</p>
<h3 id="heading-git-add-p"><code>git add -p</code></h3>
<p>Allows you to interactively stage changes from your working directory by breaking them into chunks (hunks). This lets you review and selectively add parts of the changes to the index before committing.</p>
<h3 id="heading-git-add-i"><code>git add -i</code></h3>
<p>Enters the interactive mode of adding files. Provides a text-based interactive menu where you can select various actions to perform, such as staging individual changes, updating files, or viewing the status.</p>
<h3 id="heading-git-rm"><code>git rm &lt;file&gt;</code></h3>
<p>Removes a file from the working directory and stages the removal.</p>
<h3 id="heading-git-rm-cached"><code>git rm --cached &lt;file&gt;</code></h3>
<p>Removes the specified file from the staging area (index) but leaves it intact in your working directory. This effectively un-tracks the file from version control.</p>
<h3 id="heading-git-mv"><code>git mv &lt;old_path&gt; &lt;new_path&gt;</code></h3>
<p>This command is used to move or rename a file or directory within a Git repository. It automatically stages the change, making it ready for the next commit.</p>
<h3 id="heading-git-commit-m-message"><code>git commit -m "message"</code></h3>
<p>This command is used to create a new commit in your Git repository. It saves the changes that have been staged (added to the index) along with a descriptive message. This message should briefly explain what changes were made in this commit.</p>
<h2 id="heading-working-with-branches"><strong>Working with Branches</strong></h2>
<p>Git branches are parallel lines of development within a Git repository. They allow you to work on different features, bug fixes, or experiments independently from the main codebase.</p>
<p>Each branch can have its own commit history, and changes made in one branch do not affect others until they are merged. This helps you organize your work, and facilitates collaboration by enabling multiple developers to work on different aspects of a project simultaneously without interfering with each other's progress.</p>
<p>In this section we'll introduce commands that allow you to create, switch, list, rename, and delete branches in your Git repository. These commands help manage parallel lines of development, enabling you to work on different features or bug fixes independently. You'll also learn how to display commit histories and branch relationships, as well as manage remote branches.</p>
<h3 id="heading-git-branch"><code>git branch &lt;branch_name&gt;</code></h3>
<p>Creates a new branch.</p>
<h3 id="heading-git-checkout-1"><code>git checkout &lt;branch_name&gt;</code></h3>
<p>Switches to the specified branch and updates the working directory.</p>
<h3 id="heading-git-branch-1"><code>git branch</code></h3>
<p>Lists all branches.</p>
<h3 id="heading-git-branch-d"><code>git branch -d &lt;branch_name&gt;</code></h3>
<p>Deletes a branch.</p>
<h3 id="heading-git-push-delete"><code>git push --delete &lt;remote&gt; &lt;branch&gt;</code></h3>
<p>Deletes a remote branch.</p>
<h3 id="heading-git-branch-m"><code>git branch -m &lt;old_name&gt; &lt;new_name&gt;</code></h3>
<p>Renames a branch.</p>
<h3 id="heading-git-checkout-b"><code>git checkout -b &lt;new_branch&gt;</code></h3>
<p>Creates and switches to a new branch named <code>&lt;new_branch&gt;</code>, based on the current branch.</p>
<h3 id="heading-git-switch"><code>git switch &lt;branch&gt;</code></h3>
<p>Switches the working directory to the specified branch.</p>
<h3 id="heading-git-show-branch"><code>git show-branch &lt;branch&gt;</code></h3>
<p>Displays a summary of the commit history and branch relationships for all or selected branches, showing where each branch diverged.</p>
<h3 id="heading-git-show-branch-all"><code>git show-branch --all</code></h3>
<p>Same as above, but for all branches and their commits.</p>
<h3 id="heading-git-branch-r"><code>git branch -r</code></h3>
<p>Lists all remote branches that your local repository is aware of.</p>
<h3 id="heading-git-branch-a"><code>git branch -a</code></h3>
<p>Lists all branches in your repository, including both local and remote branches (the ones the local repository is aware of).</p>
<h3 id="heading-git-branch-merged"><code>git branch --merged</code></h3>
<p>Lists all branches that have been fully merged into the current branch, and can be safely deleted if no longer needed.</p>
<h3 id="heading-git-branch-no-merged"><code>git branch --no-merged</code></h3>
<p>Lists all branches that have not been fully merged into your current branch, showing branches with changes that haven't been integrated yet.</p>
<h2 id="heading-merging-in-git"><strong>Merging in Git</strong></h2>
<p>The git merge command is used to combine the changes from one branch into another branch. It integrates the histories of both branches, creating a new commit that includes the changes from both sources.</p>
<p>This process allows multiple lines of development to be brought together, facilitating collaboration and ensuring that all updates are incorporated into the main project.</p>
<p>During a merge, conflicts may arise if changes overlap, requiring manual resolution to ensure a coherent final result.</p>
<h3 id="heading-git-merge"><code>git merge &lt;branch&gt;</code></h3>
<p>Integrates the changes from the specified branch into your current branch, combining their histories.</p>
<h3 id="heading-git-merge-no-ff"><code>git merge --no-ff &lt;branch&gt;</code></h3>
<p>Merges the specified branch into your current branch, always creating a new merge commit even if a fast-forward merge is possible.</p>
<h3 id="heading-git-merge-squash"><code>git merge --squash &lt;branch&gt;</code></h3>
<p>Combines all the changes from the specified branch into a single commit, preparing the changes for a commit in the current branch without merging the branch’s history. This allows you to manually edit the commit message.</p>
<h3 id="heading-git-merge-abort"><code>git merge --abort</code></h3>
<p>Cancels an ongoing merge process and restores the state of your working directory and index to what it was before the merge started.</p>
<h3 id="heading-git-merge-s-ours-or"><code>git merge -s ours &lt;branch&gt;</code> or</h3>
<h3 id="heading-git-merge-strategyours"><code>git merge —-strategy=ours &lt;branch&gt;</code></h3>
<p>These commands are functionally the same, but the second is the expanded (more explicit) version, while <code>git merge -s ours &lt;branch&gt;</code> is the shorthand version (which is commonly used). You'll see this a few times throughout this guide.</p>
<p>The <code>git merge —-strategy=ours &lt;branch&gt;</code> command (<code>git merge -s ours &lt;branch&gt;</code> for short) performs a merge using the "ours" strategy, which keeps the current branch's changes and discards changes from the specified branch. This effectively merges the histories without integrating the changes from the other branch.</p>
<h3 id="heading-git-merge-strategytheirs"><code>git merge --strategy=theirs &lt;branch&gt;</code></h3>
<p>Merges the specified branch into the current branch using the "theirs" strategy, which resolves all conflicts by favoring changes from the branch being merged. Note that the "theirs" strategy is not a built-in strategy and usually requires custom scripting or is used with tools to handle conflict resolution.</p>
<h2 id="heading-git-remotes"><strong>Git Remotes</strong></h2>
<p>Git remotes are references to remote repositories, which are versions of your project hosted on the internet or another network. They enable collaboration by allowing multiple users to share and sync changes with a central repository.</p>
<p>Common operations with remotes include <code>git fetch</code> to retrieve updates, <code>git pull</code> to fetch and merge changes, and <code>git push</code> to upload local commits to the remote repository.</p>
<p>Managing remotes involves adding, removing, and renaming remote connections, as well as configuring URLs for seamless collaboration.</p>
<h3 id="heading-git-fetch"><code>git fetch</code></h3>
<p>Fetches changes from a remote repository but does not merge them into your current branch.</p>
<h3 id="heading-git-pull"><code>git pull</code></h3>
<p>Fetches changes from a remote repository and immediately merges them into your current branch.</p>
<h3 id="heading-git-push"><code>git push</code></h3>
<p>Uploads your local branch's changes to a remote repository.</p>
<h3 id="heading-git-remote"><code>git remote</code></h3>
<p>Lists the names of remote repositories configured for your local repository.</p>
<h3 id="heading-git-remote-v"><code>git remote -v</code></h3>
<p>Displays the URLs of the remote repositories associated with your local repository, showing both the fetched and pushed URLs.</p>
<h3 id="heading-git-remote-add"><code>git remote add &lt;name&gt; &lt;url&gt;</code></h3>
<p>Adds a new remote repository with the specified name and URL to your local repository configuration.</p>
<h3 id="heading-git-remote-remove-or"><code>git remote remove &lt;name&gt;</code> or</h3>
<h3 id="heading-git-remote-rm"><code>git remote rm &lt;name&gt;</code></h3>
<p>Deletes the specified remote repository connection from your local git configuration. <code>git remote rm &lt;name&gt;</code> is the shorthand version of the command.</p>
<h3 id="heading-git-remote-rename"><code>git remote rename &lt;old_name&gt; &lt;new_name&gt;</code></h3>
<p>Changes the name of an existing remote repository connection in your local Git configuration</p>
<h3 id="heading-git-remote-set-url"><code>git remote set-url &lt;name&gt; &lt;newurl&gt;</code></h3>
<p>Changes the URL of an existing remote repository connection in your local Git configuration.</p>
<h3 id="heading-git-fetch-1"><code>git fetch &lt;remote&gt;</code></h3>
<p>Retrieves the latest changes from the specified remote repository, updating your local copy of the remote branches without merging them into your local branches.</p>
<h3 id="heading-git-pull-1"><code>git pull &lt;remote&gt;</code></h3>
<p>Fetches changes from the specified remote repository and merges them into your current branch.</p>
<h3 id="heading-git-remote-update"><code>git remote update</code></h3>
<p>Fetches updates for all remotes tracked by the repository.</p>
<h3 id="heading-git-push-1"><code>git push &lt;remote&gt; &lt;branch&gt;</code></h3>
<p>Uploads the specified branch from your local repository to the given remote repository.</p>
<h3 id="heading-git-push-delete-1"><code>git push &lt;remote&gt; --delete &lt;branch&gt;</code></h3>
<p>Removes the specified branch from the remote repository.</p>
<h3 id="heading-git-remote-show"><code>git remote show &lt;remote&gt;</code></h3>
<p>Displays detailed information about the specified remote repository, including its URL, fetch and push configurations, and the branches it tracks.</p>
<h3 id="heading-git-ls-remote"><code>git ls-remote &lt;repository&gt;</code></h3>
<p>Lists references (such as branches and tags) and their commit IDs from the specified remote repository. This command allows you to view the branches and tags available in a remote repository without cloning it.</p>
<h3 id="heading-git-push-origin-set-upstream"><code>git push origin &lt;branch&gt; --set-upstream</code></h3>
<p>Pushes the local branch &lt;branch&gt; to the remote repository origin and sets up the local branch to track the remote branch. This lets future git push and git pull commands default to this remote branch.</p>
<h3 id="heading-git-remote-add-upstream"><code>git remote add upstream &lt;repository&gt;</code></h3>
<p>Adds a new remote named upstream to your local repository, pointing to the specified &lt;repository&gt;. This is commonly used to track the original repository from which you forked, while origin typically refers to your own fork.</p>
<h3 id="heading-git-fetch-upstream"><code>git fetch upstream</code></h3>
<p>Retrieves updates from the upstream remote repository, updating your local references to the branches and tags from that remote without modifying your working directory or merging changes.</p>
<h3 id="heading-git-pull-upstream"><code>git pull upstream &lt;branch&gt;</code></h3>
<p>Fetches updates from the &lt;branch&gt; of the upstream remote repository and merges those changes into your current branch. This is often used to integrate changes from the original repository into your own local branch.</p>
<h3 id="heading-git-push-origin"><code>git push origin &lt;branch&gt;</code></h3>
<p>Uploads the local branch &lt;branch&gt; to the origin remote repository, making your branch and its commits available on the remote.</p>
<h2 id="heading-amending-commits"><strong>Amending Commits</strong></h2>
<p>Amending Git commits allows you to modify the most recent commit, typically to correct or update its contents or message. You can do this using the <code>git commit --amend</code> command, which opens the commit in your default text editor for changes.</p>
<p>Amending is particularly useful for fixing small mistakes or adding forgotten changes without creating a new commit, resulting in a cleaner and more accurate commit history.</p>
<h3 id="heading-git-commit-amend"><code>git commit --amend</code></h3>
<p>Modifies the most recent commit, combining staged changes.</p>
<h3 id="heading-git-commit-amend-m-new-message"><code>git commit --amend -m "new message"</code></h3>
<p>Amends the commit message of the most recent commit.</p>
<h3 id="heading-git-commit-fixuphead"><code>git commit --fixup=HEAD</code></h3>
<p>Creates a new commit with the <code>--fixup</code> option that is intended to correct or amend the most recent commit (HEAD). The new commit is marked with a <code>fixup!</code> prefix in the commit message and will be used to automatically fix or amend the specified commit during an interactive rebase.</p>
<h2 id="heading-stashing-in-git"><strong>Stashing in Git</strong></h2>
<p>Git stashing is a feature that allows you to temporarily save changes in your working directory that are not yet ready to be committed.</p>
<p>By using the git stash command, you can set aside these changes and revert your working directory to a clean state, enabling you to switch branches or perform other tasks without losing progress. Later, you can reapply the stashed changes with git stash apply or git stash pop, allowing you to continue where you left off.</p>
<p>This functionality is especially useful for managing work in progress when you need to address an urgent issue or experiment with a different code path.</p>
<h3 id="heading-git-stash"><code>git stash</code></h3>
<p>Temporarily saves your uncommitted changes, allowing you to switch branches or perform other operations without committing incomplete work.</p>
<p>There's an older version, <code>git stash save</code>, that allows you to specify a custom message. But it's largely been deprecated in favor of the simpler <code>git stash</code>.</p>
<h3 id="heading-git-stash-m-message"><code>git stash -m "message"</code></h3>
<p>Same as above, but stores changes with a message. It also has an older version, <code>git stash save "message"</code>, but <code>git stash -m "message"</code> is preferred for versions of Git 2.13 and newer.</p>
<h3 id="heading-git-stash-show"><code>git stash show</code></h3>
<p>Displays a summary of the changes in the most recent stash entry, showing which files were modified.</p>
<h3 id="heading-git-stash-list"><code>git stash list</code></h3>
<p>Shows all the stashed changes in your repository, displaying them in a numbered list.</p>
<h3 id="heading-git-stash-pop"><code>git stash pop</code></h3>
<p>Applies the most recent stash and then immediately removes it from the stash list.</p>
<h3 id="heading-git-stash-drop"><code>git stash drop</code></h3>
<p>Removes the most recent stash entry from the stash list without applying it to your working directory.</p>
<h3 id="heading-git-stash-apply"><code>git stash apply</code></h3>
<p>Reapplies the most recently stashed changes to your working directory without removing them from the stash list.</p>
<h3 id="heading-git-stash-clear"><code>git stash clear</code></h3>
<p>Clears and removes all stashed entries, permanently deleting all saved changes in your stash.</p>
<h3 id="heading-git-stash-branch"><code>git stash branch &lt;branch&gt;</code></h3>
<p>Creates a new branch named &lt;branch&gt; from the commit where you were before stashing your changes. Then it applies the stashed changes to that new branch.</p>
<p>This command effectively allows you to continue working on your stashed changes in a separate branch, preserving the original context and changes.</p>
<h2 id="heading-git-tagging"><strong>Git Tagging</strong></h2>
<p>Git tagging is a feature that allows you to mark specific points in your repository's history as important with a meaningful name, often used for releases or significant milestones.</p>
<p>Unlike branches, tags are typically immutable and do not change, serving as a permanent reference to a particular commit.</p>
<p>There are two types of tags in Git: lightweight tags, which are simple pointers to a commit, and annotated tags, which store additional metadata like the tagger's name, email, date, and a message.</p>
<p>Tags can be easily created, listed, pushed to remote repositories, and deleted, providing a convenient way to manage and reference key points in your project's development timeline.</p>
<h3 id="heading-git-tag"><code>git tag &lt;tag_name&gt;</code></h3>
<p>Creates a new tag with the specified name pointing to the current commit (typically used to mark specific points in the commit history, like releases).</p>
<h3 id="heading-git-tag-a-m-message"><code>git tag -a &lt;tag_name&gt; -m "message"</code></h3>
<p>Creates an annotated tag with the specified name and message, which includes additional metadata like the tagger's name, email, and date, and points to the current commit.</p>
<h3 id="heading-git-tag-d"><code>git tag -d &lt;tag_name&gt;</code></h3>
<p>Deletes the specified tag from your local repository.</p>
<h3 id="heading-git-tag-f"><code>git tag -f &lt;tag&gt; &lt;commit&gt;</code></h3>
<p>Forces a tag to point to a different commit.</p>
<h3 id="heading-git-show"><code>git show &lt;tag_name&gt;</code></h3>
<p>Displays detailed information about the specified tag, including the commit it points to and any associated tag messages or annotations.</p>
<h3 id="heading-git-push-origin-1"><code>git push origin &lt;tag_name&gt;</code></h3>
<p>Uploads the specified tag to the remote repository, making it available to others.</p>
<h3 id="heading-git-push-origin-tags"><code>git push origin --tags</code></h3>
<p>Pushes all local tags to the remote repository, ensuring that all tags are synchronized with the remote.</p>
<h3 id="heading-git-push-follow-tags"><code>git push --follow-tags</code></h3>
<p>Pushes both commits and tags.</p>
<h3 id="heading-git-fetch-tags"><code>git fetch --tags</code></h3>
<p>Retrieves all tags from the default remote repository and updates your local repository with them, without affecting your current branches.</p>
<h2 id="heading-reverting-changes-in-git"><strong>Reverting Changes in Git</strong></h2>
<p>Reverting changes in Git involves undoing modifications made to a repository's history. You can do this using several commands, such as <code>git revert</code>. It creates a new commit that negates the changes of a specified previous commit, effectively reversing its effects while preserving the commit history.</p>
<p>Another method is using <code>git reset</code>, which changes the current HEAD to a specified commit and can update the staging area and working directory depending on the chosen options (<code>--soft</code>, <code>--mixed</code>, or <code>--hard</code>).</p>
<p>You can also use <code>git checkout</code> to discard changes in the working directory, reverting files to their state in the last commit.</p>
<p>These tools provide flexibility in managing and correcting changes, ensuring the repository remains accurate and clean.</p>
<h3 id="heading-git-checkout-2"><code>git checkout -- &lt;file&gt;</code></h3>
<p>Discards changes in the specified file from the working directory, reverting it to the state of the last commit and effectively undoing any modifications that haven't been staged.</p>
<h3 id="heading-git-revert"><code>git revert &lt;commit&gt;</code></h3>
<p>Creates a new commit that undoes the changes in the specified commit, effectively reversing its effects while preserving the history.</p>
<h3 id="heading-git-revert-n"><code>git revert -n &lt;commit&gt;</code></h3>
<p>Reverts a commit but does not commit the result.</p>
<h3 id="heading-git-reset"><code>git reset</code></h3>
<p>Resets the current HEAD to the specified state, and optionally updates the staging area and working directory, depending on the options used (<code>--soft</code>, <code>--mixed</code>, or <code>--hard</code>).</p>
<h3 id="heading-git-reset-soft"><code>git reset --soft &lt;commit&gt;</code></h3>
<p>Moves HEAD to the specified commit, while keeping the index (staging area) and working directory unchanged, so all changes after the specified commit remain staged for committing. This is useful when you want to undo commits but keep the changes ready to be committed again.</p>
<h3 id="heading-git-reset-mixed"><code>git reset --mixed &lt;commit&gt;</code></h3>
<p>Moves HEAD to the specified commit and updates the index (staging area) to match that commit. But it leaves the working directory unchanged, so changes after the specified commit are kept but are untracked.</p>
<h3 id="heading-git-reset-hard"><code>git reset --hard &lt;commit&gt;</code></h3>
<p>Moves HEAD to the specified commit and updates both the index (staging area) and working directory to match that commit. It discards all changes and untracked files after the specified commit.</p>
<h2 id="heading-viewing-history-logs"><strong>Viewing History Logs</strong></h2>
<p>Git history refers to the record of all changes made to a repository over time. It includes a chronological sequence of commits, each representing a snapshot of the repository at a specific point.</p>
<p>This history allows you to track modifications, understand the evolution of the codebase, and collaborate effectively by providing a detailed log of who made changes, when, and why.</p>
<p>Tools like git log help you navigate this history, offering insights into the development process and aiding in debugging and project management.</p>
<h3 id="heading-git-log"><code>git log</code></h3>
<p>Displays the commits log.</p>
<h3 id="heading-git-log-oneline"><code>git log --oneline</code></h3>
<p>Displays a summary of commits with one line each.</p>
<h3 id="heading-git-log-graph"><code>git log --graph</code></h3>
<p>Shows a graphical representation of the commit history.</p>
<h3 id="heading-git-log-stat"><code>git log --stat</code></h3>
<p>Displays file statistics along with the commit history.</p>
<h3 id="heading-git-log-prettyformath-s"><code>git log --pretty=format:"%h %s"</code></h3>
<p>Formats the log output according to the specified format.</p>
<h3 id="heading-git-log-prettyformath-an-ar-s"><code>git log --pretty=format:"%h - %an, %ar : %s"</code></h3>
<p>Provides a more human-readable format for logs.</p>
<h3 id="heading-git-log-author"><code>git log --author=&lt;author&gt;</code></h3>
<p>Shows commits made by the specified author.</p>
<h3 id="heading-git-log-before"><code>git log --before=&lt;date&gt;</code></h3>
<p>Shows commits made before the specified date.</p>
<h3 id="heading-git-log-after"><code>git log --after=&lt;date&gt;</code></h3>
<p>Shows commits made after the specified date (same as <code>git log --since=&lt;date&gt;</code>)</p>
<h3 id="heading-git-log-cherry-pick"><code>git log --cherry-pick</code></h3>
<p>Omits commits that are equivalent between two branches.</p>
<h3 id="heading-git-log-follow"><code>git log --follow &lt;file&gt;</code></h3>
<p>Shows commits for a file, including renames.</p>
<h3 id="heading-git-log-show-signature"><code>git log --show-signature</code></h3>
<p>Displays GPG signature information for commits.</p>
<h3 id="heading-git-shortlog"><code>git shortlog</code></h3>
<p>Summarizes git log output by author.</p>
<h3 id="heading-git-shortlog-sn"><code>git shortlog -sn</code></h3>
<p>Summarizes git log output by author, with commit counts.</p>
<h3 id="heading-git-log-simplify-by-decoration"><code>git log --simplify-by-decoration</code></h3>
<p>Shows only commits that are referenced by tags or branches.</p>
<h3 id="heading-git-log-no-merges"><code>git log --no-merges</code></h3>
<p>Omits merge commits from the log.</p>
<h3 id="heading-git-whatchanged"><code>git whatchanged</code></h3>
<p>Lists commit data in a format similar to a commit log.</p>
<h3 id="heading-git-diff-tree-pretty-name-only-root"><code>git diff-tree --pretty --name-only --root &lt;commit&gt;</code></h3>
<p>Shows detailed information for a commit tree.</p>
<h3 id="heading-git-log-first-parent"><code>git log --first-parent</code></h3>
<p>Only shows commits of the current branch and excludes those merged from other branches.</p>
<h2 id="heading-git-diffs"><strong>Git Diffs</strong></h2>
<p>Git diffs are a feature in Git that allows you to see the differences between various states in your repository. This can include differences between your working directory and the staging area, between the staging area and the last commit, or between any two commits or branches.</p>
<p>By displaying line-by-line changes in files, diffs help you review modifications before committing, merging, or applying changes, thus ensuring accuracy and consistency in your codebase.</p>
<h3 id="heading-git-diff"><code>git diff</code></h3>
<p>Shows the differences between various states in your repository, such as between your working directory and the index (staging area), between the index and the last commit, or between two commits. It displays line-by-line changes in files, helping you review modifications before committing or merging.</p>
<h3 id="heading-git-diff-stat"><code>git diff --stat</code></h3>
<p>Shows a summary of changes between your working directory and the index (staging area), helping you see what files have been modified and how many lines have been added or removed.</p>
<h3 id="heading-git-diff-stat-1"><code>git diff --stat &lt;commit&gt;</code></h3>
<p>Views changes between a commit and the working directory.</p>
<h3 id="heading-git-diff-stat-2"><code>git diff --stat &lt;commit1&gt; &lt;commit2&gt;</code></h3>
<p>Provides a summary of changes between two commits, showing which files were altered and the extent of changes between them.</p>
<h3 id="heading-git-diff-stat-3"><code>git diff --stat &lt;branch1&gt; &lt;branch2&gt;</code></h3>
<p>Summarizes the differences between the two branches, indicating the files changed and the magnitude of changes.</p>
<h3 id="heading-git-diff-name-only"><code>git diff --name-only &lt;commit&gt;</code></h3>
<p>Shows only the names of files that changed in the specified commit.</p>
<h3 id="heading-git-diff-cached"><code>git diff --cached</code></h3>
<p>Shows the differences between the staged changes (index) and the last commit, helping you review what will be included in the next commit.</p>
<h3 id="heading-git-diff-head"><code>git diff HEAD</code></h3>
<p>Shows the differences between the working directory and the latest commit (HEAD), allowing you to see what changes have been made since the last commit.</p>
<h3 id="heading-git-diff-1"><code>git diff &lt;branch1&gt; &lt;branch2&gt;</code></h3>
<p>Shows the differences between the tips of two branches, highlighting the changes between the commits at the end of each branch.</p>
<h3 id="heading-git-difftool"><code>git difftool</code></h3>
<p>Launches a diff tool to compare changes.</p>
<h3 id="heading-git-difftool-1"><code>git difftool &lt;commit1&gt; &lt;commit2&gt;</code></h3>
<p>Uses the diff tool to show the differences between two specified commits.</p>
<h3 id="heading-git-difftool-2"><code>git difftool &lt;branch1&gt; &lt;branch2&gt;</code></h3>
<p>Opens the diff tool to compare changes between two branches.</p>
<h3 id="heading-git-cherry"><code>git cherry &lt;branch&gt;</code></h3>
<p>Compares the commits in your current branch against another branch and shows which commits are unique to each branch. It is commonly used to identify which commits in one branch have not been applied to another branch.</p>
<h2 id="heading-git-flow"><strong>Git Flow</strong></h2>
<p>Git Flow is a branching model for Git that provides a robust framework for managing larger projects. It defines a strict branching strategy designed around the project release cycle, with two primary branches (main and develop) and supporting branches for features, releases, and hotfixes.</p>
<p>This model helps in organizing work, ensuring a clean and manageable history, and facilitating collaboration by clearly defining roles and processes for different types of development work.</p>
<h3 id="heading-git-flow-init"><code>git flow init</code></h3>
<p>Initializes a repository for a git-flow branching model.</p>
<h3 id="heading-git-flow-feature-start"><code>git flow feature start &lt;feature&gt;</code></h3>
<p>Starts a new feature branch in git-flow.</p>
<h3 id="heading-git-flow-feature-finish"><code>git flow feature finish &lt;feature&gt;</code></h3>
<p>Finishes a feature branch in git-flow.</p>
<h2 id="heading-exploring-git-references"><strong>Exploring Git References</strong></h2>
<p>Git references, often referred to as refs, are pointers to specific commits or objects within a Git repository. These can include branches, tags, and other references like HEAD, which points to the current commit checked out in your working directory.</p>
<p>References are used to keep track of the structure and history of the repository. They help Git efficiently manage and navigate different points in the project's timeline.</p>
<p>Refs also provide a way to name and refer to particular commits, making it easier to work with and manipulate the repository's history.</p>
<h3 id="heading-git-show-ref-heads"><code>git show-ref --heads</code></h3>
<p>Lists references to all heads (branches).</p>
<h3 id="heading-git-show-ref-tags"><code>git show-ref --tags</code></h3>
<p>Lists references to all tags.</p>
<h2 id="heading-how-to-configure-git"><strong>How to Configure Git</strong></h2>
<p>Git configuration involves setting up various options and preferences that control the behavior of your Git environment. This can include specifying your username and email, setting up default text editors, creating aliases for commonly used commands, and configuring global ignore files.</p>
<p>You can apply configuration settings at different levels: global (affecting all repositories on your system), local (affecting a single repository), and system-wide. These settings ensure a customized and consistent user experience, streamline workflows, and enhance the overall efficiency of version control operations.</p>
<h3 id="heading-git-config-global-usernamehttpusername-your-name"><code>git config --global</code> <a target="_blank" href="http://user.name"><code>user.name</code></a> <code>"Your Name"</code></h3>
<p>Sets the user name on a global level.</p>
<h3 id="heading-git-config-global-useremailhttpuseremail-youremailexamplecom"><code>git config --global</code> <a target="_blank" href="http://user.email"><code>user.email</code></a> <code>"your_email@example.com"</code></h3>
<p>Sets the user email on a global level.</p>
<h3 id="heading-git-config-global-coreeditor"><code>git config --global core.editor &lt;editor&gt;</code></h3>
<p>Sets the default text editor.</p>
<h3 id="heading-git-config-global-coreexcludesfile"><code>git config --global core.excludesfile &lt;file&gt;</code></h3>
<p>Sets the global ignore file.</p>
<h3 id="heading-git-config-list"><code>git config --list</code></h3>
<p>Lists all the configuration settings.</p>
<h3 id="heading-git-config-list-show-origin"><code>git config --list --show-origin</code></h3>
<p>Lists all config variables, showing their origins.</p>
<h3 id="heading-git-config"><code>git config &lt;key&gt;</code></h3>
<p>Retrieves the value for the specified key.</p>
<h3 id="heading-git-config-get"><code>git config --get &lt;key&gt;</code></h3>
<p>Retrieves the value for the specified configuration key.</p>
<h3 id="heading-git-config-unset"><code>git config --unset &lt;key&gt;</code></h3>
<p>Removes the specified configuration key.</p>
<h3 id="heading-git-config-global-unset"><code>git config --global --unset &lt;key&gt;</code></h3>
<p>Removes the specified configuration key globally.</p>
<h2 id="heading-git-security"><strong>Git Security</strong></h2>
<p>Git GPG security involves using GNU Privacy Guard (GPG) to sign commits and tags, ensuring their authenticity and integrity. By configuring a GPG key and enabling automatic signing, you can verify that commits and tags were created by a trusted source. This helps prevent tampering and ensures the integrity of the repository's history.</p>
<p>This practice enhances security by providing cryptographic assurance that the changes come from a legitimate contributor.</p>
<h3 id="heading-git-config-global-usersigningkey"><code>git config --global user.signingKey &lt;key&gt;</code></h3>
<p>Configures the GPG key for signing commits and tags.</p>
<h3 id="heading-git-config-global-commitgpgsign-true"><code>git config --global commit.gpgSign true</code></h3>
<p>Automatically signs all commits with GPG.</p>
<h2 id="heading-how-to-set-aliases-in-git"><strong>How to Set Aliases in Git</strong></h2>
<p>Git aliases are custom shortcuts that you can create to simplify and speed up your workflow by mapping longer Git commands to shorter, more memorable names.</p>
<p>By configuring aliases in your Git settings, you can quickly execute frequently used commands with less typing. This not only enhances productivity but also reduces the likelihood of errors.</p>
<p>For example, you can set an alias like git st to replace git status, or git co to replace git checkout.</p>
<p>You can define aliases globally to apply across all repositories or locally for individual projects, providing flexibility in how you streamline your Git operations.</p>
<h3 id="heading-git-config-global-aliasci-commit"><code>git config --global alias.ci commit</code></h3>
<p>Sets git ci as an alias for git commit.</p>
<h3 id="heading-git-config-global-aliasst-status"><code>git config --global alias.st status</code></h3>
<p>Sets git st as an alias for git status.</p>
<h3 id="heading-git-config-global-aliasco-checkout"><code>git config --global alias.co checkout</code></h3>
<p>Sets git co as an alias for git checkout.</p>
<h3 id="heading-git-config-global-aliasbr-branch"><code>git config --global alias.br branch</code></h3>
<p>Sets git br as an alias for git branch.</p>
<h3 id="heading-git-config-global-aliasgraph-log-graph-all-oneline-decorate"><code>git config --global alias.graph "log --graph --all --oneline --decorate"</code></h3>
<p>Creates an alias for a detailed graph of the repository history.</p>
<h2 id="heading-rebasing-in-git"><strong>Rebasing in Git</strong></h2>
<p>Git rebasing re-applies your changes on top of another branch's history, creating a cleaner and more linear project history.</p>
<p>In practice, this helps integrate updates smoothly by avoiding unnecessary merge commits, ensuring that the commit sequence is straightforward, and making it easier to understand the evolution of the project.</p>
<h3 id="heading-git-rebase"><code>git rebase &lt;branch&gt;</code></h3>
<p>The git rebase command is used to re-apply commits on top of another base tip. It allows you to move or combine a sequence of commits to a new base commit. This is commonly used to:</p>
<ol>
<li><p>Keep a linear project history.</p>
</li>
<li><p>Integrate changes from one branch into another.</p>
</li>
<li><p>Update a feature branch with the latest changes from the main branch.</p>
</li>
</ol>
<p>The basic usage is git rebase &lt;branch&gt;, which will rebase the current branch onto the specified branch.</p>
<h3 id="heading-git-rebase-interactive"><code>git rebase --interactive &lt;branch&gt;</code></h3>
<p>Starts an interactive rebase session, allowing you to modify commits starting from &lt;base&gt; up to the current HEAD. This lets you reorder, squash, edit, or delete commits, providing a way to clean up and refine commit history before pushing changes. Shorter version: <code>git rebase -i &lt;branch&gt;</code></p>
<h3 id="heading-git-rebase-continue"><code>git rebase --continue</code></h3>
<p>Continues the rebase process after resolving conflicts.</p>
<h3 id="heading-git-rebase-abort"><code>git rebase --abort</code></h3>
<p>Aborts the rebase process and returns to the original branch.</p>
<h3 id="heading-git-fetch-rebase"><code>git fetch --rebase</code></h3>
<p>Fetches from the remote repository and rebases local changes.</p>
<h2 id="heading-what-is-cherry-picking"><strong>What is Cherry-Picking?</strong></h2>
<p>Git cherry-picking is a process that allows you to apply the changes introduced by a specific commit from one branch into another branch. This is particularly useful when you want to selectively incorporate individual changes from different branches without merging the entire branch.</p>
<p>By using the git cherry-pick command, you can isolate and integrate only the desired commits, ensuring that specific modifications are included in your current branch while avoiding potential conflicts and unwanted changes from other parts of the branch.</p>
<h3 id="heading-git-cherry-pick"><code>git cherry-pick &lt;commit&gt;</code></h3>
<p>Applies the changes introduced by an existing commit.</p>
<h3 id="heading-git-cherry-pick-continue"><code>git cherry-pick --continue</code></h3>
<p>Continues cherry-picking after resolving conflicts.</p>
<h3 id="heading-git-cherry-pick-abort"><code>git cherry-pick --abort</code></h3>
<p>Aborts the cherry-pick process.</p>
<h3 id="heading-git-cherry-pick-no-commit"><code>git cherry-pick --no-commit &lt;commit&gt;</code></h3>
<p>Cherry-picks a commit without automatically committing and allows further changes. Shorter version: <code>git cherry-pick -n &lt;commit&gt;</code></p>
<h2 id="heading-patching-in-git"><strong>Patching in Git</strong></h2>
<p>Git patching is a method used to apply changes from one repository to another or from one branch to another within the same repository. It involves creating patch files, which are text files representing differences between commits or branches. These patch files can then be applied to a repository using commands like <code>git apply</code> or <code>git am</code>, allowing changes to be transferred and integrated without directly merging branches.</p>
<p>Patching is particularly useful for sharing specific changes or updates across different codebases, ensuring that only the intended modifications are applied.</p>
<h3 id="heading-git-apply"><code>git apply &lt;patch_file&gt;</code></h3>
<p>Applies changes to the working directory from a patch file.</p>
<h3 id="heading-git-apply-check"><code>git apply --check</code></h3>
<p>Checks if patches can be applied cleanly.</p>
<h3 id="heading-git-format-patch"><code>git format-patch &lt;since_commit&gt;</code></h3>
<p>Creates patch files for each commit since the specified commit.</p>
<h3 id="heading-git-am"><code>git am &lt;patch_file&gt;</code></h3>
<p>Applies patches from a mailbox.</p>
<h3 id="heading-git-am-continue"><code>git am --continue</code></h3>
<p>Continues applying patches after resolving conflicts.</p>
<h3 id="heading-git-am-abort"><code>git am --abort</code></h3>
<p>Aborts the patch application process.</p>
<h3 id="heading-git-diff-gt"><code>git diff &gt; &lt;file.patch&gt;</code></h3>
<p>Creates a patch file from differences.</p>
<h2 id="heading-relative-dates-in-git"><strong>Relative Dates in Git</strong></h2>
<p>Git relative dates allow users to refer to specific points in the repository's history using human-readable time expressions. For instance, commands like main@{1.week.ago} or @{3.days.ago} enable you to access the state of a branch or view changes made since a certain time period relative to the current date.</p>
<p>This feature simplifies navigating the repository's timeline by using intuitive terms like "yesterday," "2 weeks ago," or specific dates, making it easier to track and manage the evolution of the codebase without needing to remember exact commit hashes or timestamps.</p>
<h3 id="heading-git-show-main1weekago"><code>git show main@{1.week.ago}</code></h3>
<p>Lets you see the state of your main branch one week ago.</p>
<h3 id="heading-git-diff-3daysago"><code>git diff @{3.days.ago}</code></h3>
<p>Shows what changes you've made in the last 3 days.</p>
<h3 id="heading-git-checkout-main2weeksago"><code>git checkout main@{2.weeks.ago}</code></h3>
<p>Checks out your repository as it was 2 weeks ago.</p>
<h3 id="heading-git-log-1monthagohead"><code>git log @{1.month.ago}..HEAD</code></h3>
<p>Shows you the log of commits from 1 month ago until now.</p>
<h3 id="heading-2024-06-01"><code>@{2024-06-01}</code></h3>
<h3 id="heading-yesterday"><code>@{yesterday}</code></h3>
<h3 id="heading-1-week-2-days-ago"><code>@{"1 week 2 days ago"}</code></h3>
<p>Other usage examples.</p>
<h2 id="heading-git-blame"><strong>Git Blame</strong></h2>
<p>Git blaming is a feature in Git that identifies the last modification made to each line of a file, attributing changes to specific commits and authors. You can do this using the <code>git blame</code> command, which provides a detailed annotation of the file, showing who made changes and when they were made.</p>
<p>This tool is particularly useful for tracking the history of a file, understanding the evolution of the code, and identifying the source of bugs or changes.</p>
<p>By pinpointing the exact commit and author responsible for each line, developers can gain insights into the development process and facilitate better collaboration and accountability within a team.</p>
<h3 id="heading-git-blame-1"><code>git blame &lt;file&gt;</code></h3>
<p>Shows the last modification for each line of a file.</p>
<h3 id="heading-git-blame-l"><code>git blame &lt;file&gt; -L &lt;start&gt;,&lt;end&gt;</code></h3>
<p>Limits the blame output to the specified line range.</p>
<h3 id="heading-git-blame-2"><code>git blame &lt;file&gt; &lt;commit&gt;</code></h3>
<p>Shows the blame information up to the specified commit.</p>
<h3 id="heading-git-blame-c-c"><code>git blame &lt;file&gt; -C -C</code></h3>
<p>Shows which revisions and authors last modified each line of a file, with copying detection.</p>
<p>The <code>-C</code> option detects lines moved or copied within the same file. Using it once (<code>-C</code>) detects lines moved or copied within the same file. Using the <code>-C</code> option twice (<code>-C -C</code>) makes Git inspect unmodified files as candidates for the source of copy. This means it will try to find the origin of copied lines not just in the same file but in other files as well.</p>
<h3 id="heading-git-blame-reverse"><code>git blame &lt;file&gt; --reverse</code></h3>
<p>Works backwards, showing who last altered each line in the specified file.</p>
<h3 id="heading-git-blame-first-parent"><code>git blame &lt;file&gt; --first-parent</code></h3>
<p>Shows who most recently modified each line in a file, following only the first parent commit for merge changes.</p>
<h2 id="heading-archiving-in-git"><strong>Archiving in Git</strong></h2>
<p>Git archiving is a feature that allows you to create archive files, such as .tar or .zip, containing the contents of a specific commit, branch, or tag. This is useful for packaging a snapshot of your repository at a specific point in time, enabling you to distribute or backup the repository's state without including the entire Git history.</p>
<p>The git archive command is typically used for this purpose, providing a convenient way to export the current state of the project into a portable format.</p>
<h3 id="heading-git-archive"><code>git archive &lt;format&gt; &lt;tree-ish&gt;</code></h3>
<p>Creates an archive file (for example, a .tar or .zip file) containing the contents of the specified tree-ish (like a commit, branch, or tag) in the given format. For example:</p>
<ul>
<li><p><code>git archive --format=tar HEAD</code> creates a .tar archive of the current commit (HEAD).</p>
</li>
<li><p><code>git archive --format=zip v1.0</code> creates a .zip archive of the files in the v1.0 tag.</p>
</li>
</ul>
<p>This command is useful for packaging a snapshot of your repository at a specific point in time.</p>
<h2 id="heading-how-to-track-files-in-git"><strong>How to Track Files in Git</strong></h2>
<p>Git tracking refers to the process of monitoring and managing the files in a repository.</p>
<p>The command <code>git ls-files</code> lists all files that are being tracked by Git, providing a clear view of the files that are currently under version control. On the other hand, <code>git ls-tree &lt;branch&gt;</code> displays the contents of a tree object for a specified branch, showing the structure and files at that point in the repository.</p>
<p>Together, these commands help developers understand which files are included in the repository and how they are organized, ensuring efficient tracking and management of the project's codebase.</p>
<h3 id="heading-git-ls-files"><code>git ls-files</code></h3>
<p>Lists all tracked files.</p>
<h3 id="heading-git-ls-tree"><code>git ls-tree &lt;branch&gt;</code></h3>
<p>Lists the contents of a tree object.</p>
<h2 id="heading-index-manipulation-in-git"><strong>Index Manipulation in Git</strong></h2>
<p>Git index manipulation involves managing the staging area (also known as the index) where changes are prepared before committing. This can include marking files as "assume unchanged" to temporarily ignore changes, or resetting these markings to track changes again.</p>
<p>Index manipulation commands, such as <code>git update-index</code>, allow you to control which files are included in the next commit, providing flexibility in handling changes and optimizing the workflow for specific tasks.</p>
<h3 id="heading-git-update-index-assume-unchanged"><code>git update-index --assume-unchanged &lt;file&gt;</code></h3>
<p>Marks a file as assume unchanged.</p>
<h3 id="heading-git-update-index-no-assume-unchanged"><code>git update-index --no-assume-unchanged &lt;file&gt;</code></h3>
<p>Unmarks a file as assume unchanged.</p>
<h2 id="heading-squashing-in-git"><strong>Squashing in Git</strong></h2>
<p>Git squashing is the process of combining multiple commits into a single commit. Devs often do this to clean up the commit history before merging changes into a main branch, making the history more concise and easier to read.</p>
<p>Squashing can be performed using the interactive rebase command (<code>git rebase -i</code>), which lets you selectively merge, reorder, or edit commits. By squashing commits, you can consolidate redundant or minor changes, presenting a clearer narrative of the development process.</p>
<h3 id="heading-git-rebase-i-head"><code>git rebase -i HEAD~&lt;n&gt;</code></h3>
<p>Squashes commits interactively.</p>
<h2 id="heading-data-integrity-in-git"><strong>Data Integrity in Git</strong></h2>
<p>Git data integrity refers to the mechanisms and processes Git employs to ensure the accuracy and consistency of data within a repository.</p>
<p>Git uses cryptographic hashes (SHA-1 or SHA-256) to uniquely identify objects such as commits, trees, and blobs. This hashing not only provides a unique identifier for each object but also ensures that any modification to the object's content will result in a different hash, thus detecting any corruption or tampering.</p>
<p>You can use commands like <code>git fsck</code> to verify the connectivity and validity of objects in the database, ensuring the overall health and integrity of the repository.</p>
<h3 id="heading-git-fsck"><code>git fsck</code></h3>
<p>Verifies the connectivity and validity of objects in the database.</p>
<h3 id="heading-git-fsck-unreachable"><code>git fsck --unreachable</code></h3>
<p>Finds objects in the repository that are not reachable from any reference.</p>
<h3 id="heading-git-prune"><code>git prune</code></h3>
<p>Removes unreachable objects.</p>
<h3 id="heading-git-gc"><code>git gc</code></h3>
<p>Runs a garbage collection process.</p>
<p>Git garbage collection is a maintenance process that cleans up and optimizes the repository by removing unnecessary files and compressing file revisions to save space. This process, triggered by the <code>git gc</code> command, consolidates and deletes unreachable objects, such as orphaned commits and unreferenced blobs, ensuring the repository remains efficient and performant.</p>
<p>Regular garbage collection helps manage storage effectively and keeps the repository's structure organized.</p>
<h2 id="heading-cleaning-up-in-git"><strong>Cleaning Up in Git</strong></h2>
<p>Cleaning up in Git involves removing unnecessary files, references, and branches that are no longer needed. This helps to keep your repository organized and efficient.</p>
<p>Regular cleanup activities, such as pruning remote-tracking branches, deleting untracked files, and removing stale references, ensure that your repository remains manageable and free from clutter.</p>
<p>In practice, these actions can improve performance, reduce storage requirements, and make it easier to navigate and work within your project.</p>
<h3 id="heading-git-fetch-prune"><code>git fetch --prune</code></h3>
<p>Removes references that no longer exist on the remote.</p>
<h3 id="heading-git-remote-prune"><code>git remote prune &lt;name&gt;</code></h3>
<p>Prunes all stale remote-tracking branches.</p>
<h3 id="heading-git-fetch-origin-prune"><code>git fetch origin --prune</code></h3>
<p>Cleans up outdated references from the remote repository.</p>
<h3 id="heading-git-clean-f"><code>git clean -f</code></h3>
<p>Removes untracked files from the working directory, forcing the deletion of files not being tracked by Git.</p>
<h3 id="heading-git-clean-fd"><code>git clean -fd</code></h3>
<p>Removes untracked files and directories from the working directory, including any files and directories not tracked by Git.</p>
<h3 id="heading-git-clean-i"><code>git clean -i</code></h3>
<p>Enters interactive mode for cleaning untracked files.</p>
<h3 id="heading-git-clean-x"><code>git clean -X</code></h3>
<p>Removes only ignored files from the working directory.</p>
<h2 id="heading-git-subtree"><strong>Git Subtree</strong></h2>
<p>Git subtree is a mechanism for managing and integrating subprojects into a main repository. Unlike submodules, which treat the subproject as a separate entity with its own repository, subtrees allow you to include the contents of another repository directly within a subdirectory of your main repository.</p>
<p>This approach simplifies the workflow by eliminating the need for multiple repositories and enabling seamless integration, merging, and pulling of updates from the subproject. Subtrees provide a flexible and convenient way to manage dependencies and collaborate on projects that require incorporating external codebases.</p>
<h3 id="heading-git-subtree-add-prefix"><code>git subtree add --prefix=&lt;dir&gt; &lt;repository&gt; &lt;branch&gt;</code></h3>
<p>Adds a repository as a subtree.</p>
<h3 id="heading-git-subtree-merge-prefix"><code>git subtree merge --prefix=&lt;dir&gt; &lt;branch&gt;</code></h3>
<p>Merges a subtree.</p>
<h3 id="heading-git-subtree-pull-prefix"><code>git subtree pull --prefix=&lt;dir&gt; &lt;repository&gt; &lt;branch&gt;</code></h3>
<p>Pulls in new changes from the subtree's repository.</p>
<h2 id="heading-how-to-search-in-git"><strong>How to Search in Git</strong></h2>
<p><code>git grep</code> is a powerful search command in Git that allows users to search for specific strings or patterns within the files of a repository. It searches through the working directory and the index, providing a quick and efficient way to locate occurrences of a specified pattern across multiple files.</p>
<p>This command is particularly useful for developers looking to find instances of code, comments, or text within a project, enabling them to navigate and understand large codebases with ease. With various options and flags, git grep lets you perform targeted searches, making it an essential tool for code analysis and maintenance.</p>
<h3 id="heading-git-grep"><code>git grep &lt;pattern&gt;</code></h3>
<p>Searches for a string in the working directory and the index.</p>
<h3 id="heading-git-grep-e"><code>git grep -e &lt;pattern&gt;</code></h3>
<p>Searches for a specific pattern.</p>
<h2 id="heading-bisecting-in-git"><strong>Bisecting in Git</strong></h2>
<p>Git bisecting is a powerful debugging tool that helps identify the specific commit that introduced a bug or issue in a project. By performing a binary search through the commit history, git bisect efficiently narrows down the range of potential problem commits.</p>
<p>The process involves marking a known good commit and a known bad commit, and then repeatedly testing intermediate commits to determine whether they are good or bad.</p>
<p>This iterative approach quickly isolates the faulty commit, allowing developers to pinpoint the exact change that caused the problem. This facilitates faster and more accurate debugging.</p>
<h3 id="heading-git-bisect-start"><code>git bisect start</code></h3>
<p>Starts a bisect session.</p>
<h3 id="heading-git-bisect-bad"><code>git bisect bad</code></h3>
<p>Marks the current version as bad.</p>
<h3 id="heading-git-bisect-good"><code>git bisect good &lt;commit&gt;</code></h3>
<p>Marks the specified commit as good.</p>
<h3 id="heading-git-bisect-reset"><code>git bisect reset</code></h3>
<p>Ends a bisect session and returns to the original branch.</p>
<h3 id="heading-git-bisect-visualize"><code>git bisect visualize</code></h3>
<p>Launches a visual tool to assist with bisecting.</p>
<h2 id="heading-git-attributes"><strong>Git Attributes</strong></h2>
<p>Git attributes are settings that define how Git should handle specific files or paths within a repository. These attributes are defined in a file named .gitattributes, and they can control various behaviors such as text encoding, line-ending normalization, merge strategies, and diff algorithms.</p>
<p>By setting attributes, you can ensure consistent behavior across different environments and collaborators, making it easier to manage files with special requirements or complexities.</p>
<p>For example, you can mark certain files as binary to prevent Git from attempting to merge them, or specify custom diff drivers for more meaningful comparisons.</p>
<h3 id="heading-git-check-attr"><code>git check-attr &lt;attribute&gt; -- &lt;file&gt;</code></h3>
<p>Shows the value of a specific attribute for the given file as defined in the .gitattributes configuration, helping you understand how Git is treating the file with respect to attributes like text encoding, merge behavior, or diff handling.</p>
<h2 id="heading-git-checkout-3"><strong>Git Checkout</strong></h2>
<p><code>git checkout</code> is a versatile command in Git used to switch between different branches, tags, or commits within a repository. By updating the working directory and index to match the specified branch or commit, it allows you to view or work with the state of the repository at that point.</p>
<p>You can also use <code>git checkout</code> to create new branches, restore specific files from a commit, or even start a new branch with no history using the <code>--orphan</code> option. This command is essential for navigating and managing different versions of a project's codebase.</p>
<h3 id="heading-git-checkout-4"><code>git checkout &lt;commit&gt;</code></h3>
<p>Updates the working directory and index to match the specified commit, allowing you to view or work with the state of the repository at that commit. Just keep in mind that this leaves you in a "detached HEAD" state, meaning you're not on any branch.</p>
<h3 id="heading-git-checkout-b-1"><code>git checkout -b &lt;branch&gt; &lt;commit&gt;</code></h3>
<p>Creates a new branch named &lt;branch&gt; starting from the specified commit and switches to that branch, allowing you to begin working from that point in the commit history.</p>
<h3 id="heading-git-checkout-5"><code>git checkout &lt;commit&gt; -- &lt;file&gt;</code></h3>
<p>Restores the specified file from a specific commit into your working directory, replacing the current version of the file with the version from that commit without changing the commit history or index.</p>
<h3 id="heading-git-checkout-orphan"><code>git checkout --orphan &lt;new_branch&gt;</code></h3>
<p>Creates a new branch named &lt;new_branch&gt; with no commit history, effectively starting a new branch that begins with a clean working directory and index, as if it were a new repository.</p>
<h2 id="heading-git-reflog"><strong>Git Reflog</strong></h2>
<p>Git reflog is a powerful tool that records all changes made to the tips of branches and the HEAD reference in a Git repository. This includes actions such as commits, checkouts, merges, and resets.</p>
<p>By maintaining a history of these changes, reflog allows users to track recent modifications and recover lost commits, even if they are not part of the current branch history. It provides a way to navigate through the repository's state changes, making it an invaluable resource for debugging and undoing mistakes.</p>
<h3 id="heading-git-reflog-1"><code>git reflog</code></h3>
<p>Displays a log of all the changes to the HEAD reference and branch tips, including commits, checkouts, merges, and resets, allowing you to recover lost commits or track recent changes to the repository's state.</p>
<h3 id="heading-git-reflog-show"><code>git reflog show &lt;ref&gt;</code></h3>
<p>Displays the reflog for the specified reference (&lt;ref&gt;), showing a log of changes to that reference, including updates to HEAD or branch tips, along with associated commit messages and timestamps.</p>
<h2 id="heading-how-to-handle-untracked-files-in-git"><strong>How to Handle Untracked Files in Git</strong></h2>
<h3 id="heading-git-clean"><code>git clean</code></h3>
<p><code>git clean</code> removes untracked files and directories from the working directory. By default, it only shows what would be removed without actually deleting anything.</p>
<p>To perform the actual cleanup, you need to use additional flags:</p>
<ul>
<li><p><code>git clean -f</code>: Removes untracked files.</p>
</li>
<li><p><code>git clean -fd</code>: Removes untracked files and directories.</p>
</li>
<li><p><code>git clean -fx</code>: Removes untracked files, including those ignored by .gitignore.</p>
</li>
<li><p><code>git clean -n</code>: Shows which files would be removed without actually deleting them.</p>
</li>
</ul>
<h2 id="heading-force-pushing-in-git"><strong>Force Pushing in Git</strong></h2>
<h3 id="heading-git-push-force"><code>git push --force</code></h3>
<p>Forces a push of your local branch to the remote repository, even if it results in a non-fast-forward merge. It overwrites the remote branch with your local changes.</p>
<p>This can be necessary when you have rewritten history (for example, with a rebase) and need to update the remote branch to match your local branch. But it can also potentially overwrite others' changes – so use it with caution.</p>
<h2 id="heading-git-fetching-and-pulling"><strong>Git Fetching and Pulling</strong></h2>
<h3 id="heading-git-fetch-all"><code>git fetch --all</code></h3>
<p>Retrieves updates from all remote repositories configured for your local repository, fetching changes from all branches and tags without modifying your local branches.</p>
<h3 id="heading-git-pull-rebase"><code>git pull --rebase</code></h3>
<p>Fetches changes from the remote repository and rebases your local commits on top of the updated remote branch, rather than merging them. This keeps the commit history linear and avoids unnecessary merge commits.</p>
<h2 id="heading-how-to-handle-merge-conflicts-in-git"><strong>How to Handle Merge Conflicts in Git</strong></h2>
<p>Handling merge conflicts in Git is an essential skill for collaborating on projects with multiple contributors.</p>
<p>Merge conflicts occur when changes in different branches or commits overlap or contradict each other, preventing an automatic merge. Resolving these conflicts involves reviewing and manually reconciling the differences to ensure that the final code integrates contributions from all parties accurately.</p>
<p>In practice, effectively managing merge conflicts helps maintain code integrity and facilitates smooth collaboration by ensuring that everyone's changes are correctly incorporated into the project's history.</p>
<h3 id="heading-git-mergetool"><code>git mergetool</code></h3>
<p>This launches a merge tool to help you resolve conflicts that arise during a merge or rebase. It opens a graphical interface or a text-based tool configured in your Git settings, allowing you to manually resolve conflicts and finalize the merge.</p>
<h3 id="heading-git-rerere"><code>git rerere</code></h3>
<p><code>rerere</code> stands for "reuse recorded resolution" and is a feature that helps automatically resolve conflicts in future merges or rebases by reusing conflict resolutions you've previously recorded.</p>
<p>Once enabled, Git records how you resolved conflicts. If the same conflicts arise again, it can apply the same resolutions automatically.</p>
<h2 id="heading-working-trees-in-git"><strong>Working Trees in Git</strong></h2>
<p>Working trees in Git allow you to have multiple working directories associated with a single repository. This is particularly useful for working on multiple branches simultaneously without the need to constantly switch branches in the same directory.</p>
<p>By using working trees, you can easily manage different features, bug fixes, or experiments in isolated environments, improving workflow efficiency and reducing the risk of conflicts.</p>
<h3 id="heading-git-worktree-add-new-branch-feature-branch"><code>git worktree add ../new-branch feature-branch</code></h3>
<p>Creates a new working tree in a directory named "new-branch" based on the "feature-branch".</p>
<h3 id="heading-git-worktree-list"><code>git worktree list</code></h3>
<p>Lists all working trees associated with the current repository, showing their paths and the branches they are checked out to.</p>
<h3 id="heading-git-worktree-remove"><code>git worktree remove &lt;path&gt;</code></h3>
<p>Removes the specified working tree at the given &lt;path&gt;, deleting the working directory and detaching the branch.</p>
<h3 id="heading-git-worktree-prune"><code>git worktree prune</code></h3>
<p>Removes references to nonexistent working trees, cleaning up the working tree list.</p>
<h3 id="heading-git-worktree-lock"><code>git worktree lock &lt;path&gt;</code></h3>
<p>Locks the specified working tree at the given &lt;path&gt;, preventing it from being pruned.</p>
<h3 id="heading-git-worktree-unlock"><code>git worktree unlock &lt;path&gt;</code></h3>
<p>Unlocks the specified working tree at the given &lt;path&gt;, allowing it to be pruned if necessary.</p>
<h2 id="heading-submodules-in-git"><strong>Submodules in Git</strong></h2>
<p>Submodules in Git are a way to include and manage external repositories within your own repository. They are particularly useful for reusing code across multiple projects, maintaining dependencies, or integrating third-party libraries.</p>
<p>By using submodules, you can keep your main repository clean and modular, while still ensuring that all necessary components are included and version-controlled.</p>
<h3 id="heading-git-submodule-init"><code>git submodule init</code></h3>
<p>Initializes submodules in your repository. This command sets up the configuration necessary for the submodules, but doesn't actually clone them.</p>
<h3 id="heading-git-submodule-update"><code>git submodule update</code></h3>
<p>Clones and checks out the submodules into the specified paths. This is typically run after git submodule init.</p>
<h3 id="heading-git-submodule-add"><code>git submodule add &lt;repository&gt; &lt;path&gt;</code></h3>
<p>Adds a new submodule to your repository at the specified path, linking it to the specified repository.</p>
<h3 id="heading-git-submodule-status"><code>git submodule status</code></h3>
<p>Displays the status of all submodules, showing their commit hashes and whether they are up-to-date, modified, or uninitialized.</p>
<h3 id="heading-git-submodule-foreach"><code>git submodule foreach &lt;command&gt;</code></h3>
<p>Runs the specified command in each submodule. This is useful for performing batch operations across all submodules.</p>
<h3 id="heading-git-submodule-sync"><code>git submodule sync</code></h3>
<p>Synchronizes the submodule URLs in your configuration file with those in the .gitmodules file, ensuring they are up-to-date.</p>
<h3 id="heading-git-submodule-deinit"><code>git submodule deinit &lt;path&gt;</code></h3>
<p>Unregisters the specified submodule, removing its configuration. This doesn't delete the submodule's working directory.</p>
<h3 id="heading-git-submodule-update-remote"><code>git submodule update --remote</code></h3>
<p>Fetches and updates the submodules to the latest commit from their remote repositories.</p>
<h3 id="heading-git-submodule-set-url"><code>git submodule set-url &lt;path&gt; &lt;newurl&gt;</code></h3>
<p>Changes the URL of the specified submodule to the new URL.</p>
<h3 id="heading-git-submodule-absorbgitdirs"><code>git submodule absorbgitdirs</code></h3>
<p>Absorbs the submodule's Git directory into the superproject to simplify the structure.</p>
<p>Thank you for reading! I hope this cheatsheet helps you work more easily in Git.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Express +  Node.js Handbook – Learn the Express JavaScript Framework for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ What is Express? Express is a Web Framework built upon Node.js. Node.js is an amazing tool for building networking services and applications. Express builds on top of its features to provide easy to use functionality that satisfies the needs of the W... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-express-handbook/</link>
                <guid isPermaLink="false">66bb5aa724dd38751ddeb5d5</guid>
                
                    <category>
                        <![CDATA[ Express ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Flavio Copes ]]>
                </dc:creator>
                <pubDate>Fri, 18 Nov 2022 18:52:29 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/11/pexels-paul-ijsendoorn-1181202.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <h2 id="heading-what-is-express">What is Express?</h2>
<p>Express is a Web Framework built upon Node.js.</p>
<p>Node.js is an amazing tool for building networking services and applications.</p>
<p>Express builds on top of its features to provide easy to use functionality that satisfies the needs of the Web Server use-case. It's Open Source, free, easy to extend, and very performant.</p>
<p>There are also lots and lots of pre-built packages you can just drop in and use to do all kinds of things.</p>
<p><a target="_blank" href="https://thevalleyofcode.com/download/express/">You can get a PDF and ePub version of this Express Handbook</a></p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-to-install-express">How to Install Express</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-first-hello-world-example">The first "Hello, World" example</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-request-parameters">Request Parameters</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-send-a-response-to-the-client">How to Send a Response to the Client</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-send-a-json-response">How to Send a JSON Response</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-manage-cookies">How to Manage Cookies</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-work-with-http-headers">How to Work with HTTP Headers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-handle-redirects">How to Handle Redirects</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-routing-in-express">Routing in Express</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-templates-in-express">Templates in Express</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-express-middleware">Express Middleware</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-serve-static-assets-with-express">How to Serve Static Assets with Express</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-send-files-to-the-client">How to Send Files to the Client</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-sessions-in-express">Sessions in Express</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-validate-input-in-express">How to Validate Input in Express</a></p>
</li>
<li><p><a class="post-section-overview" href="#how-to-sanitize-input-in-express">How to Sanitize Input in Express</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-handle-forms-in-express">How to Handle Forms in Express</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-handle-file-uploads-in-forms-in-express">How to Handle File Uploads in Forms in Express</a></p>
</li>
</ul>
<h2 id="heading-how-to-install-express">How to Install Express</h2>
<p>You can install Express into any project with npm.</p>
<p>If you're in an empty folder, first create a new Node.js project with this command:</p>
<pre><code class="lang-javascript">npm init -y
</code></pre>
<p>then run this:</p>
<pre><code class="lang-javascript">npm install express
</code></pre>
<p>to install Express into the project.</p>
<h2 id="heading-the-first-hello-world-example">The First "Hello, World" Example</h2>
<p>The first example we're going to create is a simple Express Web Server.</p>
<p>Copy this code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)
<span class="hljs-keyword">const</span> app = express()

app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> res.send(<span class="hljs-string">'Hello World!'</span>))
app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server ready'</span>))
</code></pre>
<p>Save this to an <code>index.js</code> file in your project root folder, and start the server using this command:</p>
<pre><code class="lang-javascript">node index.js
</code></pre>
<p>You can open the browser to port 3000 on localhost and you should see the <code>Hello World!</code> message.</p>
<p>Those 4 lines of code do a lot behind the scenes.</p>
<p>First, we import the <code>express</code> package to the <code>express</code> value.</p>
<p>We instantiate an application by calling the <code>express()</code> method.</p>
<p>Once we have the application object, we tell it to listen for GET requests on the <code>/</code> path, using the <code>get()</code> method.</p>
<p>There is a method for every HTTP <strong>verb</strong>: <code>get()</code>, <code>post()</code>, <code>put()</code>, <code>delete()</code>, and <code>patch()</code>:</p>
<pre><code class="lang-js">app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> { <span class="hljs-comment">/* */</span> })
app.post(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> { <span class="hljs-comment">/* */</span> })
app.put(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> { <span class="hljs-comment">/* */</span> })
app.delete(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> { <span class="hljs-comment">/* */</span> })
app.patch(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> { <span class="hljs-comment">/* */</span> })
</code></pre>
<p>Those methods accept a callback function – which is called when a request is started – and we need to handle it.</p>
<p>We pass in an arrow function:</p>
<pre><code class="lang-js">(req, res) =&gt; res.send(<span class="hljs-string">'Hello World!'</span>)
</code></pre>
<p>Express sends us two objects in this callback, which we called <code>req</code> and <code>res</code>. They represent the Request and the Response objects.</p>
<p>Both are standards and you can read more on them <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Request">here</a> and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Response">here</a>.</p>
<p>Request is the HTTP request. It gives us all the request information, including the request parameters, the headers, the body of the request, and more.</p>
<p>Response is the HTTP response object that we'll send to the client.</p>
<p>What we do in this callback is send the 'Hello World!' string to the client, using the <code>Response.send()</code> method.</p>
<p>This method sets that string as the body, and it closes the connection.</p>
<p>The last line of the example actually starts the server, and tells it to listen on port <code>3000</code>. We pass in a callback that is called when the server is ready to accept new requests.</p>
<h2 id="heading-request-parameters">Request Parameters</h2>
<p>I mentioned how the Request object holds all the HTTP request information.</p>
<p>These are the main properties you'll likely use:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Property</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td>.app</td><td>holds a reference to the Express app object</td></tr>
<tr>
<td>.baseUrl</td><td>the base path on which the app responds</td></tr>
<tr>
<td>.body</td><td>contains the data submitted in the request body (must be parsed and populated manually before you can access it)</td></tr>
<tr>
<td>.cookies</td><td>contains the cookies sent by the request (needs the <code>cookie-parser</code> middleware)</td></tr>
<tr>
<td>.hostname</td><td>the hostname as defined in the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Host">Host HTTP header</a> value</td></tr>
<tr>
<td>.ip</td><td>the client IP</td></tr>
<tr>
<td>.method</td><td>the HTTP method used</td></tr>
<tr>
<td>.params</td><td>the route named parameters</td></tr>
<tr>
<td>.path</td><td>the URL path</td></tr>
<tr>
<td>.protocol</td><td>the request protocol</td></tr>
<tr>
<td>.query</td><td>an object containing all the query strings used in the request</td></tr>
<tr>
<td>.secure</td><td>true if the request is secure (uses HTTPS)</td></tr>
<tr>
<td>.signedCookies</td><td>contains the signed cookies sent by the request (needs the <code>cookie-parser</code> middleware)</td></tr>
<tr>
<td>.xhr</td><td>true if the request is an <a target="_blank" href="https://www.freecodecamp.org/news/xhr/">XMLHttpRequest</a></td></tr>
</tbody>
</table>
</div><h2 id="heading-how-to-send-a-response-to-the-client">How to Send a Response to the Client</h2>
<p>In the Hello World example, we used the <code>send()</code> method of the Response object to send a simple string as a response, and to close the connection:</p>
<pre><code class="lang-js">(req, res) =&gt; res.send(<span class="hljs-string">'Hello World!'</span>)
</code></pre>
<p>If you pass in a string, it sets the <code>Content-Type</code> header to <code>text/html</code>.</p>
<p>If you pass in an object or an array, it sets the <code>application/json</code> <code>Content-Type</code> header, and parses that parameter into <a target="_blank" href="https://www.freecodecamp.org/news/json/">JSON</a>.</p>
<p>After this, <code>send()</code> closes the connection.</p>
<p><code>send()</code> automatically sets the <code>Content-Length</code> HTTP response header, unlike <code>end()</code> which requires you to do that.</p>
<h3 id="heading-how-to-use-end-to-send-an-empty-response">How to use end() to send an empty response</h3>
<p>An alternative way to send the response, without any body, is by using the <code>Response.end()</code> method:</p>
<pre><code class="lang-js">res.end()
</code></pre>
<h3 id="heading-how-to-set-the-http-response-status">How to set the HTTP response status</h3>
<p>Use the <code>status()</code> method on the response object:</p>
<pre><code class="lang-js">res.status(<span class="hljs-number">404</span>).end()
</code></pre>
<p>or</p>
<pre><code class="lang-js">res.status(<span class="hljs-number">404</span>).send(<span class="hljs-string">'File not found'</span>)
</code></pre>
<p><code>sendStatus()</code> is a shortcut:</p>
<pre><code class="lang-js">res.sendStatus(<span class="hljs-number">200</span>)
<span class="hljs-comment">// === res.status(200).send('OK')</span>

res.sendStatus(<span class="hljs-number">403</span>)
<span class="hljs-comment">// === res.status(403).send('Forbidden')</span>

res.sendStatus(<span class="hljs-number">404</span>)
<span class="hljs-comment">// === res.status(404).send('Not Found')</span>

res.sendStatus(<span class="hljs-number">500</span>)
<span class="hljs-comment">// === res.status(500).send('Internal Server Error')</span>
</code></pre>
<h2 id="heading-how-to-send-a-json-response">How to Send a JSON Response</h2>
<p>When you listen for connections on a route in Express, the callback function will be invoked on every network call with a Request object instance and a Response object instance.</p>
<p>Example:</p>
<pre><code class="lang-js">app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> res.send(<span class="hljs-string">'Hello World!'</span>))
</code></pre>
<p>Here we used the <code>Response.send()</code> method, which accepts any string.</p>
<p>You can send <a target="_blank" href="https://www.freecodecamp.org/news/json/">JSON</a> to the client by using <code>Response.json()</code>, a useful method.</p>
<p>It accepts an object or array, and converts it to JSON before sending it:</p>
<pre><code class="lang-js">res.json({ <span class="hljs-attr">username</span>: <span class="hljs-string">'Flavio'</span> })
</code></pre>
<h2 id="heading-how-to-manage-cookies">How to Manage Cookies</h2>
<p>Use the <code>Response.cookie()</code> method to manipulate your cookies.</p>
<p>Examples:</p>
<pre><code class="lang-js">res.cookie(<span class="hljs-string">'username'</span>, <span class="hljs-string">'Flavio'</span>)
</code></pre>
<p>This method accepts a third parameter, which contains various options:</p>
<pre><code class="lang-js">res.cookie(<span class="hljs-string">'username'</span>, <span class="hljs-string">'Flavio'</span>, { <span class="hljs-attr">domain</span>: <span class="hljs-string">'.flaviocopes.com'</span>, <span class="hljs-attr">path</span>: <span class="hljs-string">'/administrator'</span>, <span class="hljs-attr">secure</span>: <span class="hljs-literal">true</span> })

res.cookie(<span class="hljs-string">'username'</span>, <span class="hljs-string">'Flavio'</span>, { <span class="hljs-attr">expires</span>: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-built_in">Date</span>.now() + <span class="hljs-number">900000</span>), <span class="hljs-attr">httpOnly</span>: <span class="hljs-literal">true</span> })
</code></pre>
<p>The most useful parameters you can set are:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Value</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>domain</code></td><td>The <a target="_blank" href="https://www.freecodecamp.org/news/cookies/#set-a-cookie-domain">cookie domain name</a></td></tr>
<tr>
<td><code>expires</code></td><td>Set the <a target="_blank" href="https://www.freecodecamp.org/news/cookies/#set-a-cookie-expiration-date">cookie expiration date</a>. If missing, or 0, the cookie is a session cookie</td></tr>
<tr>
<td><code>httpOnly</code></td><td>Set the cookie to be accessible only by the web server. See <a target="_blank" href="https://www.freecodecamp.org/news/cookies/#httponly">HttpOnly</a></td></tr>
<tr>
<td><code>maxAge</code></td><td>Set the expiry time relative to the current time, expressed in milliseconds</td></tr>
<tr>
<td><code>path</code></td><td>The <a target="_blank" href="https://www.freecodecamp.org/news/cookies/#set-a-cookie-path">cookie path</a>. Defaults to '/'</td></tr>
<tr>
<td><code>secure</code></td><td>Marks the <a target="_blank" href="https://www.freecodecamp.org/news/cookies/#secure">cookie HTTPS only</a></td></tr>
<tr>
<td><code>signed</code></td><td>Set the cookie to be signed</td></tr>
<tr>
<td><code>sameSite</code></td><td>Value of <a target="_blank" href="https://www.freecodecamp.org/news/cookies/#samesite"><code>SameSite</code></a></td></tr>
</tbody>
</table>
</div><p>A cookie can be cleared with:</p>
<pre><code class="lang-js">res.clearCookie(<span class="hljs-string">'username'</span>)
</code></pre>
<h2 id="heading-how-to-work-with-http-headers">How to Work with HTTP Headers</h2>
<h3 id="heading-how-to-access-http-headers-values-from-a-request">How to access HTTP headers values from a request</h3>
<p>You can access all the HTTP headers using the <code>Request.headers</code> property:</p>
<pre><code class="lang-js">app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(req.headers)
})
</code></pre>
<p>Use the <code>Request.header()</code> method to access one individual request header's value:</p>
<pre><code class="lang-js">app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  req.header(<span class="hljs-string">'User-Agent'</span>)
})
</code></pre>
<h3 id="heading-how-to-change-any-http-header-value-for-a-response">How to change any HTTP header value for a response</h3>
<p>You can change any HTTP header value using <code>Response.set()</code>:</p>
<pre><code class="lang-js">res.set(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/html'</span>)
</code></pre>
<p>There is a shortcut for the Content-Type header, however:</p>
<pre><code class="lang-js">res.type(<span class="hljs-string">'.html'</span>)
<span class="hljs-comment">// =&gt; 'text/html'</span>

res.type(<span class="hljs-string">'html'</span>)
<span class="hljs-comment">// =&gt; 'text/html'</span>

res.type(<span class="hljs-string">'json'</span>)
<span class="hljs-comment">// =&gt; 'application/json'</span>

res.type(<span class="hljs-string">'application/json'</span>)
<span class="hljs-comment">// =&gt; 'application/json'</span>

res.type(<span class="hljs-string">'png'</span>)
<span class="hljs-comment">// =&gt; image/png:</span>
</code></pre>
<h2 id="heading-how-to-handle-redirects">How to Handle Redirects</h2>
<p>Redirects are common in Web Development. You can create a redirect using the <code>Response.redirect()</code> method:</p>
<pre><code class="lang-js">res.redirect(<span class="hljs-string">'/go-there'</span>)
</code></pre>
<p>This creates a 302 redirect.</p>
<p>A 301 redirect is made in this way:</p>
<pre><code class="lang-js">res.redirect(<span class="hljs-number">301</span>, <span class="hljs-string">'/go-there'</span>)
</code></pre>
<p>You can specify an absolute path (<code>/go-there</code>), an absolute URL (<code>https://anothersite.com</code>), a relative path (<code>go-there</code>) or use the <code>..</code> to go back one level:</p>
<pre><code class="lang-js">res.redirect(<span class="hljs-string">'../go-there'</span>)
res.redirect(<span class="hljs-string">'..'</span>)
</code></pre>
<p>You can also redirect back to the Referrer HTTP header value (defaulting to <code>/</code> if not set) using</p>
<pre><code class="lang-js">res.redirect(<span class="hljs-string">'back'</span>)
</code></pre>
<h2 id="heading-routing-in-express">Routing in Express</h2>
<p>Routing is the process of determining what should happen when a URL is called, or also which parts of the application should handle a specific incoming request.</p>
<p>In the Hello World example we used this code:</p>
<pre><code class="lang-js">app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> { <span class="hljs-comment">/* */</span> })
</code></pre>
<p>This creates a route that maps accessing the root domain URL <code>/</code> using the HTTP GET method to the response we want to provide.</p>
<h3 id="heading-named-parameters">Named parameters</h3>
<p>What if we want to listen for custom requests? Maybe we want to create a service that accepts a string and returns it as uppercase – and we don't want the parameter to be sent as a query string, but as part of the URL. In a case like that, we use named parameters:</p>
<pre><code class="lang-js">app.get(<span class="hljs-string">'/uppercase/:theValue'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> res.send(req.params.theValue.toUpperCase()))
</code></pre>
<p>If we send a request to <code>/uppercase/test</code>, we'll get <code>TEST</code> in the body of the response.</p>
<p>You can use multiple named parameters in the same URL, and they will all be stored in <code>req.params</code>.</p>
<h3 id="heading-how-to-use-a-regular-expression-to-match-a-path">How to use a regular expression to match a path</h3>
<p>You can use <a target="_blank" href="https://flaviocopes.com/javascript-regular-expressions/">regular expressions</a> to match multiple paths with one statement:</p>
<pre><code class="lang-js">app.get(<span class="hljs-regexp">/post/</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> { <span class="hljs-comment">/* */</span> })
</code></pre>
<p>will match <code>/post</code>, <code>/post/first</code>, <code>/thepost</code>, <code>/posting/something</code>, and so on.</p>
<h2 id="heading-templates-in-express">Templates in Express</h2>
<p>Express is capable of handling server-side template engines.</p>
<p>Template engines allow us to add data to a view, and generate HTML dynamically.</p>
<p>Express uses Jade as the default. Jade is the old version of Pug, specifically Pug 1.0.</p>
<p>Note that the name was changed from Jade to Pug due to a trademark issue in 2016, when the project released version 2. You can still use Jade, aka Pug 1.0, but going forward, it's best to use Pug 2.0</p>
<p>Although the last version of Jade is getting old, it's still the default in Express for backward compatibility reasons.</p>
<p>In any new project, you should use Pug or another engine of your choice. The official site of Pug is <a target="_blank" href="https://pugjs.org/">https://pugjs.org/</a>.</p>
<p>You can use many different template engines, including Pug, Handlebars, Mustache, EJS and more.</p>
<p>To use Pug we must first install it:</p>
<pre><code class="lang-bash">npm install pug
</code></pre>
<p>and when initializing the Express app, we need to set it:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)
<span class="hljs-keyword">const</span> app = express()
app.set(<span class="hljs-string">'view engine'</span>, <span class="hljs-string">'pug'</span>)
</code></pre>
<p>We can now start writing our templates in <code>.pug</code> files.</p>
<p>Create an about view:</p>
<pre><code class="lang-js">app.get(<span class="hljs-string">'/about'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.render(<span class="hljs-string">'about'</span>)
})
</code></pre>
<p>and the template in <code>views/about.pug</code>:</p>
<pre><code class="lang-javascript">p Hello <span class="hljs-keyword">from</span> Flavio
</code></pre>
<p>This template will create a <code>p</code> tag with the content <code>Hello from Flavio</code>.</p>
<p>You can interpolate a variable using this code:</p>
<pre><code class="lang-js">app.get(<span class="hljs-string">'/about'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.render(<span class="hljs-string">'about'</span>, { <span class="hljs-attr">name</span>: <span class="hljs-string">'Flavio'</span> })
})
</code></pre>
<pre><code class="lang-javascript">p Hello <span class="hljs-keyword">from</span> #{name}
</code></pre>
<p>Look at the <a target="_blank" href="https://flaviocopes.com/pug">Pug guide</a> for more information on how to use Pug.</p>
<p>This online converter from HTML to Pug will be a great help: <a target="_blank" href="https://html-to-pug.com/">https://html-to-pug.com/</a>.</p>
<h2 id="heading-express-middleware">Express Middleware</h2>
<p>A middleware is a function that hooks into the routing process, performing an arbitrary operation at some point in the chain (depending on what we want it to do).</p>
<p>It's commonly used to edit the request or response objects, or terminate the request before it reaches the route handler code.</p>
<p>Middleware is added to the execution stack like so:</p>
<pre><code class="lang-js">app.use(<span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =&gt;</span> { <span class="hljs-comment">/* */</span> })
</code></pre>
<p>This is similar to defining a route, but in addition to the Request and Response objects instances, we also have a reference to the <em>next</em> middleware function, which we assign to the variable <code>next</code>.</p>
<p>We always call <code>next()</code> at the end of our middleware function, in order to pass the execution to the next handler. That is unless we want to prematurely end the response and send it back to the client.</p>
<p>You typically use pre-made middleware, in the form of <code>npm</code> packages. You can find a big list of the available ones <a target="_blank" href="https://expressjs.com/en/resources/middleware.html">here</a>.</p>
<p>One example is <code>cookie-parser</code>, which is used to parse cookies into the <code>req.cookies</code> object. You can install it using <code>npm install cookie-parser</code> and you use it like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)
<span class="hljs-keyword">const</span> app = express()
<span class="hljs-keyword">const</span> cookieParser = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cookie-parser'</span>)

app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> res.send(<span class="hljs-string">'Hello World!'</span>))

app.use(cookieParser())
app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server ready'</span>))
</code></pre>
<p>We can also set a middleware function to run for specific routes only (not for all), by using it as the second parameter of the route definition:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myMiddleware = <span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =&gt;</span> {
  <span class="hljs-comment">/* ... */</span>
  next()
}

app.get(<span class="hljs-string">'/'</span>, myMiddleware, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> res.send(<span class="hljs-string">'Hello World!'</span>))
</code></pre>
<p>If you need to store data that's generated in a middleware to pass it down to subsequent middleware functions, or to the request handler, you can use the <code>Request.locals</code> object. It will attach that data to the current request:</p>
<pre><code class="lang-js">req.locals.name = <span class="hljs-string">'Flavio'</span>
</code></pre>
<h2 id="heading-how-to-serve-static-assets-with-express">How to Serve Static Assets with Express</h2>
<p>It's common to have images, CSS, and more in a <code>public</code> subfolder, and expose them to the root level:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)
<span class="hljs-keyword">const</span> app = express()

app.use(express.static(<span class="hljs-string">'public'</span>))

<span class="hljs-comment">/* ... */</span>

app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server ready'</span>))
</code></pre>
<p>If you have an <code>index.html</code> file in <code>public/</code>, that will be served if you now hit the root domain URL (<code>http://localhost:3000</code>)</p>
<h2 id="heading-how-to-send-files-to-the-client">How to Send Files to the Client</h2>
<p>Express provides a handy method to transfer a file as an attachment: <code>Response.download()</code>.</p>
<p>Once a user hits a route that sends a file using this method, browsers will prompt the user to download.</p>
<p>The <code>Response.download()</code> method allows you to send a file attached to the request, and the browser, instead of showing it in the page, will save it to disk.</p>
<pre><code class="lang-js">app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> res.download(<span class="hljs-string">'./file.pdf'</span>))
</code></pre>
<p>In the context of an app:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)
<span class="hljs-keyword">const</span> app = express()

app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> res.download(<span class="hljs-string">'./file.pdf'</span>))
app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server ready'</span>))
</code></pre>
<p>You can set the file to be sent with a custom filename:</p>
<pre><code class="lang-js">res.download(<span class="hljs-string">'./file.pdf'</span>, <span class="hljs-string">'user-facing-filename.pdf'</span>)
</code></pre>
<p>This method provides a callback function which you can use to execute code once the file has been sent:</p>
<pre><code class="lang-js">res.download(<span class="hljs-string">'./file.pdf'</span>, <span class="hljs-string">'user-facing-filename.pdf'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (err) {
    <span class="hljs-comment">//handle error</span>
    <span class="hljs-keyword">return</span>
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-comment">//do something</span>
  }
})
</code></pre>
<h2 id="heading-sessions-in-express">Sessions in Express</h2>
<p>By default Express requests are sequential and no request can be linked to another. There is no way to know if this request comes from a client that already performed a request previously.</p>
<p>Users cannot be identified unless using some kind of mechanism that makes it possible.</p>
<p>That's what sessions are.</p>
<p>When implemented, every user of your API or website will be assigned a unique session, and this allows you to store the user's state.</p>
<p>We'll use the <code>express-session</code> module, which is maintained by the Express team.</p>
<p>You can install it using this command:</p>
<pre><code class="lang-bash">npm install express-session
</code></pre>
<p>and once you're done, you can instantiate it in your application with this one:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> session = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express-session'</span>)
</code></pre>
<p>This is a middleware, so you <em>install</em> it in Express using the following:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)
<span class="hljs-keyword">const</span> session = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express-session'</span>)

<span class="hljs-keyword">const</span> app = express()
app.use(session({
  <span class="hljs-string">'secret'</span>: <span class="hljs-string">'343ji43j4n3jn4jk3n'</span>
}))
</code></pre>
<p>After this is done, all the requests to the app routes are now using sessions.</p>
<p><code>secret</code> is the only required parameter, but there are many more you can use. It should be a randomly unique string for your application.</p>
<p>The session is attached to the request, so you can access it using <code>req.session</code> here:</p>
<pre><code class="lang-js">app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =&gt;</span> {
  <span class="hljs-comment">// req.session</span>
}
</code></pre>
<p>This object can be used to get data out of the session, and also to set data:</p>
<pre><code class="lang-js">req.session.name = <span class="hljs-string">'Flavio'</span>
<span class="hljs-built_in">console</span>.log(req.session.name) <span class="hljs-comment">// 'Flavio'</span>
</code></pre>
<p>This data is serialized as <a target="_blank" href="https://www.freecodecamp.org/news/json/">JSON</a> when stored, so you are safe to use nested objects.</p>
<p>You can use sessions to communicate data to middleware that's executed later, or to retrieve it later on, on subsequent requests.</p>
<p>Where is the session data stored? It depends on how you set up the <code>express-session</code> module.</p>
<p>It can store session data in:</p>
<ul>
<li><p><strong>memory</strong>, not meant for production</p>
</li>
<li><p>a <strong>database</strong> like MySQL or Mongo</p>
</li>
<li><p>a <strong>memory cache</strong> like Redis or Memcached</p>
</li>
</ul>
<p>There is a big list of 3rd packages that implement a wide variety of different compatible caching stores in <a target="_blank" href="https://github.com/expressjs/session">https://github.com/expressjs/session</a>.</p>
<p>All solutions store the session id in a cookie, and keep the data server-side. The client will receive the session id in a cookie, and will send it along with every HTTP request.</p>
<p>We'll reference that server-side to associate the session id with the data stored locally.</p>
<p>Memory is the default, and it requires no special setup on your part. It's the simplest thing but it's meant only for development purposes.</p>
<p>The best choice is a memory cache like Redis, for which you need to setup its own infrastructure.</p>
<p>Another popular package to manage sessions in Express is <code>cookie-session</code>, which has a big difference: it stores data client-side in the cookie.</p>
<p>I do not recommend doing that because storing data in cookies means that it's stored client-side, and sent back and forth in every single request made by the user. It's also limited in size, as it can only store 4 kilobytes of data.</p>
<p>Cookies also need to be secured, but by default they are not, since secure Cookies are possible on HTTPS sites and you need to configure them if you have proxies.</p>
<h2 id="heading-how-to-validate-input-in-express">How to Validate Input in Express</h2>
<p>Let's see how to validate any data coming in as input in your Express endpoints.</p>
<p>Say you have a POST endpoint that accepts the name, email, and age parameters:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)
<span class="hljs-keyword">const</span> app = express()

app.use(express.json())

app.post(<span class="hljs-string">'/form'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> name  = req.body.name
  <span class="hljs-keyword">const</span> email = req.body.email
  <span class="hljs-keyword">const</span> age   = req.body.age
})
</code></pre>
<p>How do you perform server-side validation on those results to make sure that:</p>
<ul>
<li><p>name is a string of at least 3 characters?</p>
</li>
<li><p>email is a real email?</p>
</li>
<li><p>age is a number, between 0 and 110?</p>
</li>
</ul>
<p>The best way to handle validation on any kind of input coming from outside in Express is by using the <a target="_blank" href="https://express-validator.github.io"><code>express-validator</code> package</a>:</p>
<pre><code class="lang-bash">npm install express-validator
</code></pre>
<p>You require the <code>check</code> and <code>validationResult</code> objects from the package:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> { check, validationResult } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express-validator'</span>);
</code></pre>
<p>We pass an array of <code>check()</code> calls as the second argument of the <code>post()</code> call. Every <code>check()</code> call accepts the parameter name as argument. Then we call <code>validationResult()</code> to verify there were no validation errors. If there are any, we tell them to the client:</p>
<pre><code class="lang-js">app.post(<span class="hljs-string">'/form'</span>, [
  check(<span class="hljs-string">'name'</span>).isLength({ <span class="hljs-attr">min</span>: <span class="hljs-number">3</span> }),
  check(<span class="hljs-string">'email'</span>).isEmail(),
  check(<span class="hljs-string">'age'</span>).isNumeric()
], <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> errors = validationResult(req)
  <span class="hljs-keyword">if</span> (!errors.isEmpty()) {
    <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">422</span>).json({ <span class="hljs-attr">errors</span>: errors.array() })
  }

  <span class="hljs-keyword">const</span> name  = req.body.name
  <span class="hljs-keyword">const</span> email = req.body.email
  <span class="hljs-keyword">const</span> age   = req.body.age
})
</code></pre>
<p>Notice I used:</p>
<ul>
<li><p><code>isLength()</code></p>
</li>
<li><p><code>isEmail()</code></p>
</li>
<li><p><code>isNumeric()</code></p>
</li>
</ul>
<p>There are many more of these methods, all coming from <a target="_blank" href="https://github.com/chriso/validator.js#validators">validator.js</a>, including:</p>
<ul>
<li><p><code>contains()</code>, checks if value contains the specified value</p>
</li>
<li><p><code>equals()</code>, checks if value equals the specified value</p>
</li>
<li><p><code>isAlpha()</code></p>
</li>
<li><p><code>isAlphanumeric()</code></p>
</li>
<li><p><code>isAscii()</code></p>
</li>
<li><p><code>isBase64()</code></p>
</li>
<li><p><code>isBoolean()</code></p>
</li>
<li><p><code>isCurrency()</code></p>
</li>
<li><p><code>isDecimal()</code></p>
</li>
<li><p><code>isEmpty()</code></p>
</li>
<li><p><code>isFQDN()</code>, checks if it's a fully qualified domain name</p>
</li>
<li><p><code>isFloat()</code></p>
</li>
<li><p><code>isHash()</code></p>
</li>
<li><p><code>isHexColor()</code></p>
</li>
<li><p><code>isIP()</code></p>
</li>
<li><p><code>isIn()</code>, checks if the value is in an array of allowed values</p>
</li>
<li><p><code>isInt()</code></p>
</li>
<li><p><code>isJSON()</code></p>
</li>
<li><p><code>isLatLong()</code></p>
</li>
<li><p><code>isLength()</code></p>
</li>
<li><p><code>isLowercase()</code></p>
</li>
<li><p><code>isMobilePhone()</code></p>
</li>
<li><p><code>isNumeric()</code></p>
</li>
<li><p><code>isPostalCode()</code></p>
</li>
<li><p><code>isURL()</code></p>
</li>
<li><p><code>isUppercase()</code></p>
</li>
<li><p><code>isWhitelisted()</code>, checks the input against a whitelist of allowed characters</p>
</li>
</ul>
<p>You can validate the input against a regular expression using <code>matches()</code>.</p>
<p>Dates can be checked using:</p>
<ul>
<li><p><code>isAfter()</code>, checks if the entered date is after the one you pass</p>
</li>
<li><p><code>isBefore()</code>, checks if the entered date is before the one you pass</p>
</li>
<li><p><code>isISO8601()</code></p>
</li>
<li><p><code>isRFC3339()</code></p>
</li>
</ul>
<p>For exact details on how to use those validators, <a target="_blank" href="https://github.com/chriso/validator.js#validators">refer to the docs here</a>.</p>
<p>All those checks can be combined by piping them:</p>
<pre><code class="lang-js">check(<span class="hljs-string">'name'</span>)
  .isAlpha()
  .isLength({ <span class="hljs-attr">min</span>: <span class="hljs-number">10</span> })
</code></pre>
<p>If there is any error, the server automatically sends a response to communicate the error. For example if the email is not valid, this is what will be returned:</p>
<pre><code class="lang-js">{
  <span class="hljs-string">"errors"</span>: [{
    <span class="hljs-string">"location"</span>: <span class="hljs-string">"body"</span>,
    <span class="hljs-string">"msg"</span>: <span class="hljs-string">"Invalid value"</span>,
    <span class="hljs-string">"param"</span>: <span class="hljs-string">"email"</span>
  }]
}
</code></pre>
<p>This default error can be overridden for each check you perform, using <code>withMessage()</code>:</p>
<pre><code class="lang-js">check(<span class="hljs-string">'name'</span>)
  .isAlpha()
  .withMessage(<span class="hljs-string">'Must be only alphabetical chars'</span>)
  .isLength({ <span class="hljs-attr">min</span>: <span class="hljs-number">10</span> })
  .withMessage(<span class="hljs-string">'Must be at least 10 chars long'</span>)
</code></pre>
<p>What if you want to write your own special, custom validator? You can use the <code>custom</code> validator.</p>
<p>In the callback function you can reject the validation either by throwing an exception, or by returning a rejected promise:</p>
<pre><code class="lang-js">app.post(<span class="hljs-string">'/form'</span>, [
  check(<span class="hljs-string">'name'</span>).isLength({ <span class="hljs-attr">min</span>: <span class="hljs-number">3</span> }),
  check(<span class="hljs-string">'email'</span>).custom(<span class="hljs-function"><span class="hljs-params">email</span> =&gt;</span> {
    <span class="hljs-keyword">if</span> (alreadyHaveEmail(email)) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Email already registered'</span>)
    }
  }),
  check(<span class="hljs-string">'age'</span>).isNumeric()
], <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> name  = req.body.name
  <span class="hljs-keyword">const</span> email = req.body.email
  <span class="hljs-keyword">const</span> age   = req.body.age
})
</code></pre>
<p>The custom validator:</p>
<pre><code class="lang-js">check(<span class="hljs-string">'email'</span>).custom(<span class="hljs-function"><span class="hljs-params">email</span> =&gt;</span> {
  <span class="hljs-keyword">if</span> (alreadyHaveEmail(email)) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Email already registered'</span>)
  }
})
</code></pre>
<p>can be rewritten like this:</p>
<pre><code class="lang-js">check(<span class="hljs-string">'email'</span>).custom(<span class="hljs-function"><span class="hljs-params">email</span> =&gt;</span> {
  <span class="hljs-keyword">if</span> (alreadyHaveEmail(email)) {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Promise</span>.reject(<span class="hljs-string">'Email already registered'</span>)
  }
})
</code></pre>
<h2 id="heading-how-to-sanitizing-input-in-express">How to Sanitizing Input in Express</h2>
<p>You've seen how to validate input that comes from the outside world to your Express app.</p>
<p>There's one thing you quickly learn when you run a public-facing server: never trust the input.</p>
<p>Even if you sanitize and make sure that people can't enter weird things using client-side code, you'll still be subject to people using tools (even just the browser devtools) to POST directly to your endpoints.</p>
<p>Or bots trying every possible combination of exploit known to humans.</p>
<p>What you need to do is sanitize your input.</p>
<p>The <a target="_blank" href="https://express-validator.github.io"><code>express-validator</code> package</a> you already use to validate input can also conveniently be used to perform sanitization.</p>
<p>Say you have a POST endpoint that accepts the name, email, and age parameters:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)
<span class="hljs-keyword">const</span> app = express()

app.use(express.json())

app.post(<span class="hljs-string">'/form'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> name  = req.body.name
  <span class="hljs-keyword">const</span> email = req.body.email
  <span class="hljs-keyword">const</span> age   = req.body.age
})
</code></pre>
<p>You might validate it using:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)
<span class="hljs-keyword">const</span> app = express()

app.use(express.json())

app.post(<span class="hljs-string">'/form'</span>, [
  check(<span class="hljs-string">'name'</span>).isLength({ <span class="hljs-attr">min</span>: <span class="hljs-number">3</span> }),
  check(<span class="hljs-string">'email'</span>).isEmail(),
  check(<span class="hljs-string">'age'</span>).isNumeric()
], <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> name  = req.body.name
  <span class="hljs-keyword">const</span> email = req.body.email
  <span class="hljs-keyword">const</span> age   = req.body.age
})
</code></pre>
<p>You can add sanitization by piping the sanitization methods after the validation ones:</p>
<pre><code class="lang-js">app.post(<span class="hljs-string">'/form'</span>, [
  check(<span class="hljs-string">'name'</span>).isLength({ <span class="hljs-attr">min</span>: <span class="hljs-number">3</span> }).trim().escape(),
  check(<span class="hljs-string">'email'</span>).isEmail().normalizeEmail(),
  check(<span class="hljs-string">'age'</span>).isNumeric().trim().escape()
], <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-comment">//...</span>
})
</code></pre>
<p>Here I used the methods:</p>
<ul>
<li><p><code>trim()</code> trims characters (whitespace by default) at the beginning and at the end of a string</p>
</li>
<li><p><code>escape()</code> replaces <code>&lt;</code>, <code>&gt;</code>, <code>&amp;</code>, <code>'</code>, <code>"</code> and <code>/</code> with their corresponding HTML entities</p>
</li>
<li><p><code>normalizeEmail()</code> canonicalizes an email address. Accepts several options to lowercase email addresses or subaddresses (for example <code>flavio+newsletters@gmail.com</code>)</p>
</li>
</ul>
<p>Other sanitization methods:</p>
<ul>
<li><p><code>blacklist()</code> removes characters that appear in the blacklist</p>
</li>
<li><p><code>whitelist()</code> removes characters that do not appear in the whitelist</p>
</li>
<li><p><code>unescape()</code> replaces HTML encoded entities with <code>&lt;</code>, <code>&gt;</code>, <code>&amp;</code>, <code>'</code>, <code>"</code> and <code>/</code></p>
</li>
<li><p><code>ltrim()</code> like trim(), but only trims characters at the start of the string</p>
</li>
<li><p><code>rtrim()</code> like trim(), but only trims characters at the end of the string</p>
</li>
<li><p><code>stripLow()</code> removes ASCII control characters, which are normally invisible</p>
</li>
</ul>
<p>Force conversion to a format:</p>
<ul>
<li><p><code>toBoolean()</code> converts the input string to a boolean. Everything except for '0', 'false' and '' returns true. In strict mode only '1' and 'true' return true.</p>
</li>
<li><p><code>toDate()</code> converts the input string to a date, or null if the input is not a date</p>
</li>
<li><p><code>toFloat()</code> converts the input string to a float, or NaN if the input is not a float</p>
</li>
<li><p><code>toInt()</code> converts the input string to an integer, or NaN if the input is not an integer</p>
</li>
</ul>
<p>Like with custom validators, you can create a custom sanitizer.</p>
<p>In the callback function you just return the sanitized value:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> sanitizeValue = <span class="hljs-function"><span class="hljs-params">value</span> =&gt;</span> {
  <span class="hljs-comment">//sanitize...</span>
}

app.post(<span class="hljs-string">'/form'</span>, [
  check(<span class="hljs-string">'value'</span>).customSanitizer(<span class="hljs-function"><span class="hljs-params">value</span> =&gt;</span> {
    <span class="hljs-keyword">return</span> sanitizeValue(value)
  }),
], <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> value  = req.body.value
})
</code></pre>
<h2 id="heading-how-to-handle-forms-in-express">How to Handle Forms in Express</h2>
<p>This is an example of an HTML form:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"POST"</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"/submit-form"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span> /&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> /&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<p>When the user presses the submit button, the browser will automatically make a <code>POST</code> request to the <code>/submit-form</code> URL on the same origin of the page. The browser sends the data contained, encoded as <code>application/x-www-form-urlencoded</code>. In this particular example, the form data contains the <code>username</code> input field value.</p>
<p>Forms can also send data using the <code>GET</code> method, but the vast majority of the forms you'll build will use <code>POST</code>.</p>
<p>The form data will be sent in the POST request body.</p>
<p>To extract it, you will need to use the <code>express.urlencoded()</code> middleware:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)
<span class="hljs-keyword">const</span> app = express()

app.use(express.urlencoded({
  <span class="hljs-attr">extended</span>: <span class="hljs-literal">true</span>
}))
</code></pre>
<p>Now, you need to create a <code>POST</code> endpoint on the <code>/submit-form</code> route, and any data will be available on <code>Request.body</code>:</p>
<pre><code class="lang-js">app.post(<span class="hljs-string">'/submit-form'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> username = req.body.username
  <span class="hljs-comment">//...</span>
  res.end()
})
</code></pre>
<p>Don't forget to validate the data before using it with <code>express-validator</code>.</p>
<h2 id="heading-how-to-handle-file-uploads-in-forms-in-express">How to Handle File Uploads in Forms in Express</h2>
<p>This is an example of an HTML form that allows a user to upload a file:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"POST"</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"/submit-form"</span> <span class="hljs-attr">enctype</span>=<span class="hljs-string">"multipart/form-data"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"file"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"document"</span> /&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> /&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<p>Don't forget to add <code>enctype="multipart/form-data"</code> to the form, or files won't be uploaded.</p>
<p>When the user press the submit button, the browser will automatically make a <code>POST</code> request to the <code>/submit-form</code> URL on the same origin of the page. The browser sends the data contained, not encoded as as a normal form <code>application/x-www-form-urlencoded</code>, but as <code>multipart/form-data</code>.</p>
<p>On the server-side, handling multipart data can be tricky and error prone, so we are going to use a utility library called <strong>formidable</strong>. <a target="_blank" href="https://github.com/felixge/node-formidable">Here's the GitHub repo</a> – it has over 4000 stars and is well-maintained.</p>
<p>You can install it using:</p>
<pre><code class="lang-bash">npm install formidable
</code></pre>
<p>Then include it in your Node.js file:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)
<span class="hljs-keyword">const</span> app = express()
<span class="hljs-keyword">const</span> formidable = <span class="hljs-built_in">require</span>(<span class="hljs-string">'formidable'</span>)
</code></pre>
<p>Now, in the <code>POST</code> endpoint on the <code>/submit-form</code> route, we instantiate a new Formidable form using <code>formidable.IncomingForm()</code>:</p>
<pre><code class="lang-js">app.post(<span class="hljs-string">'/submit-form'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">new</span> formidable.IncomingForm()
})
</code></pre>
<p>After doing so, we need to be able to parse the form. We can do so synchronously by providing a callback, which means all files are processed. Once formidable is done, it makes them available:</p>
<pre><code class="lang-js">app.post(<span class="hljs-string">'/submit-form'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">new</span> formidable.IncomingForm().parse(req, <span class="hljs-function">(<span class="hljs-params">err, fields, files</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (err) {
      <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error'</span>, err)
      <span class="hljs-keyword">throw</span> err
    }
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Fields'</span>, fields)
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Files'</span>, files)
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> file <span class="hljs-keyword">of</span> <span class="hljs-built_in">Object</span>.entries(files)) {
      <span class="hljs-built_in">console</span>.log(file)
    }
  })
})
</code></pre>
<p>Or, you can use events instead of a callback. For example, you can be notified when each file is parsed, or other events such as completion of file processing, receiving a non-file field, or if an error occurred:</p>
<pre><code class="lang-js">app.post(<span class="hljs-string">'/submit-form'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">new</span> formidable.IncomingForm().parse(req)
    .on(<span class="hljs-string">'field'</span>, <span class="hljs-function">(<span class="hljs-params">name, field</span>) =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Field'</span>, name, field)
    })
    .on(<span class="hljs-string">'file'</span>, <span class="hljs-function">(<span class="hljs-params">name, file</span>) =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Uploaded file'</span>, name, file)
    })
    .on(<span class="hljs-string">'aborted'</span>, <span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Request aborted by the user'</span>)
    })
    .on(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
      <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error'</span>, err)
      <span class="hljs-keyword">throw</span> err
    })
    .on(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =&gt;</span> {
      res.end()
    })
})
</code></pre>
<p>Whichever way you choose, you'll get one or more Formidable.File objects, which give you information about the file uploaded. These are some of the methods you can call:</p>
<ul>
<li><p><code>file.size</code>, the file size in bytes</p>
</li>
<li><p><code>file.path</code>, the path the file is written to</p>
</li>
<li><p><code>file.name</code>, the name of the file</p>
</li>
<li><p><code>file.type</code>, the MIME type of the file</p>
</li>
</ul>
<p>The path defaults to the temporary folder and can be modified if you listen for the <code>fileBegin</code> event:</p>
<pre><code class="lang-js">app.post(<span class="hljs-string">'/submit-form'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">new</span> formidable.IncomingForm().parse(req)
    .on(<span class="hljs-string">'fileBegin'</span>, <span class="hljs-function">(<span class="hljs-params">name, file</span>) =&gt;</span> {
        file.path = __dirname + <span class="hljs-string">'/uploads/'</span> + file.name
    })
    .on(<span class="hljs-string">'file'</span>, <span class="hljs-function">(<span class="hljs-params">name, file</span>) =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Uploaded file'</span>, name, file)
    })
    <span class="hljs-comment">//...</span>
})
</code></pre>
<h2 id="heading-thank-you-for-reading">Thank you for reading!</h2>
<p>That's it for this handbook. And don't forget that <a target="_blank" href="https://thevalleyofcode.com/download/express/">you can get a PDF and ePub version of this Express Handbook</a> if you'd like.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Swift Handbook – Learn Swift for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ Introduction to Swift The Swift programming language was created by Apple in 2014. It's the official language that works with the whole Apple Operating Systems lineup: iOS, iPadOS, watchOS, macOS, and tvOS. Swift is an open source, general purpose, c... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-swift-handbook/</link>
                <guid isPermaLink="false">66bb5ac25a83db22bea98450</guid>
                
                    <category>
                        <![CDATA[ Apple ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Swift ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Flavio Copes ]]>
                </dc:creator>
                <pubDate>Mon, 24 Oct 2022 21:04:27 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/10/pexels-quang-nguyen-vinh-6131283.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <h2 id="heading-introduction-to-swift">Introduction to Swift</h2>
<p>The Swift programming language was created by Apple in 2014. It's the official language that works with the whole Apple Operating Systems lineup: iOS, iPadOS, watchOS, macOS, and tvOS.</p>
<p>Swift is an open source, general purpose, compiled programming language that's statically typed.</p>
<p>Every value has a type assigned. The type of a value is always checked when used as an argument or returned, at compile time. If there is a mismatch, the program will not compile.</p>
<p>Swift's compiler is LLVM, and it is included within Xcode, the standard IDE you use for Apple software development.</p>
<p>Swift is a modern programming language that was designed to "fit" in an ecosystem that was previously designed for a different programming language called Objective-C.</p>
<p>Most of the software running on the iPhone and Mac today is based on Objective-C code, even for official Apple apps. But Swift usage is gaining traction year after year. While Objective-C will be used for years to maintain and improve existing apps, new applications are likely going to be created with Swift.</p>
<p>Before Apple introduced Swift, Objective-C was heavily developed to introduce new capabilities and features. But in the recent years this effort has decreased a lot in favor of Swift development.</p>
<p>This does not mean Objective-C is dead or not worth learning: Objective-C is still an essential tool for any Apple developer.</p>
<p>That said, I am not going to cover Objective-C here, because we're focusing on Swift – the present and future of the Apple platform.</p>
<p>In just 6 years, Swift has gone through 5 major versions, and we're now (at the time of writing) at version 5.</p>
<p>Swift is famously Apple's products language, but it is not an Apple-only language. You can use it on several other platforms. </p>
<p>It is open source, so porting the language to other platforms does not require any permission or licensing, and you can find Swift projects to create Web servers and APIs (<a target="_blank" href="https://github.com/vapor/vapor">https://github.com/vapor/vapor</a>) as well as projects to interact with microcontrollers.</p>
<p>Swift is a general-purpose language, built with modern concepts, and it has a bright future.</p>
<h2 id="heading-what-well-cover-here">What We'll Cover Here</h2>
<p>The goal of this book is to get you up and running with Swift, starting from zero.</p>
<p>If you have a Mac or an iPad, I recommend you to download the Playgrounds application made by Apple from the App Store. </p>
<p>This app lets you run snippets of Swift code without having to create a full app first. It's a very handy way to test your code, not just when you start learning, but whenever you need to try some code.</p>
<p>It also contains a series of awesome examples and tutorials to expand your Swift and iOS knowledge.</p>
<p>Note: <a target="_blank" href="https://thevalleyofcode.com/download/swift/">You can get a PDF and ePub version of this Swift Beginner's Handbook</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-introduction-to-swift">Introduction to Swift</a></li>
<li><a class="post-section-overview" href="#heading-variables-in-swift">Variables in Swift</a></li>
<li><a class="post-section-overview" href="#heading-objects-in-swift">Objects in Swift</a></li>
<li><a class="post-section-overview" href="#heading-operators-in-swift">Operators in Swift</a></li>
<li><a class="post-section-overview" href="#heading-conditionals-in-swift">Conditionals in Swift</a></li>
<li><a class="post-section-overview" href="#heading-loops-in-swift">Loops in Swift</a></li>
<li><a class="post-section-overview" href="#heading-how-to-write-comments-in-swift">How to Write Comments in Swift</a></li>
<li><a class="post-section-overview" href="#heading-semicolons-in-swift">Semicolons in Swift</a></li>
<li><a class="post-section-overview" href="#heading-numbers-in-swift">Numbers in Swift</a></li>
<li><a class="post-section-overview" href="#heading-strings-in-swift">Strings in Swift</a></li>
<li><a class="post-section-overview" href="#heading-booleans-in-swift">Booleans in Swift</a></li>
<li><a class="post-section-overview" href="#heading-arrays-in-swift">Arrays in Swift</a></li>
<li><a class="post-section-overview" href="#heading-sets-in-swift">Sets in Swift</a></li>
<li><a class="post-section-overview" href="#heading-dictionaries-in-swift">Dictionaries in Swift</a></li>
<li><a class="post-section-overview" href="#heading-tuples-in-swift">Tuples in Swift</a></li>
<li><a class="post-section-overview" href="#heading-optionals-and-nil-in-swift">Optionals and <code>nil</code> in Swift</a> </li>
<li><a class="post-section-overview" href="#heading-enumerations-in-swift">Enumerations in Swift</a></li>
<li><a class="post-section-overview" href="#heading-structures-in-swift">Structures in Swift</a></li>
<li><a class="post-section-overview" href="#heading-classes-in-swift">Classes in Swift</a></li>
<li><a class="post-section-overview" href="#heading-functions-in-swift">Functions in Swift</a></li>
<li><a class="post-section-overview" href="#heading-protocols-in-swift">Protocols in Swift</a></li>
<li><a class="post-section-overview" href="#heading-where-to-go-from-here">Where to Go From Here</a></li>
</ul>
<h2 id="heading-variables-in-swift">Variables in Swift</h2>
<p>Variables let us assign a value to a label. We define them using the <code>var</code> keyword:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> name = <span class="hljs-string">"Roger"</span>
<span class="hljs-keyword">var</span> age = <span class="hljs-number">8</span>
</code></pre>
<p>Once a variable is defined, we can change its value:</p>
<pre><code class="lang-swift">age = <span class="hljs-number">9</span>
</code></pre>
<p>Variables that you do not want to change can be defined as constants, using the <code>let</code> keyword:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> name = <span class="hljs-string">"Roger"</span>
<span class="hljs-keyword">let</span> age = <span class="hljs-number">8</span>
</code></pre>
<p>Changing the value of a constant is forbidden.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen-Shot-2020-11-01-at-07.51.48.png" alt="Image" width="600" height="400" loading="lazy">
<em>You can't change the value of a constant or you'll get this error</em></p>
<p>When you define a variable and you assign it a value, Swift implicitly infers the type of it.</p>
<p><code>8</code> is an <code>Int</code> value.</p>
<p><code>"Roger"</code> is a <code>String</code> value.</p>
<p>A decimal number like <code>3.14</code> is a <code>Double</code> value.</p>
<p>You can also specify the type at initialization time:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> age: <span class="hljs-type">Int</span> = <span class="hljs-number">8</span>
</code></pre>
<p>But it's typical to let Swift infer it, and it's mostly done when you declare a variable without initializing it.</p>
<p>You can declare a constant, and initialize it later:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> age : <span class="hljs-type">Int</span>

age = <span class="hljs-number">8</span>
</code></pre>
<p>Once a variable is defined, it is bound to that type. You cannot assign to it a different type, unless you explicitly convert it.</p>
<p>You can't do this:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> age = <span class="hljs-number">8</span>
age = <span class="hljs-string">"nine"</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen-Shot-2020-11-01-at-07.54.25.png" alt="Image" width="600" height="400" loading="lazy">
<em>Cannot assign value of type 'String' to type 'Int' error</em></p>
<p><code>Int</code> and <code>String</code> are just two of the built-in data types provided by Swift.</p>
<h2 id="heading-objects-in-swift">Objects in Swift</h2>
<p>In Swift, everything is an object. Even the <code>8</code> value we assigned to the <code>age</code> variable is an object.</p>
<p>In some languages, objects are a special type. But in Swift, everything is an object and this leads to one particular feature: every value can <em>receive messages</em>.</p>
<p>Each type can have multiple functions associated to it, which we call <strong>methods</strong>.</p>
<p>For example, talking about the <code>8</code> number value, we can call its <code>isMultiple</code> method, to check if the number is a multiple of another number:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen-Shot-2020-11-01-at-14.43.49.png" alt="Image" width="600" height="400" loading="lazy">
<em><code>isMultiple</code> method</em></p>
<p>A String value has another set of methods.</p>
<p>A type also has instance variables. For example the String type has the instance variable <code>count</code>, which gives you the number of characters in a string:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen-Shot-2020-11-01-at-14.45.39.png" alt="Image" width="600" height="400" loading="lazy">
<em>instance variable <code>count</code></em></p>
<p>Swift has 3 different <strong>object types</strong>, which we'll see more in details later on: <strong>classes</strong>, <strong>structs</strong> and <strong>enums</strong>.</p>
<p>Those are very different, but they have one thing in common: to object type, we can <strong>add methods</strong>, and to any value, of any object type, we can <strong>send messages</strong>.</p>
<h2 id="heading-operators-in-swift">Operators in Swift</h2>
<p>We can use a wide set of operators to operate on values.</p>
<p>We can divide operators in many categories. The first is the number of targets: 1 for <strong>unary operators</strong>, 2 for <strong>binary operators</strong> or 3 for the one and only <strong>ternary operator</strong>.</p>
<p>Then we can divide operators based on the kind of operation they perform:</p>
<ul>
<li>assignment operator</li>
<li>arithmetic operators</li>
<li>compound assignment operators</li>
<li>comparison operators</li>
<li>range operators</li>
<li>logical operators</li>
</ul>
<p>plus some more advanced ones, including nil-coalescing, ternary conditional, overflow, bitwise and pointwise operators.</p>
<p>Note: Swift allows you to create your own operators and define how operators work on your types you define.</p>
<h3 id="heading-assignment-operator-in-swift">Assignment operator in Swift</h3>
<p>You use the assignment operator to assign a value to a variable:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> age = <span class="hljs-number">8</span>
</code></pre>
<p>Or to assign a variable value to another variable:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> age = <span class="hljs-number">8</span>
<span class="hljs-keyword">var</span> another = age
</code></pre>
<h3 id="heading-arithmetic-operators-in-swift">Arithmetic operators in Swift</h3>
<p>Swift has a number of binary arithmetic operators: <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code> (division), <code>%</code> (remainder):</p>
<pre><code class="lang-swift"><span class="hljs-number">1</span> + <span class="hljs-number">1</span> <span class="hljs-comment">//2</span>
<span class="hljs-number">2</span> - <span class="hljs-number">1</span> <span class="hljs-comment">//1</span>
<span class="hljs-number">2</span> * <span class="hljs-number">2</span> <span class="hljs-comment">//4</span>
<span class="hljs-number">4</span> / <span class="hljs-number">2</span> <span class="hljs-comment">//2</span>
<span class="hljs-number">4</span> % <span class="hljs-number">3</span> <span class="hljs-comment">//1</span>
<span class="hljs-number">4</span> % <span class="hljs-number">2</span> <span class="hljs-comment">//0</span>
</code></pre>
<p><code>-</code> also works as a unary minus operator:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> hotTemperature = <span class="hljs-number">20</span>
<span class="hljs-keyword">let</span> freezingTemperature = -<span class="hljs-number">20</span>
</code></pre>
<p>You can also use <code>+</code> to concatenate String values:</p>
<pre><code class="lang-swift"><span class="hljs-string">"Roger"</span> + <span class="hljs-string">" is a good dog"</span>
</code></pre>
<h3 id="heading-compound-assignment-operators-in-swift">Compound assignment operators in Swift</h3>
<p>The compound assignment operators combine the assignment operator with arithmetic operators:</p>
<ul>
<li><code>+=</code></li>
<li><code>-=</code></li>
<li><code>*=</code></li>
<li><code>/=</code></li>
<li><code>%=</code></li>
</ul>
<p>Example:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> age = <span class="hljs-number">8</span>
age += <span class="hljs-number">1</span>
</code></pre>
<h3 id="heading-comparison-operators-in-swift">Comparison operators in Swift</h3>
<p>Swift defines a few comparison operators:</p>
<ul>
<li><code>==</code></li>
<li><code>!=</code></li>
<li><code>&gt;</code></li>
<li><code>&lt;</code></li>
<li><code>&gt;=</code></li>
<li><code>&lt;=</code></li>
</ul>
<p>You can use those operators to get a boolean value (<code>true</code> or <code>false</code>) depending on the result:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> a = <span class="hljs-number">1</span>
<span class="hljs-keyword">let</span> b = <span class="hljs-number">2</span>

a == b <span class="hljs-comment">//false</span>
a != b <span class="hljs-comment">//true</span>
a &gt; b <span class="hljs-comment">// false</span>
a &lt;= b <span class="hljs-comment">//true</span>
</code></pre>
<h3 id="heading-range-operators-in-swift">Range operators in Swift</h3>
<p>Range operators are used in loops. They allow us to define a range:</p>
<pre><code class="lang-swift"><span class="hljs-number">0</span>...<span class="hljs-number">3</span> <span class="hljs-comment">//4 times</span>
<span class="hljs-number">0</span>..&lt;<span class="hljs-number">3</span> <span class="hljs-comment">//3 times</span>

<span class="hljs-number">0</span>...<span class="hljs-built_in">count</span> <span class="hljs-comment">//"count" times</span>
<span class="hljs-number">0</span>..&lt;<span class="hljs-built_in">count</span> <span class="hljs-comment">//"count-1" times</span>
</code></pre>
<p>Here's a sample usage:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> <span class="hljs-built_in">count</span> = <span class="hljs-number">3</span>
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>...<span class="hljs-built_in">count</span> {
  <span class="hljs-comment">//loop body</span>
}
</code></pre>
<h3 id="heading-logical-operators-in-swift">Logical operators in Swift</h3>
<p>Swift gives us the following logical operators:</p>
<ul>
<li><code>!</code>, the unary operator NOT</li>
<li><code>&amp;&amp;</code>, the binary operator AND</li>
<li><code>||</code>, the binary operator OR</li>
</ul>
<p>Sample usage:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> condition1 = <span class="hljs-literal">true</span>
<span class="hljs-keyword">let</span> condition2 = <span class="hljs-literal">false</span>

!condition1 <span class="hljs-comment">//false</span>

condition1 &amp;&amp; condition2 <span class="hljs-comment">//false</span>
condition1 || condition2 <span class="hljs-comment">//true</span>
</code></pre>
<p>Those are mostly used in the <code>if</code> conditional expression evaluation:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">if</span> condition1 &amp;&amp; condition2 {
  <span class="hljs-comment">//if body</span>
}
</code></pre>
<h2 id="heading-conditionals-in-swift">Conditionals in Swift</h2>
<h3 id="heading-if-statements-in-swift"><code>if</code> statements in Swift</h3>
<p><code>if</code> statements are the most popular way to perform a conditional check. We use the <code>if</code> keyword followed by a boolean expression, followed by a block containing code that is run if the condition is true:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> condition = <span class="hljs-literal">true</span>
<span class="hljs-keyword">if</span> condition == <span class="hljs-literal">true</span> {
    <span class="hljs-comment">// code executed if the condition is true</span>
}
</code></pre>
<p>An <code>else</code> block is executed if the condition is false:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> condition = <span class="hljs-literal">true</span>
<span class="hljs-keyword">if</span> condition == <span class="hljs-literal">true</span> {
    <span class="hljs-comment">// code executed if the condition is true</span>
} <span class="hljs-keyword">else</span> {
    <span class="hljs-comment">// code executed if the condition is false</span>
}
</code></pre>
<p>You can optionally wrap the condition validation into parentheses if you prefer:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">if</span> (condition == <span class="hljs-literal">true</span>) {
    <span class="hljs-comment">// ...</span>
}
</code></pre>
<p>And you can also just write:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">if</span> condition {
    <span class="hljs-comment">// runs if `condition` is `true`</span>
}
</code></pre>
<p>or</p>
<pre><code class="lang-swift"><span class="hljs-keyword">if</span> !condition {
    <span class="hljs-comment">// runs if `condition` is `false`</span>
}
</code></pre>
<p>One thing that separates Swift from many other languages is that it prevents bugs caused by erroneously doing an assignment instead of a comparison. This means you can't do this:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">if</span> condition = <span class="hljs-literal">true</span> {
    <span class="hljs-comment">// The program does not compile</span>
}
</code></pre>
<p>The reason is that the assignment operator does not return anything, but the <code>if</code> conditional must be a boolean expression.</p>
<h3 id="heading-switch-statements-in-swift"><code>switch</code> statements in Swift</h3>
<p>Switch statements are a handy way to create a conditional with multiple options:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> name = <span class="hljs-string">"Roger"</span>

<span class="hljs-keyword">switch</span> name {
<span class="hljs-keyword">case</span> <span class="hljs-string">"Roger"</span>:
    <span class="hljs-built_in">print</span>(<span class="hljs-string">"Hello, mr. Roger!"</span>)
<span class="hljs-keyword">default</span>: 
    <span class="hljs-built_in">print</span>(<span class="hljs-string">"Hello, \(name)"</span>)
}
</code></pre>
<p>When the code of a case ends, the switch exits automatically.</p>
<p>A switch in Swift needs to cover all cases. If the <em>tag</em>, <code>name</code> in this case, is a string that can have any value, we need to add a <code>default</code> case, mandatory.</p>
<p>Otherwise with an enumeration, you can simply list all the options:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-keyword">case</span> dog
    <span class="hljs-keyword">case</span> cat
}

<span class="hljs-keyword">var</span> animal: <span class="hljs-type">Animal</span> = .dog

<span class="hljs-keyword">switch</span> animal {
<span class="hljs-keyword">case</span> .dog:
    <span class="hljs-built_in">print</span>(<span class="hljs-string">"Hello, dog!"</span>)
<span class="hljs-keyword">case</span> .cat:
    <span class="hljs-built_in">print</span>(<span class="hljs-string">"Hello, cat!"</span>)
}
</code></pre>
<p>A case can be a Range:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> age = <span class="hljs-number">20</span>

<span class="hljs-keyword">switch</span> age {
<span class="hljs-keyword">case</span> <span class="hljs-number">0</span>..&lt;<span class="hljs-number">18</span>:
    <span class="hljs-built_in">print</span>(<span class="hljs-string">"You can't drive!!"</span>)
<span class="hljs-keyword">default</span>: 
    <span class="hljs-built_in">print</span>(<span class="hljs-string">"You can drive"</span>)
}
</code></pre>
<h3 id="heading-ternary-conditional-operator-in-swift">Ternary conditional operator in Swift</h3>
<p>The ternary conditional operator is a shorter version of an <code>if</code> expression. It allows us to execute an expression if a condition is true, and another expression if the condition is false.</p>
<p>Here is the syntax:</p>
<pre><code><span class="hljs-string">`condition`</span> ? <span class="hljs-string">`value if true`</span> : <span class="hljs-string">`value if false`</span>
</code></pre><p>Example:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> num1 = <span class="hljs-number">1</span>
<span class="hljs-keyword">let</span> num2 = <span class="hljs-number">2</span>

<span class="hljs-keyword">let</span> smallerNumber = num1 &lt; num2 ? num1 : num2 

<span class="hljs-comment">// smallerNumber == 1</span>
</code></pre>
<p>The syntax is shorter than an <code>if</code> statement, and sometimes it might make more sense to use it.</p>
<h2 id="heading-loops-in-swift">Loops in Swift</h2>
<h3 id="heading-for-in-loops-in-swift"><code>for-in</code> loops in Swift</h3>
<p>You can use <code>for-in</code> loops to iterate a specific amount of times, using a range operator:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">for</span> index <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>...<span class="hljs-number">3</span> {
  <span class="hljs-comment">//iterate 4 times, `index` is: 0, 1, 2, 3</span>
}
</code></pre>
<p>You can iterate over the elements of an array or set:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> list = [<span class="hljs-string">"a"</span>, <span class="hljs-string">"b"</span>, <span class="hljs-string">"c"</span>]
<span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> list {
  <span class="hljs-comment">// `item` contains the element value</span>
}
</code></pre>
<p>And on the elements of a dictionary:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> list = [<span class="hljs-string">"a"</span>: <span class="hljs-number">1</span>, <span class="hljs-string">"b"</span>: <span class="hljs-number">2</span>, <span class="hljs-string">"c"</span>: <span class="hljs-number">2</span>]
<span class="hljs-keyword">for</span> (key, value) <span class="hljs-keyword">in</span> list {
  <span class="hljs-comment">// `key` contains the item key</span>
  <span class="hljs-comment">// `value` contains the item value</span>
}
</code></pre>
<h3 id="heading-while-loops-in-swift"><code>while</code> loops in Swift</h3>
<p>A <code>while</code> loop can be used to iterate on anything, and will run while the condition is <code>true</code>:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">while</span> [condition] {
    <span class="hljs-comment">//statements...</span>
}
</code></pre>
<p>The condition is checked at the start, before the loop block is executed.</p>
<p>Example:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> item = <span class="hljs-number">0</span>
<span class="hljs-keyword">while</span> item &lt;= <span class="hljs-number">3</span> { <span class="hljs-comment">//repeats 3 times</span>
    <span class="hljs-built_in">print</span>(item)
    item += <span class="hljs-number">1</span>
}
</code></pre>
<h3 id="heading-repeat-while-loops-in-swift"><code>repeat-while</code> loops in Swift</h3>
<p>A <code>repeat-while</code> loop in Swift is similar to the <code>while</code> loop. But in this case the condition is checked at the end, after the loop block, so the loop block is executed at least once. Then the condition is checked, and if it is evaluated as <code>true</code>, the loop block is repeated:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">repeat</span> {
    <span class="hljs-comment">//statements...</span>
} <span class="hljs-keyword">while</span> [condition]
</code></pre>
<p>Example:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> item = <span class="hljs-number">0</span>
<span class="hljs-keyword">repeat</span> { <span class="hljs-comment">//repeats 3 times</span>
    <span class="hljs-built_in">print</span>(item)
    item += <span class="hljs-number">1</span>
} <span class="hljs-keyword">while</span> item &lt; <span class="hljs-number">3</span>
</code></pre>
<h3 id="heading-continue-and-break-statements-in-swift"><code>continue</code> and <code>break</code> statements in Swift</h3>
<p>Swift provides you 2 statements that you can use to control the flow inside a loop: <code>continue</code> and <code>break</code>.</p>
<p>You use <code>continue</code> to stop the current iteration, and run the next iteration of the loop.</p>
<p><code>break</code> ends the loop, not executing any other iteration.</p>
<p>Example:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> list = [<span class="hljs-string">"a"</span>, <span class="hljs-string">"b"</span>, <span class="hljs-string">"c"</span>]
<span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> list {
  <span class="hljs-keyword">if</span> (item == <span class="hljs-string">"b"</span>) {
    <span class="hljs-keyword">break</span>
  }
  <span class="hljs-comment">//do something</span>
}
</code></pre>
<h2 id="heading-how-to-write-comments-in-swift">How to Write Comments in Swift</h2>
<p>A comment in Swift can take 2 forms: a single-line comment, and a multi-line comment.</p>
<p>A single-line comment looks like this:</p>
<pre><code class="lang-swift"><span class="hljs-comment">//this is a comment</span>
</code></pre>
<p>and and you can put it at the end of a line of code:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> a = <span class="hljs-number">1</span> <span class="hljs-comment">//this is a comment</span>
</code></pre>
<p>A multi-line comment is written using this syntax:</p>
<pre><code class="lang-swift"><span class="hljs-comment">/* this
 is
    a multi-line
 comment
*/</span>
</code></pre>
<p>Swift allows you to nest multi-line comments:</p>
<pre><code class="lang-swift"><span class="hljs-comment">/* this
 is
    a <span class="hljs-comment">/* nested */</span> multi-line
 comment
*/</span>
</code></pre>
<p>This is handy especially when commenting out large portions of code that already contain multi-line comments.</p>
<h2 id="heading-semicolons-in-swift">Semicolons in Swift</h2>
<p>In Swift, semicolons are generally optional.</p>
<p>You can write statements on separate lines, and you don't need to add a semicolon:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> list = [<span class="hljs-string">"a"</span>, <span class="hljs-string">"b"</span>, <span class="hljs-string">"c"</span>]
<span class="hljs-keyword">var</span> a = <span class="hljs-number">2</span>
</code></pre>
<p>You <em>can</em> add a semicolon, but it adds nothing meaningful in this case:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> list = [<span class="hljs-string">"a"</span>, <span class="hljs-string">"b"</span>, <span class="hljs-string">"c"</span>];
<span class="hljs-keyword">var</span> a = <span class="hljs-number">2</span>;
</code></pre>
<p>But if you want to write more than one statement on the same line, then you need to add a semicolon:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> a = <span class="hljs-number">2</span>; <span class="hljs-keyword">let</span> b = <span class="hljs-number">3</span>
</code></pre>
<h2 id="heading-numbers-in-swift">Numbers in Swift</h2>
<p>In Swift, numbers have 2 main types: <code>Int</code> and <code>Double</code>.</p>
<p>An <code>Int</code> is a number without decimal point. A <code>Double</code> is a number with decimal point.</p>
<p>Both use 64 bits, on modern computers that work with 64 bits, and 32 bit on 32-bit platforms.</p>
<p>The range of values they can store depends on the platform used, and can be retrieved using the <code>int</code> property of each type:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen-Shot-2020-11-02-at-07.41.09.png" alt="Image" width="600" height="400" loading="lazy">
<em>Range of int values</em></p>
<p>Then, in addition to <code>Int</code> and <code>Double</code>, we have lots of other numeric types. These were mostly used to interact with APIs built in the past and that needed to interact with C or Objective-C, and you must be aware that we have them:</p>
<ul>
<li><code>Int8</code> is an integer with 8 bits</li>
<li><code>Int16</code> is an integer with 16 bits</li>
<li><code>Int32</code> is an integer with 32 bits</li>
<li><code>Int64</code> is an integer with 64 bits</li>
<li><code>UInt8</code> is an unsigned integer with 8 bits</li>
<li><code>UInt16</code> is an unsigned integer with 16 bits</li>
<li><code>UInt32</code> is an unsigned integer with 32 bits</li>
<li><code>UInt64</code> is an unsigned integer with 64 bits</li>
<li><code>UInt</code> is like <code>Int</code>, but unsigned, and it ranges from 0 to <code>Int.max * 2</code>.</li>
<li><code>Float</code> is a decimal number with 32 bits.</li>
</ul>
<p>Then using Cocoa APIs you might use other numeric types like CLong, CGFloat, and more.</p>
<p>You will always use <code>Int</code> or <code>Double</code> in your code, and use those specific types only in particular cases.</p>
<p>Remember that you can always convert any of those types to <code>Int</code> and <code>Double</code> types, instantiating a number passing the value inside parentheses to <code>Double()</code> or <code>Int()</code>:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> age : <span class="hljs-type">UInt8</span> = <span class="hljs-number">3</span>
<span class="hljs-keyword">let</span> intAge = <span class="hljs-type">Int</span>(age)
</code></pre>
<p>You can also convert a number from <code>Double</code> to <code>Int</code>:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> age = <span class="hljs-type">Double</span>(<span class="hljs-number">3</span>)
<span class="hljs-keyword">let</span> <span class="hljs-built_in">count</span> = <span class="hljs-type">Int</span>(<span class="hljs-number">3.14</span>)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen-Shot-2020-11-02-at-07.59.19.png" alt="Image" width="600" height="400" loading="lazy">
<em>How to convert a number from <code>Double</code> to <code>Int</code></em></p>
<h2 id="heading-strings-in-swift">Strings in Swift</h2>
<p>Strings are one of the most popular tools in programming.</p>
<p>In Swift, you can define a string using the string literal syntax:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> name = <span class="hljs-string">"Roger"</span>
</code></pre>
<p>We use double quotes. Single quotes are not valid string delimiters.</p>
<p>A string can span over multiple lines using 3 double quotes:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> description = <span class="hljs-string">"""
    a long
      long 
          long description
    """</span>
</code></pre>
<p>You can use string interpolation to embed an expression in a string:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> age = <span class="hljs-number">8</span>

<span class="hljs-keyword">let</span> name = <span class="hljs-string">"""
    Roger, age \(age)
    Next year he will be \(age + 1)
    """</span>
</code></pre>
<p>You can concatenate two strings with the <code>+</code> operator:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> name = <span class="hljs-string">"Roger"</span>
name = name + <span class="hljs-string">" The Dog"</span>
</code></pre>
<p>And you can append text to a string with the <code>+=</code> operator:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> name = <span class="hljs-string">"Roger"</span>
name += <span class="hljs-string">" The Dog"</span>
</code></pre>
<p>Or using the <code>append(_:)</code> method:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> name = <span class="hljs-string">"Roger"</span>
name.append(<span class="hljs-string">" The Dog"</span>)
</code></pre>
<p>You can count the characters in a string using the <code>count</code> string property:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> name = <span class="hljs-string">"Roger"</span>
name.<span class="hljs-built_in">count</span> <span class="hljs-comment">//5</span>
</code></pre>
<p>Any string comes with a set of useful methods, for example:</p>
<ul>
<li><code>removeFirst()</code> to remove the first character</li>
<li><code>removeLast()</code> to remove the last character</li>
<li><code>lowercased()</code> to get a new string, lowercased</li>
<li><code>uppercased()</code> to get a new string, uppercased</li>
<li><code>starts(with:)</code> which returns true if the string starts with a specific substring</li>
<li><code>contains()</code> which returns true if the string contains a specific character</li>
</ul>
<p>and many, many more.</p>
<p>When you need to reference an item in the string, since strings in Swift are unicode, we can't simply reference the letter <code>o</code> in <code>let name = "Roger"</code> using <code>name[1]</code>. You need to work with indexes.</p>
<p>Any string provides the starting index with the <code>startIndex</code> property:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> name = <span class="hljs-string">"Roger"</span>
name.startIndex <span class="hljs-comment">//0</span>
</code></pre>
<p>To calculate a specific index in the string, you calculate it using the <code>index(i:offsetBy:)</code> method:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> name = <span class="hljs-string">"Roger"</span>
<span class="hljs-keyword">let</span> i = name.index(name.startIndex, offsetBy: <span class="hljs-number">2</span>)
name[i] <span class="hljs-comment">//"g"</span>
</code></pre>
<p>You can also use the index to get a substring:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> name = <span class="hljs-string">"Roger"</span>
<span class="hljs-keyword">let</span> i = name.index(name.startIndex, offsetBy: <span class="hljs-number">2</span>)
name.suffix(from: i) <span class="hljs-comment">//"ger"</span>

<span class="hljs-comment">//Or using the subscript:</span>

name[i...] <span class="hljs-comment">//"ger"</span>
</code></pre>
<p>When you get a substring from a string, the type of the result is <code>Substring</code>, not <code>String</code>.</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> name = <span class="hljs-string">"Roger"</span>
<span class="hljs-keyword">let</span> i = name.index(name.startIndex, offsetBy: <span class="hljs-number">2</span>)
<span class="hljs-built_in">print</span>(type(of: name.suffix(from: i))) 
<span class="hljs-comment">//Substring</span>
</code></pre>
<p>Substrings are more memory efficient, because you do not get a new string, but the same memory structure is used behind the scenes. But you need to be careful when you deal with strings a lot, as there are optimizations you can implement.</p>
<p>Strings are collections, and they can be iterated over in loops.</p>
<h2 id="heading-booleans-in-swift">Booleans in Swift</h2>
<p>Swift provides the <code>Bool</code> type, which can have two values: <code>true</code> and <code>false</code>.</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> done = <span class="hljs-literal">false</span>
done = <span class="hljs-literal">true</span>
</code></pre>
<p>Booleans are especially useful with conditional control structures like <code>if</code> statements or the ternary conditional operator:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> done = <span class="hljs-literal">true</span>

<span class="hljs-keyword">if</span> done == <span class="hljs-literal">true</span> {
    <span class="hljs-comment">//code</span>
}
</code></pre>
<h2 id="heading-arrays-in-swift">Arrays in Swift</h2>
<p>We use arrays to create a collection of items.</p>
<p>In this example we create an array holding 3 integers:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> list = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
</code></pre>
<p>We can access the first item using the syntax <code>list[0]</code>, the second using <code>list[1]</code>, and so on.</p>
<p>Elements in an array in Swift must have the same type.</p>
<p>The type can be inferred if you initialize the array at declaration time, like in the case above.</p>
<p>Otherwise the type of values an array can include must be declared, in this way:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> list: [<span class="hljs-type">Int</span>] = []
</code></pre>
<p>Another shorthand syntax is:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> list = [<span class="hljs-type">Int</span>]()
</code></pre>
<p>You can also explicitly declare the type at initialization, like this:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> list: [<span class="hljs-type">Int</span>] = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
</code></pre>
<p>A quick way to initialize an array is to use the range operator:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> list = <span class="hljs-type">Array</span>(<span class="hljs-number">1</span>...<span class="hljs-number">4</span>) <span class="hljs-comment">//[1, 2, 3, 4]</span>
</code></pre>
<p>To get the number of items in the array, use the <code>count</code> property:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> list = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
list.<span class="hljs-built_in">count</span> <span class="hljs-comment">//3</span>
</code></pre>
<p>If an array is empty, its <code>isEmpty</code> property is <code>true</code>.</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> list = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
list.isEmpty <span class="hljs-comment">//false</span>
</code></pre>
<p>You can append an item at the end of the array using the <code>append()</code> method:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> list: [<span class="hljs-type">Int</span>] = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
list.append(<span class="hljs-number">4</span>)
</code></pre>
<p>or you can insert an item at any position of the array using <code>insert(newElement: &lt;Type&gt; at: Int)</code>:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> list: [<span class="hljs-type">Int</span>] = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
list.insert(<span class="hljs-number">17</span>, at: <span class="hljs-number">2</span>)
<span class="hljs-comment">//list is [1, 2, 17, 3]</span>
</code></pre>
<p>An array must be declared as <code>var</code> to be modified. If it's declared with <code>let</code>, you cannot modify it by adding or removing elements.</p>
<p>To remove one item from the array, use <code>remove(at:)</code> passing the index of the element to remove:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> list: [<span class="hljs-type">Int</span>] = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
list.remove(<span class="hljs-number">1</span>)
<span class="hljs-comment">//list is [1, 3]</span>
</code></pre>
<p><code>removeLast()</code> and <code>removeFirst()</code> are two handy ways to remove the last and first element.</p>
<p>To remove all items from the array, you can use <code>removeAll()</code> or you can assign an empty array:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> list: [<span class="hljs-type">Int</span>] = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
list.removeAll()
<span class="hljs-comment">//or</span>
list = []
</code></pre>
<p>The <code>sort()</code> method sorts the array:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> list = [<span class="hljs-number">3</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
list.<span class="hljs-built_in">sort</span>()
<span class="hljs-comment">//list is [1, 2, 3]</span>
</code></pre>
<p>There are a lot more methods, but those are the basic ones.</p>
<p>Arrays are equal when they contain the same elements, of the same type:</p>
<pre><code class="lang-swift">[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>] == [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>] <span class="hljs-comment">//true</span>
</code></pre>
<p>Arrays are passed by value, which means if you pass an array to a function, or return it from a function, the array is copied.</p>
<p>Arrays are collections, and they can be iterated over in loops.</p>
<h2 id="heading-sets-in-swift">Sets in Swift</h2>
<p>You use sets to create collections of non-repeated items.</p>
<p>While an array can contain many times the same item, you only have unique items in a set.</p>
<p>You can declare a set of <code>Int</code> values in this way:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> <span class="hljs-keyword">set</span>: <span class="hljs-type">Set</span>&lt;<span class="hljs-type">Int</span>&gt; = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
</code></pre>
<p>or you can initialize it from an array:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> <span class="hljs-keyword">set</span> = <span class="hljs-type">Set</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>])
</code></pre>
<p>You can add items to the set using <code>insert()</code>:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> <span class="hljs-keyword">set</span> = <span class="hljs-type">Set</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>])
<span class="hljs-keyword">set</span>.insert(<span class="hljs-number">17</span>)
</code></pre>
<p>Unlike arrays, there is no order or position in a set. Items are retrieved and inserted randomly.</p>
<p>The way to print the content of a set so it's ordered is to transform it into an array using the <code>sorted()</code> method:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> <span class="hljs-keyword">set</span> = <span class="hljs-type">Set</span>([<span class="hljs-number">2</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>])
<span class="hljs-keyword">let</span> orderedList = <span class="hljs-keyword">set</span>.sorted()
</code></pre>
<p>To check if a set contains an element, use the <code>contains()</code> method:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> <span class="hljs-keyword">set</span> = <span class="hljs-type">Set</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>])
<span class="hljs-keyword">set</span>.<span class="hljs-built_in">contains</span>(<span class="hljs-number">2</span>) <span class="hljs-comment">//true</span>
</code></pre>
<p>To get the number of items in the set, use the <code>count</code> property:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> <span class="hljs-keyword">set</span> = <span class="hljs-type">Set</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>])
<span class="hljs-keyword">set</span>.<span class="hljs-built_in">count</span> <span class="hljs-comment">//3</span>
</code></pre>
<p>If a set is empty, its <code>isEmpty</code> property is <code>true</code>.</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> <span class="hljs-keyword">set</span> = <span class="hljs-type">Set</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>])
<span class="hljs-keyword">set</span>.isEmpty <span class="hljs-comment">//false</span>
</code></pre>
<p>To remove one item from the array, use <code>remove()</code> passing the value of the element:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> <span class="hljs-keyword">set</span> = <span class="hljs-type">Set</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>])
<span class="hljs-keyword">set</span>.remove(<span class="hljs-number">1</span>)
<span class="hljs-comment">//set is [2, 3]</span>
</code></pre>
<p>To remove all items from the set, you can use <code>removeAll()</code>:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">set</span>.removeAll()
</code></pre>
<p>Sets, like arrays, are passed by value. This means that if you pass it to a function, or return it from a function, the set is copied.</p>
<p>Sets are great to perform set math operations like intersection, union, subtracting, and more.</p>
<p>These methods help with this:</p>
<ul>
<li><code>intersection(_:)</code></li>
<li><code>symmetricDifference(_:)</code></li>
<li><code>union(_:)</code></li>
<li><code>subtracting(_:)</code></li>
<li><code>isSubset(of:)</code></li>
<li><code>isSuperset(of:)</code></li>
<li><code>isStrictSubset(of:)</code></li>
<li><code>isStrictSuperset(of:)</code></li>
<li><code>isDisjoint(with:)</code></li>
</ul>
<p>Sets are collections, and they can be iterated over in loops.</p>
<h2 id="heading-dictionaries-in-swift">Dictionaries in Swift</h2>
<p>We use dictionaries to create a collection of key-value pairs.</p>
<p>Here is how to create a dictionary with 1 key-value pair, where the key is a String and the value is an Int:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> dict = [<span class="hljs-string">"Roger"</span>: <span class="hljs-number">8</span>, <span class="hljs-string">"Syd"</span>: <span class="hljs-number">7</span>]
</code></pre>
<p>In this case the type is inferred. You can also explicitly set the type at declaration time:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> dict: [<span class="hljs-type">String</span>: <span class="hljs-type">Int</span>] = [<span class="hljs-string">"Roger"</span>: <span class="hljs-number">8</span>, <span class="hljs-string">"Syd"</span>: <span class="hljs-number">7</span>]
</code></pre>
<p>In this example we create an empty dictionary of Int keys and String values:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> dict = [<span class="hljs-type">String</span>: <span class="hljs-type">Int</span>]()

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

<span class="hljs-keyword">var</span> dict: [<span class="hljs-type">String</span>: <span class="hljs-type">Int</span>] = [:]
</code></pre>
<p>You can access the value assigned to a key using this syntax:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> dict = [<span class="hljs-string">"Roger"</span>: <span class="hljs-number">8</span>, <span class="hljs-string">"Syd"</span>: <span class="hljs-number">7</span>]

dict[<span class="hljs-string">"Roger"</span>] <span class="hljs-comment">//8</span>
dict[<span class="hljs-string">"Syd"</span>] <span class="hljs-comment">//7</span>
</code></pre>
<p>You can change the value assigned to a key in this way:</p>
<pre><code class="lang-swift">dict[<span class="hljs-string">"Roger"</span>] = <span class="hljs-number">9</span>
</code></pre>
<p>A dictionary must be declared as <code>var</code> to be modified. If it's declared with <code>let</code>, you cannot modify it by adding or removing elements.</p>
<p>Use the same syntax to add a new key/value pair:</p>
<pre><code class="lang-swift">dict[<span class="hljs-string">"Tina"</span>] = <span class="hljs-number">4</span>
</code></pre>
<p>To remove a key/value pair, assign the value to <code>nil</code>:</p>
<pre><code class="lang-swift">dict[<span class="hljs-string">"Tina"</span>] = <span class="hljs-literal">nil</span>
</code></pre>
<p>Or call the <code>removeValue(forKey:)</code> method:</p>
<pre><code class="lang-swift">dict.removeValue(forKey: <span class="hljs-string">"Tina"</span>)
</code></pre>
<p>To get the number of items in the dictionary, use the <code>count</code> property:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> dict = [<span class="hljs-string">"Roger"</span>: <span class="hljs-number">8</span>, <span class="hljs-string">"Syd"</span>: <span class="hljs-number">7</span>]
dict.<span class="hljs-built_in">count</span> <span class="hljs-comment">//2</span>
</code></pre>
<p>If a dictionary is empty, its <code>isEmpty</code> property is <code>true</code>.</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> dict = [<span class="hljs-type">String</span>: <span class="hljs-type">Int</span>]()
dict.isEmpty <span class="hljs-comment">//true</span>
</code></pre>
<p>There are a lot of methods related to dictionaries, but those are the basic ones.</p>
<p>Dictionaries are passed by value, which means if you pass it to a function, or return it from a function, the dictionary is copied.</p>
<p>Dictionaries are collections, and they can be iterated over in loops.</p>
<h2 id="heading-tuples-in-swift">Tuples in Swift</h2>
<p>You use tuples to group multiple values into a single collection. For example you can declare a variable <code>dog</code> containing a String and an Int value:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> dog : (<span class="hljs-type">String</span>, <span class="hljs-type">Int</span>)
</code></pre>
<p>And you can initialize them with a name and an age</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> dog : (<span class="hljs-type">String</span>, <span class="hljs-type">Int</span>) = (<span class="hljs-string">"Roger"</span>, <span class="hljs-number">8</span>)
</code></pre>
<p>But as with any other variable, the type can be inferred during initialization:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> dog = (<span class="hljs-string">"Roger"</span>, <span class="hljs-number">8</span>)
</code></pre>
<p>You can use named elements:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> dog = (name: <span class="hljs-string">"Roger"</span>, age: <span class="hljs-number">8</span>)

dog.name <span class="hljs-comment">//"Roger"</span>
dog.age <span class="hljs-comment">//8</span>
</code></pre>
<p>Once a tuple is defined, you can decompose it to individual variables in this way:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> dog = (<span class="hljs-string">"Roger"</span>, <span class="hljs-number">8</span>)
<span class="hljs-keyword">let</span> (name, age) = dog
</code></pre>
<p>and if you need to just get one of the values, you can use the special underscore keyword to ignore the other ones:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> dog = (<span class="hljs-string">"Roger"</span>, <span class="hljs-number">8</span>)
<span class="hljs-keyword">let</span> (name, <span class="hljs-number">_</span>) = dog
</code></pre>
<p>Tuples are an awesome tool for various needs.</p>
<p>The most obvious one is that they're a short way to group similar data.</p>
<p>Another one of those needs is returning multiple items from a function. A function can only return a single item, so a tuple is a convenient structure for that.</p>
<p>Another handy functionality allowed by tuples is swapping elements:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> a = <span class="hljs-number">1</span>
<span class="hljs-keyword">var</span> b = <span class="hljs-number">2</span>

(a, b) = (b, a)

<span class="hljs-comment">//a == 2</span>
<span class="hljs-comment">//b == 1</span>
</code></pre>
<h2 id="heading-optionals-and-nil-in-swift">Optionals and <code>nil</code> in Swift</h2>
<p>Optionals are one key feature of Swift.</p>
<p>When you don't know if a value will be present or absent, you declare the type as an optional.</p>
<p>The optional wraps another value with its own type. Or maybe not.</p>
<p>We declare an optional by adding a question mark after its type, like this:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> value: <span class="hljs-type">Int?</span> = <span class="hljs-number">10</span>
</code></pre>
<p>Now <code>value</code> is not an Int value. It's an optional wrapping an Int value.</p>
<p>To find out if the optional wraps a value, you must <strong>unwrap</strong> it.</p>
<p>You do so using an exclamation mark:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> value: <span class="hljs-type">Int?</span> = <span class="hljs-number">10</span>
<span class="hljs-built_in">print</span>(value!) <span class="hljs-comment">//10</span>
</code></pre>
<p>Swift methods often return an optional. For example the <code>Int</code> type initializer accepts a string, and returns an Int optional:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen-Shot-2020-11-02-at-18.08.48.png" alt="Image" width="600" height="400" loading="lazy">
<em>Int type initializer takes in a string and returns an int optional</em></p>
<p>This is because it does not know if the string can be converted to a number.</p>
<p>If the optional does not contain a value, it evaluates as <code>nil</code>, and you cannot unwrap it:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen-Shot-2020-11-02-at-18.12.13.png" alt="Image" width="600" height="400" loading="lazy">
<em>Evaluating to <code>nil</code></em></p>
<p><code>nil</code> is a special value that cannot be assigned to a variable. Only to an optional:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen-Shot-2020-11-02-at-18.14.21.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen-Shot-2020-11-02-at-18.13.56-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>You can only assign <code>nil</code> to an optional (not an int)</em></p>
<p>You typically use <code>if</code> statements to unwrap values in your code, like this:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> value: <span class="hljs-type">Int?</span> = <span class="hljs-number">2</span>

<span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> age = value {
    <span class="hljs-built_in">print</span>(age)
}
</code></pre>
<h2 id="heading-enumerations-in-swift">Enumerations in Swift</h2>
<p>Enumerations are a way to group a set of different options under a common name.</p>
<p>Example:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-keyword">case</span> dog
    <span class="hljs-keyword">case</span> cat
    <span class="hljs-keyword">case</span> mouse
    <span class="hljs-keyword">case</span> horse
}
</code></pre>
<p>This <code>Animal</code> enum is now a <strong>type</strong>.</p>
<p>A type whose value can only be one of the cases listed.</p>
<p>If you define a variable of type <code>Animal</code>:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> animal: <span class="hljs-type">Animal</span>
</code></pre>
<p>you can later decide which value to assign it using this syntax:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> animal: <span class="hljs-type">Animal</span>
animal = .dog
</code></pre>
<p>We can use enumerations in control structures like switches:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-keyword">case</span> dog
    <span class="hljs-keyword">case</span> cat
    <span class="hljs-keyword">case</span> mouse
    <span class="hljs-keyword">case</span> horse
}

<span class="hljs-keyword">let</span> animal = <span class="hljs-type">Animal</span>.dog

<span class="hljs-keyword">switch</span> animal {
<span class="hljs-keyword">case</span> .dog: <span class="hljs-built_in">print</span>(<span class="hljs-string">"dog"</span>)
<span class="hljs-keyword">case</span> .cat: <span class="hljs-built_in">print</span>(<span class="hljs-string">"cat"</span>)
<span class="hljs-keyword">default</span>: <span class="hljs-built_in">print</span>(<span class="hljs-string">"another animal"</span>)
}
</code></pre>
<p>Enumeration values can be strings, characters, or numbers.</p>
<p>You can also define an enum on a single line:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-keyword">case</span> dog, cat, mouse, horse
}
</code></pre>
<p>And you can also add type declaration to the enumeration, and each case has a value of that type assigned:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Animal</span>: <span class="hljs-title">Int</span> </span>{
    <span class="hljs-keyword">case</span> dog = <span class="hljs-number">1</span>
    <span class="hljs-keyword">case</span> cat = <span class="hljs-number">2</span>
    <span class="hljs-keyword">case</span> mouse = <span class="hljs-number">3</span>
    <span class="hljs-keyword">case</span> horse = <span class="hljs-number">4</span>
}
</code></pre>
<p>Once you have a variable, you can get this value using its <code>rawValue</code> property:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Animal</span>: <span class="hljs-title">Int</span> </span>{
    <span class="hljs-keyword">case</span> dog = <span class="hljs-number">1</span>
    <span class="hljs-keyword">case</span> cat = <span class="hljs-number">2</span>
    <span class="hljs-keyword">case</span> mouse = <span class="hljs-number">3</span>
    <span class="hljs-keyword">case</span> horse = <span class="hljs-number">4</span>
}

<span class="hljs-keyword">var</span> animal: <span class="hljs-type">Animal</span>
animal = .dog

animal.rawValue <span class="hljs-comment">//1</span>
</code></pre>
<p>Enumerations are a value type. This means they are copied when passed to a function, or when returned from a function. And when we assign a variable pointing to an enumeration to another variable.</p>
<h2 id="heading-structures-in-swift">Structures in Swift</h2>
<p>Structures are an essential Swift concept.</p>
<p>Structures are everywhere in Swift. Even the built-in types are structures.</p>
<p>We can create instances of structures, which we call <strong>objects</strong>.</p>
<p>In most languages, objects can only be created from classes. Swift has classes, too, but you can create objects also from structures. The official documentation actually advises that you should prefer structures because they are easier to use.</p>
<p>Structures are a light versions of classes.</p>
<p>A struct can:</p>
<ul>
<li>have properties</li>
<li>have methods (functions)</li>
<li>define subscripts</li>
<li>define initializers</li>
<li>conform to protocols</li>
<li>be extended</li>
</ul>
<p>One important thing classes allow is inheritance, so if you need that, you have classes.</p>
<p>A struct is defined using this syntax:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Dog</span> </span>{

}
</code></pre>
<p>Inside a structure you can define <strong>stored properties</strong>:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Dog</span> </span>{
    <span class="hljs-keyword">var</span> age = <span class="hljs-number">8</span>
    <span class="hljs-keyword">var</span> name = <span class="hljs-string">"Roger"</span>
}
</code></pre>
<p>This structure definition defines a <strong>type</strong>. To create a new instance with this type, we use this syntax:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> roger = <span class="hljs-type">Dog</span>()
</code></pre>
<p>Once you have an instance, you can access its properties using the dot syntax:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> roger = <span class="hljs-type">Dog</span>()
roger.age
roger.name
</code></pre>
<p>The same dot syntax is used to update a property value:</p>
<pre><code class="lang-swift">roger.age = <span class="hljs-number">9</span>
</code></pre>
<p>You can also create a struct instance by passing the values of the properties:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> syd = <span class="hljs-type">Dog</span>(age: <span class="hljs-number">7</span>, name: <span class="hljs-string">"Syd"</span>)
syd.age
syd.name
</code></pre>
<p>To do so, properties must be defined variables with <code>var</code>, not as constants (with <code>let</code>). It's also important to respect the order those properties are defined.</p>
<p>Structures can have <strong>instance methods</strong>: functions that belong to an instance of a structure.</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Dog</span> </span>{
    <span class="hljs-keyword">var</span> age = <span class="hljs-number">8</span>
    <span class="hljs-keyword">var</span> name = <span class="hljs-string">"Roger"</span>
    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">bark</span><span class="hljs-params">()</span></span> {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"\(name): wof!"</span>)
    }
}
</code></pre>
<p>And we also have <strong>type methods</strong>:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Dog</span> </span>{
    <span class="hljs-keyword">var</span> age = <span class="hljs-number">8</span>
    <span class="hljs-keyword">var</span> name = <span class="hljs-string">"Roger"</span>
    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">bark</span><span class="hljs-params">()</span></span> {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"\(name): wof!"</span>)
    }
    <span class="hljs-keyword">static</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">hello</span><span class="hljs-params">()</span></span> {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"Hello I am the Dog struct"</span>)
    }
}
</code></pre>
<p>This is invoked as <code>Dog.hello()</code>.</p>
<p>Structures are a value type. This means they are copied when passed to a function, or when returned from a function. And when we assign a variable pointing to a structure to another variable.</p>
<p>This also means that if we want to update the properties of a structure we must define it using <code>var</code> and not <code>let</code>.</p>
<p>All types in Swift are defined as structures: Int, Double, String, arrays and dictionaries, and more are structures.</p>
<h2 id="heading-classes-in-swift">Classes in Swift</h2>
<p>Classes are a bit similar to structures, but they have some key differences.</p>
<p>A class is defined using this syntax:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> </span>{

}
</code></pre>
<p>Inside a class you can define stored properties:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> </span>{
    <span class="hljs-keyword">var</span> age = <span class="hljs-number">0</span>
}
</code></pre>
<p>A class definition defines a <strong>type</strong>. To create a new instance with this type, we use this syntax:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> roger = <span class="hljs-type">Dog</span>()
</code></pre>
<p>Once you have an instance, you can access its properties using the dot syntax:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> roger = <span class="hljs-type">Dog</span>()
roger.age
</code></pre>
<p>You use the same dot syntax to update a property value:</p>
<pre><code class="lang-swift">roger.age = <span class="hljs-number">9</span>
</code></pre>
<p>One big difference is that classes are reference types. Structures (and enumerations) are value types.</p>
<p>This means that assigning a class instance to another variable does not copy the instance. Both variables point to the same instance:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> </span>{
    <span class="hljs-keyword">var</span> age = <span class="hljs-number">0</span>
}

<span class="hljs-keyword">let</span> roger = <span class="hljs-type">Dog</span>()
<span class="hljs-keyword">let</span> syd = roger

roger.age = <span class="hljs-number">9</span>
<span class="hljs-comment">//syd.age == 9</span>
</code></pre>
<p>This also means we can define a reference to a class using <code>let</code>, and we can change its properties, as you saw in the example above.</p>
<p>We can create instances of classes, and we call them <strong>objects</strong>.</p>
<p>As with structs, classes can have properties, methods, and more.</p>
<p>Contrary to structs, we <strong>must</strong> define an initializer in order to initialize the values when we create an instance:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> </span>{
    <span class="hljs-keyword">var</span> age : <span class="hljs-type">Int</span>

    <span class="hljs-keyword">init</span>(age: <span class="hljs-type">Int</span>) {
        <span class="hljs-keyword">self</span>.age = age
    }
}

<span class="hljs-keyword">let</span> roger = <span class="hljs-type">Dog</span>(age: <span class="hljs-number">9</span>)
</code></pre>
<p>You can only declare properties without initializing them if you have an initializer.</p>
<p>See the use of <code>self</code>. We need it because <code>age</code> is both an instance property and the <code>init(age:)</code> method parameter. <code>self.age</code> references the <code>age</code> instance property.</p>
<p>Classes can have <strong>instance methods</strong>: functions that belong to an instance of a class.</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> </span>{
    <span class="hljs-keyword">var</span> age = <span class="hljs-number">8</span>
    <span class="hljs-keyword">var</span> name = <span class="hljs-string">"Roger"</span>

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">bark</span><span class="hljs-params">()</span></span> {
      <span class="hljs-built_in">print</span>(<span class="hljs-string">"\(name): wof!"</span>)
    }
}
</code></pre>
<p>And we also have <strong>type methods</strong>:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> </span>{
    <span class="hljs-keyword">var</span> age = <span class="hljs-number">8</span>
    <span class="hljs-keyword">var</span> name = <span class="hljs-string">"Roger"</span>

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">bark</span><span class="hljs-params">()</span></span> {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"\(name): wof!"</span>)
    }
    <span class="hljs-keyword">static</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">hello</span><span class="hljs-params">()</span></span> {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"Hello I am the Dog struct"</span>)
    }
}
</code></pre>
<p>Invoked as <code>Dog.hello()</code>.</p>
<p>One important thing classes allow is inheritance.</p>
<p>A class can inherit all the properties and methods from another class.</p>
<p>Say we have a class <code>Animal</code>. Every animal has an age:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-keyword">var</span> age: <span class="hljs-type">Int</span>
}
</code></pre>
<p>Not every animal has a name. Dogs have a name. So we create a <code>Dog</code> class extending from <code>Animal</code>:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>: <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-keyword">var</span> name: <span class="hljs-type">String</span>
}
</code></pre>
<p>Now we must add an initializer for both classes. In the Dog case, after we do the class-specific initialization, we can call the parent class initializer using <code>super.init()</code>:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-keyword">var</span> age: <span class="hljs-type">Int</span>

    <span class="hljs-keyword">init</span>(age: <span class="hljs-type">Int</span>) {
        <span class="hljs-keyword">self</span>.age = age
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>: <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-keyword">var</span> name: <span class="hljs-type">String</span>

    <span class="hljs-keyword">init</span>(age: <span class="hljs-type">Int</span>, name: <span class="hljs-type">String</span>) {
        <span class="hljs-keyword">self</span>.name = name
        <span class="hljs-keyword">super</span>.<span class="hljs-keyword">init</span>(age: age)
    }
}

<span class="hljs-keyword">var</span> horse = <span class="hljs-type">Animal</span>(age: <span class="hljs-number">8</span>)
<span class="hljs-keyword">var</span> roger = <span class="hljs-type">Dog</span>(age: <span class="hljs-number">8</span>, name: <span class="hljs-string">"Roger"</span>)
</code></pre>
<p><code>Animal</code> is now a <strong>superclass</strong>, and <code>Dog</code> is a <strong>subclass</strong>.</p>
<p>There's more to say about classes, but this is a good introduction.</p>
<h2 id="heading-functions-in-swift">Functions in Swift</h2>
<p>Your program's code is organized into functions.</p>
<p>You can declare a function using the <code>func</code> keyword:</p>
<pre><code class="lang-swift"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">bark</span><span class="hljs-params">()</span></span> {
    <span class="hljs-built_in">print</span>(<span class="hljs-string">"woof!"</span>)
}
</code></pre>
<p>Functions can be assigned to structures, classes and enumerations, and in this case we call them methods.</p>
<p>A function is invoked using its name:</p>
<pre><code class="lang-swift">bark()
</code></pre>
<p>A function can return a value:</p>
<pre><code class="lang-swift"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">bark</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">String</span> {
    <span class="hljs-built_in">print</span>(<span class="hljs-string">"woof!"</span>)
      <span class="hljs-keyword">return</span> <span class="hljs-string">"barked successfully"</span>
}
</code></pre>
<p>And you can assign it to a variable:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> result = bark()
</code></pre>
<p>A function can accept parameters. Each parameter has a name and a type:</p>
<pre><code class="lang-swift"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">bark</span><span class="hljs-params">(times: Int)</span></span> {
    <span class="hljs-keyword">for</span> index <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>..&lt;times {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"woof!"</span>)
    }
}
</code></pre>
<p>The name of a parameter is internal to the function.</p>
<p>We use the name of the parameter when we call the function to pass in its value:</p>
<pre><code class="lang-swift">bark(times: <span class="hljs-number">3</span>)
</code></pre>
<p>When we call the function we must pass all the parameters defined.</p>
<p>Here is a function that accepts multiple parameters:</p>
<pre><code class="lang-swift"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">bark</span><span class="hljs-params">(times: Int, repeatBark: Bool)</span></span> {
    <span class="hljs-keyword">for</span> index <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>..&lt;times {
        <span class="hljs-keyword">if</span> repeatBark == <span class="hljs-literal">true</span> {
            <span class="hljs-built_in">print</span>(<span class="hljs-string">"woof woof!"</span>)
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-built_in">print</span>(<span class="hljs-string">"woof!"</span>)
        }            
    }
}
</code></pre>
<p>In this case you call it in this way:</p>
<pre><code class="lang-swift">bark(times: <span class="hljs-number">3</span>, <span class="hljs-keyword">repeat</span>: <span class="hljs-literal">true</span>)
</code></pre>
<p>When we talk about this function, we don't call it <code>bark()</code>. We call it <code>bark(times:repeat:)</code>.</p>
<p>This is because we can have multiple functions with the same name, but different set of parameters.</p>
<p>You can avoid using labels by using the <code>_</code> keyword:</p>
<pre><code class="lang-swift"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">bark</span><span class="hljs-params">(<span class="hljs-number">_</span> times: Int, repeatBark: Bool)</span></span> {
    <span class="hljs-comment">//...the function body</span>
}
</code></pre>
<p>So you can invoke it in this way:</p>
<pre><code class="lang-swift">bark(<span class="hljs-number">3</span>, <span class="hljs-keyword">repeat</span>: <span class="hljs-literal">true</span>)
</code></pre>
<p>It's common in Swift and iOS APIs to have the first parameter with no label, and the other parameters labeled.</p>
<p>It makes for a nice and expressive API, when you design the names of the function and the parameters nicely.</p>
<p>You can only return one value from a function. If you need to return multiple values, it's common to return a tuple:</p>
<pre><code class="lang-swift"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">bark</span><span class="hljs-params">()</span></span> -&gt; (<span class="hljs-type">String</span>, <span class="hljs-type">Int</span>) {
    <span class="hljs-built_in">print</span>(<span class="hljs-string">"woof!"</span>)
      <span class="hljs-keyword">return</span> (<span class="hljs-string">"barked successfully"</span>, <span class="hljs-number">1</span>)
}
</code></pre>
<p>And you can assign the result to a tuple:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> (result, num) = bark()

<span class="hljs-built_in">print</span>(result) <span class="hljs-comment">//"barked successfully"</span>
<span class="hljs-built_in">print</span>(num) <span class="hljs-comment">//1</span>
</code></pre>
<p>You can nest functions inside other functions. When this happens, the inner function is invisible to outside the outer function.</p>
<h2 id="heading-protocols-in-swift">Protocols in Swift</h2>
<p>A protocol is a way to have different objects, of different types, have a common set of functionalities.</p>
<p>You define a protocol like this:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">protocol</span> <span class="hljs-title">Mammal</span> </span>{

}
</code></pre>
<p>Structs and classes can <strong>adopt a protocol</strong> in this way:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Dog</span>: <span class="hljs-title">Mammal</span> </span>{

}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span>: <span class="hljs-title">Mammal</span> </span>{

}
</code></pre>
<p>A protocol can define properties and methods, without providing values and implementations, and a struct/class must implement them:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">protocol</span> <span class="hljs-title">Mammal</span> </span>{
    <span class="hljs-keyword">var</span> age: <span class="hljs-type">Int</span> { <span class="hljs-keyword">get</span> <span class="hljs-keyword">set</span> }
    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">walk</span><span class="hljs-params">()</span></span>
}
</code></pre>
<p>The property can be defined as <code>get</code> or <code>get set</code>. If it's <code>get</code>, the property must be implemented as read only, with a getter.</p>
<p>Any type that adopts the protocol must <strong>conform</strong> to the protocol by implementing those methods or providing those properties:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Dog</span>: <span class="hljs-title">Mammal</span> </span>{
    <span class="hljs-keyword">var</span> age: <span class="hljs-type">Int</span> = <span class="hljs-number">0</span>
    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">walk</span><span class="hljs-params">()</span></span> {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"The dog is walking"</span>)
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span>: <span class="hljs-title">Mammal</span> </span>{
    <span class="hljs-keyword">var</span> age: <span class="hljs-type">Int</span> = <span class="hljs-number">0</span>
    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">walk</span><span class="hljs-params">()</span></span> {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"The cat is walking"</span>)
    }
}
</code></pre>
<p>Structs and classes can adopt multiple protocols:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Dog</span>: <span class="hljs-title">Mammal</span>, <span class="hljs-title">Animal</span> </span>{

}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span>: <span class="hljs-title">Mammal</span>, <span class="hljs-title">Animal</span> </span>{

}
</code></pre>
<p>Notice that for classes, this is the same syntax used to define a superclass. If there is a superclass, list it as the first item in the list, after the colon.</p>
<h2 id="heading-where-to-go-from-here">Where to Go From Here</h2>
<p>I hope this little handbook was useful in shining a light on how to get started with Swift. And I hope you are now interested to learn more about it!</p>
<p>I can now point you to a few places to learn more:</p>
<ul>
<li><a target="_blank" href="https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html">The official Swift Language Guide</a></li>
<li><a target="_blank" href="https://developer.apple.com/documentation/swift/swift-standard-library/">The Swift Standard Library</a></li>
<li><a target="_blank" href="https://developer.apple.com/videos/swift">WWDC Swift videos</a></li>
</ul>
<p><a target="_blank" href="https://thevalleyofcode.com/download/swift/">You can get a PDF and ePub version of this Swift Beginner's Handbook here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Go Handbook – Learn Golang for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ Golang is an awesome, simple, modern, and fast programming language. It’s compiled, open source, and strongly typed. Golang – also called Go – was created by Google engineers with these main goals: make their projects compile (and run) faster be sim... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/go-beginners-handbook/</link>
                <guid isPermaLink="false">66bb5a68e326dc37a9d68ef0</guid>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Go Language ]]>
                    </category>
                
                    <category>
                        <![CDATA[ golang ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Flavio Copes ]]>
                </dc:creator>
                <pubDate>Tue, 18 Oct 2022 18:35:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/10/golang.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Golang is an awesome, simple, modern, and fast programming language.</p>
<p>It’s compiled, open source, and strongly typed.</p>
<p>Golang – also called Go – was created by Google engineers with these main goals:</p>
<ul>
<li>make their projects compile (and run) faster</li>
<li>be simple so people can pick it up in little time</li>
<li>be low level enough but also avoid some pitfalls of being too low level</li>
<li>be portable (compiled Go programs are binaries that do not require other files to run and are cross-platform, so they can be distributed easily)</li>
<li>be boring, stable, predictable, offer less opportunities to make mistakes</li>
<li>make it easy to take advantage of multiprocessor systems</li>
</ul>
<p>Go was meant to be a replacement for C and C++ codebases. It aims to make some things simpler like concurrency and memory management, with garbage collection.</p>
<p>Also, it was built to work along with C and C++ codebases, thanks to its C interoperability features.</p>
<p>You can use Go for many different tasks, and it can solve both simple problems and very complex ones.</p>
<p>You can use Go to create command line utilities and networking servers, and it's widely used in many different scenarios.</p>
<p>For example, Docker and Kubernetes are written in Go.</p>
<p>My favorite Static Site Generator (Hugo) is written in Go.</p>
<p>Caddy, a quite popular web server, is written in Go.</p>
<p>There’s lots of different, widely used tools that use this programming language under the hood.</p>
<p>This handbook will introduce you to the Go programming language so you can get started coding in Go.</p>
<p><a target="_blank" href="https://thevalleyofcode.com/download/go/">You can get a PDF and ePub version of this Go Beginner's Handbook here</a>.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-how-to-get-started-with-go">How to get started with Go</a></li>
<li><a class="post-section-overview" href="#heading-how-to-install-go">How to install Go</a></li>
<li><a class="post-section-overview" href="#heading-how-to-setup-your-editor">How to setup your editor</a></li>
<li><a class="post-section-overview" href="#heading-how-to-write-hello-world-in-go">How to write Hello, World! in Go</a></li>
<li><a class="post-section-overview" href="#heading-how-to-compile-and-run-a-go-program">How to compile and run a Go program</a></li>
<li><a class="post-section-overview" href="#heading-the-go-workspace">The Go workspace</a></li>
<li><a class="post-section-overview" href="#heading-diving-into-the-go-language">Diving into the Go language</a></li>
<li><a class="post-section-overview" href="#heading-variables-in-go">Variables in Go</a></li>
<li><a class="post-section-overview" href="#heading-basic-types-in-go">Basic types in Go</a></li>
<li><a class="post-section-overview" href="#heading-strings-in-go">Strings in Go</a></li>
<li><a class="post-section-overview" href="#heading-arrays-in-go">Arrays in Go</a></li>
<li><a class="post-section-overview" href="#heading-slices-in-go">Slices in Go</a></li>
<li><a class="post-section-overview" href="#heading-maps-in-go">Maps in Go</a></li>
<li><a class="post-section-overview" href="#heading-loops-in-go">Loops in Go</a></li>
<li><a class="post-section-overview" href="#heading-conditionals-in-go">Conditionals in Go</a></li>
<li><a class="post-section-overview" href="#heading-operators-in-go">Operators in Go</a></li>
<li><a class="post-section-overview" href="#heading-structs-in-go">Structs in Go</a></li>
<li><a class="post-section-overview" href="#heading-functions-in-go">Functions in Go</a></li>
<li><a class="post-section-overview" href="#heading-pointers-in-go">Pointers in Go</a></li>
<li><a class="post-section-overview" href="#heading-methods-in-go">Methods in Go</a></li>
<li><a class="post-section-overview" href="#heading-interfaces-in-go">Interfaces in Go</a></li>
<li><a class="post-section-overview" href="#heading-where-to-go-from-here">Where to go from here</a></li>
</ol>
<h2 id="heading-how-to-get-started-with-go">How to Get Started with Go</h2>
<p>Here are a few things you should know before we dive into the specifics of the language.</p>
<p>First, <a target="_blank" href="https://go.dev/">https://go.dev</a> is the homepage of the language. This will be your go-to resource to:</p>
<ul>
<li>Download the Go binaries (the <code>go</code> command and other related tools) from <a target="_blank" href="https://go.dev/doc/install">https://go.dev/doc/install</a></li>
<li>Reference the official Go documentation <a target="_blank" href="https://go.dev/doc/">https://go.dev/doc/</a></li>
<li>See all the the Go packages <a target="_blank" href="https://pkg.go.dev/">https://pkg.go.dev/</a></li>
<li>Access the Go Playground <a target="_blank" href="https://go.dev/play/">https://go.dev/play/</a></li>
</ul>
<p>…and more.</p>
<h2 id="heading-how-to-install-go">How to Install Go</h2>
<p>Go to <a target="_blank" href="https://go.dev/doc/install">https://go.dev/doc/install</a> and download the package for your Operating System.</p>
<p>Run the installer, and at the end of the process you will have the <code>go</code> command available in your terminal:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen_Shot_2022-07-28_at_10.19.21.png" alt="Screen Shot 2022-07-28 at 10.19.21.png" width="600" height="400" loading="lazy">
<em>Welcome to the Go installer</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen_Shot_2022-07-28_at_10.20.54.png" alt="Screen Shot 2022-07-28 at 10.20.54.png" width="600" height="400" loading="lazy">
<em>Successful installation modal</em></p>
<p>Open the terminal and run <code>go version</code> and you should see something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen_Shot_2022-07-28_at_10.21.32.png" alt="Screen Shot 2022-07-28 at 10.21.32.png" width="600" height="400" loading="lazy">
<em>Displaying the Go version you have</em></p>
<p>NOTE: you might have to open a new terminal before you can run the program, as the installer added the Go binaries folder to the path.</p>
<p>The exact location of the Go installation files will depend on your Operating System.</p>
<p>On macOS, it’s under <code>/usr/local/go</code>, with binaries in <code>/usr/local/go/bin</code>.</p>
<p>On Windows, it will be under <code>C:\Program Files\go</code>.</p>
<p>The Windows and Mac installers will set the Go binaries path automatically.</p>
<p>On a Mac you might also want to install Go via Homebrew using <code>brew install golang</code>. This will make it easier to update later.</p>
<p>On Linux you will have to add the Go binaries folder to your terminal path before you can run the <code>go</code> command after unpackaging the Linux package to <code>/usr/local/go</code> with this command:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">'export PATH=$PATH:/usr/local/go/bin'</span> &gt;&gt; <span class="hljs-variable">$HOME</span>/.profile
<span class="hljs-built_in">source</span> <span class="hljs-variable">$HOME</span>/.profile
</code></pre>
<h2 id="heading-how-to-setup-your-editor">How to Setup Your Editor</h2>
<p>I recommend using <a target="_blank" href="https://code.visualstudio.com/"><strong>Visual Studio Code</strong></a> (aka VS Code) as your editor.</p>
<p>Read <a target="_blank" href="https://code.visualstudio.com/docs/languages/go">Go in Visual Studio Code</a> for a quick “up and running” setup. At the bare minimum, install <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=golang.go">the Go extension</a>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen_Shot_2022-07-28_at_10.54.06.png" alt="Screen Shot 2022-07-28 at 10.54.06.png" width="600" height="400" loading="lazy">
<em>Go extension for VSCode</em></p>
<p>This extension will make your life easier, as it provides IntelliSense (syntax highlighting, autocompletion, on hover information, error highlighting…) and other things like auto formatting, menu options to install packages, testing, and more.</p>
<h2 id="heading-how-to-write-hello-world-in-go">How to Write Hello, World! in Go</h2>
<p>Now we’re ready to create our first Go program!</p>
<p>It’s a programmer's tradition to make the first program print the “Hello, World!” string to the terminal when it’s run. So we’ll do that first, and then we’ll explain how we did it.</p>
<p>Maybe you have a folder in your home directory where you keep all your coding projects and tests.</p>
<p>In there, create a new folder, for example call it <code>hello</code>.</p>
<p>In there, create a <code>hello.go</code> file (you can name it as you want).</p>
<p>Add this content:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

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

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    fmt.Println(<span class="hljs-string">"Hello, World!"</span>)
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen_Shot_2022-07-28_at_12.17.14.png" alt="Screen Shot 2022-07-28 at 12.17.14.png" width="600" height="400" loading="lazy">
<em>Go "Hello, World!" code</em></p>
<p>This is your first Go program!</p>
<p>Let’s analyze this line by line.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main
</code></pre>
<p>We organize Go programs in packages.</p>
<p>Each <code>.go</code> file first declares which package it is part of.</p>
<p>A package can be composed by multiple files, or just one file.</p>
<p>A program can contain multiple packages.</p>
<p>The <code>main</code> package is the entry point of the program and identifies an executable program.</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>
</code></pre>
<p>We use the <code>import</code> keyword to import a package.</p>
<p><code>fmt</code> is a built-in package provided by Go that provides input/output utility functions.</p>
<p>We have a <a target="_blank" href="https://pkg.go.dev/std">large standard library</a> ready to use that we can use for anything from network connectivity to math, crypto, image processing, filesystem access, and more.</p>
<p>You can read about all the features that this <code>fmt</code> package provides <a target="_blank" href="https://pkg.go.dev/fmt">on the official documentation</a>.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {

}
</code></pre>
<p>Here we declare the <code>main()</code> function.</p>
<p>What’s a function? We’ll see more about them later, but in the meantime let’s say a function is a block of code that’s assigned a name, and contains some instructions.</p>
<p>The <code>main</code> function is special because what’s where the program starts.</p>
<p>In this simple case we just have one function – the program starts with that and then ends.</p>
<pre><code class="lang-go">fmt.Println(<span class="hljs-string">"Hello, World!"</span>)
</code></pre>
<p>This is the content of the function we defined.</p>
<p>We call the <code>Println()</code> function defined in the <code>fmt</code> package we previously imported, passing a string as a parameter.</p>
<p>This function, according to the <a target="_blank" href="https://pkg.go.dev/fmt#Printf">docs</a> "<em>formats according to a format specifier and writes to standard output</em>”.</p>
<p>Take a look at the docs because they are great. They even have examples you can run:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen_Shot_2022-07-28_at_14.18.46.png" alt="Screen Shot 2022-07-28 at 14.18.46.png" width="600" height="400" loading="lazy">
<em>Go basic function example</em></p>
<p>We use the “dot” syntax <code>fmt.Println()</code> to specify that the function is provided by that package.</p>
<p>After the code executes the <code>main</code> function, it has nothing else to do and the execution ends.</p>
<h2 id="heading-how-to-compile-and-run-a-go-program">How to Compile and Run a Go program</h2>
<p>Now open the terminal in the <code>hello</code> folder and run the program using:</p>
<pre><code class="lang-bash">go run hello.go
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen_Shot_2022-07-28_at_12.18.23.png" alt="Screen Shot 2022-07-28 at 12.18.23.png" width="600" height="400" loading="lazy">
<em>Hello world output in Go</em></p>
<p>Our program ran successfully, and it printed “Hello, World!” to the terminal.</p>
<p>The <code>go run</code> tool first compiles and then runs the program specified.</p>
<p>You can create a <strong>binary</strong> using <code>go build</code>:</p>
<pre><code class="lang-bash">go build hello.go
</code></pre>
<p>This will create a <code>hello</code> file that’s a binary you can execute:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen_Shot_2022-07-28_at_12.19.50.png" alt="Screen Shot 2022-07-28 at 12.19.50.png" width="600" height="400" loading="lazy">
<em>Executable binary in Go</em></p>
<p>In the introduction I mentioned that Go is portable.</p>
<p>Now you can distribute this binary and everyone can run the program as-is, because the binary is already packaged for execution.</p>
<p>The program will run on the same architecture we built it on.</p>
<p>We can create a different binary for a different architecture using the <code>GOOS</code> and <code>GOARCH</code> environment variables, like this:</p>
<pre><code class="lang-go">GOOS=windows GOARCH=amd64 <span class="hljs-keyword">go</span> build hello.<span class="hljs-keyword">go</span>
</code></pre>
<p>This will create a <code>hello.exe</code> executable for 64-bit Windows machines:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen_Shot_2022-07-28_at_15.36.55.png" alt="Screen Shot 2022-07-28 at 15.36.55.png" width="600" height="400" loading="lazy">
<em>Hello.exe executable</em></p>
<p>Setup for 64-bit macOS (Intel or Apple Silicon) is <code>GOOS=darwin GOARCH=amd64</code> and Linux is <code>GOOS=linux GOARCH=amd64</code>.</p>
<p>This is one of the best features of Go.</p>
<h2 id="heading-the-go-workspace">The Go Workspace</h2>
<p>One special thing about Go is what we call the <strong>workspace</strong>.</p>
<p>The workspace is the “home base” for Go.</p>
<p>By default Go picks the <code>$HOME/go</code> path, so you will see a <code>go</code> folder in your home.</p>
<p>It’s first created when you install a package (as we’ll see later) but also to store some tooling. </p>
<p>For example the moment I loaded the <code>hello.go</code> file in VS Code, it prompted me to install the <code>[gopls](https://pkg.go.dev/golang.org/x/tools/gopls)</code> command, the Delve debugger (<code>dlv</code>), and the <a target="_blank" href="https://staticcheck.io/"><code>staticcheck</code> linter</a>.</p>
<p>They were automatically installed under <code>$HOME/go</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen_Shot_2022-07-28_at_12.27.27.png" alt="Screen Shot 2022-07-28 at 12.27.27.png" width="600" height="400" loading="lazy">
<em><code>$HOME/go</code></em></p>
<p>When you install packages using <code>go install</code>, they will be stored here.</p>
<p>This is what we call <strong>GOPATH</strong>.</p>
<p>You can change the <code>GOPATH</code> environment variable to change where Go should install packages.</p>
<p>This is useful when working on different projects at the same time and you want to isolate the libraries you use.</p>
<h2 id="heading-diving-into-the-go-language">Diving into the Go Language</h2>
<p>Now that we've got the first notions in place, and we ran our first Hello, World! program, we can dive into the language.</p>
<p>The language has no semantically significant whitespace. This is like C, C++, Rust, Java, JavaScript, but unlike Python, where whitespace is meaningful and is used to create blocks instead of curly brackets.</p>
<p>Semicolons are optional, like in JavaScript (unlike in C, C++, Rust or Java).</p>
<p>Go takes indentation and visual order very seriously.</p>
<p>When we install Go we also get access to the <code>gofmt</code> command line tool which we can use to format Go programs. VS Code uses that under the hood to format Go source files.</p>
<p>This is very interesting and innovative because formatting and issues like tabs vs spaces or “should I put the curly brackets on the same line of the loop definition or in the next line” are a huge waste of time.</p>
<p>The language creators defined the rules, and everyone uses those rules.</p>
<p>This is great for projects with large teams.</p>
<p>I recommend you enable in the VS Code Settings “<strong>Format on Save</strong>” and “<strong>Format on Paste</strong>”:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen_Shot_2022-07-28_at_14.39.42.png" alt="Screen Shot 2022-07-28 at 14.39.42.png" width="600" height="400" loading="lazy">
<em>VS Code settings for Go - Format on Paste and Format on Save</em></p>
<p>You can write comments in Go using the usual C / C++ / JavaScript / Java syntax:</p>
<pre><code class="lang-go"><span class="hljs-comment">// this is a line comment</span>

<span class="hljs-comment">/*
multi
line
comment
*/</span>
</code></pre>
<h2 id="heading-variables-in-go">Variables in Go</h2>
<p>One of the first things you do in a programming language is defining a variable.</p>
<p>In Go we define variables using <code>var</code>:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> age = <span class="hljs-number">20</span>
</code></pre>
<p>You can define variables at the package level:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

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

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

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    fmt.Println(<span class="hljs-string">"Hello, World!"</span>)
}
</code></pre>
<p>or inside a function:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

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

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

    fmt.Println(<span class="hljs-string">"Hello, World!"</span>)
}
</code></pre>
<p>Defined at the package level, a variable is visible across all the files that compose the package. A package can be composed of multiple files, you just need to create another file and use the same package name at the top.</p>
<p>Defined at the function level, a variable is visible only within that function. It’s initialized when the function is called, and destroyed when the function ends the execution.</p>
<p>In the example we used:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> age = <span class="hljs-number">20</span>
</code></pre>
<p>we assign the value <code>20</code> to <code>age</code>.</p>
<p>This makes Go determine that the <strong>type</strong> of the variable <code>age</code> is <code>int</code>.</p>
<p>We’ll see more about types later, but you should know there are many different ones, starting with <code>int</code>, <code>string</code>, and <code>bool</code>.</p>
<p>We can also declare a variable without an existing value, but in this case we must set the type like this:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> age <span class="hljs-keyword">int</span>
<span class="hljs-keyword">var</span> name <span class="hljs-keyword">string</span>
<span class="hljs-keyword">var</span> done <span class="hljs-keyword">bool</span>
</code></pre>
<p>When you know the value, you typically use the short variable declaration with the <code>:=</code> operator:</p>
<pre><code class="lang-go">age := <span class="hljs-number">10</span>
name := <span class="hljs-string">"Roger"</span>
</code></pre>
<p>For the name of the variable you can use letters, digits, and the underscore <code>_</code> as long as the name starts with a character or <code>_</code>.</p>
<p>Names are <strong>case sensitive</strong>.</p>
<p>If the name is long, it’s common to use camelCase. So to indicate the name of the car we use <code>carName</code>.</p>
<p>You can assign a new value to a variable with the assignment operator <code>=</code></p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> age <span class="hljs-keyword">int</span>
age = <span class="hljs-number">10</span>
age = <span class="hljs-number">11</span>
</code></pre>
<p>If you have a variable that never changes during the program you can declare it as a constant using <code>const</code>:</p>
<pre><code class="lang-go"><span class="hljs-keyword">const</span> age = <span class="hljs-number">10</span>
</code></pre>
<p>You can declare multiple variables on a single line:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> age, name
</code></pre>
<p>and initialize them too:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> age, name = <span class="hljs-number">10</span>, <span class="hljs-string">"Roger"</span>

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

age, name := <span class="hljs-number">10</span>, <span class="hljs-string">"Roger"</span>
</code></pre>
<p>Declared variables that are not used in the program raise an error and the program does not compile.</p>
<p>You will see a warning in VS Code:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen_Shot_2022-07-28_at_15.45.31.png" alt="Screen Shot 2022-07-28 at 15.45.31.png" width="600" height="400" loading="lazy">
<em>Warning for unused declared variables</em></p>
<p>and the error from the compiler:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen_Shot_2022-07-28_at_15.45.44.png" alt="Screen Shot 2022-07-28 at 15.45.44.png" width="600" height="400" loading="lazy">
<em>Error in compiler for unused declared variables</em></p>
<p>If you declare a variable without initializing it to a value, it is assigned a value automatically that depends on the type – for example an integer is <code>0</code> and a string is an empty string.</p>
<h2 id="heading-basic-types-in-go">Basic Types in Go</h2>
<p>Go is a typed language.</p>
<p>We saw how you can declare a variable, specifying its type:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> age <span class="hljs-keyword">int</span>
</code></pre>
<p>Or you can let Go infer the type from the initial value assigned:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> age = <span class="hljs-number">10</span>
</code></pre>
<p>The basic types in Go are:</p>
<ul>
<li>Integers (<code>int</code>, <code>int8</code>, <code>int16</code>, <code>int32</code>, <code>rune</code>, <code>int64</code>, <code>uint</code>, <code>uintptr</code>, <code>uint8</code>, <code>uint16</code>, <code>uint64</code>)</li>
<li>Floats (<code>float32</code>, <code>float64</code>), useful to represent decimals</li>
<li>Complex types (<code>complex64</code>, <code>complex128</code>), useful in math</li>
<li>Byte (<code>byte</code>), represents a single ASCII character</li>
<li>Strings (<code>string</code>), a set of <code>byte</code>s</li>
<li>Booleans (<code>bool</code>), either true or false</li>
</ul>
<p>We have a lot of different types to represent integers. You will use <code>int</code> most of the time, and you might choose a more specialized one for optimization (not something you need to think about when you are just learning).</p>
<p>An <code>int</code> type will default to be 64 bits when used on a 64 bit system, 32 bits on a 32 bit system, and so on.</p>
<p><code>uint</code> is an <code>int</code> that’s unsigned, and you can use this to double the amount of values you can store if you know the number is not going to be negative.</p>
<p>All the above basic types are <strong>value types</strong>, which means they are <strong>passed by value</strong> to functions when passed as parameters, or when returned from functions.</p>
<h2 id="heading-strings-in-go">Strings in Go</h2>
<p>A string in Go is a sequence of <code>byte</code> values.</p>
<p>As we saw above, you can define a string using this syntax:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> name = <span class="hljs-string">"test"</span>
</code></pre>
<p>It’s important to note that unlike other languages, strings are defined only using double quotes, not single quotes.</p>
<p>To get the length of a string, use the built-in <code>len()</code> function:</p>
<pre><code class="lang-go"><span class="hljs-built_in">len</span>(name) <span class="hljs-comment">//4</span>
</code></pre>
<p>You can access individual characters using square brackets, passing the index of the character you want to get:</p>
<pre><code class="lang-go">name[<span class="hljs-number">0</span>] <span class="hljs-comment">//"t" (indexes start at 0)</span>
name[<span class="hljs-number">1</span>] <span class="hljs-comment">//"e"</span>
</code></pre>
<p>You can get a portion of the string using this syntax:</p>
<pre><code class="lang-go">name[<span class="hljs-number">0</span>:<span class="hljs-number">2</span>] <span class="hljs-comment">//"te"</span>
name[:<span class="hljs-number">2</span>]  <span class="hljs-comment">//"te"</span>
name[<span class="hljs-number">2</span>:]  <span class="hljs-comment">//"st"</span>
</code></pre>
<p>Using this you can create a copy of the string using:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> newstring = name[:]
</code></pre>
<p>You can assign a string to a new variable like this:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> first = <span class="hljs-string">"test"</span>
<span class="hljs-keyword">var</span> second = first
</code></pre>
<p>Strings are <strong>immutable</strong>, so you cannot update the value of a string.</p>
<p>Even if you assign a new value to <code>first</code> using an assignment operator, the value <code>second</code> is still going to be <code>"test"</code>:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> first = <span class="hljs-string">"test"</span>
<span class="hljs-keyword">var</span> second = first

first = <span class="hljs-string">"another test"</span>

first  <span class="hljs-comment">//"another test"</span>
second <span class="hljs-comment">//"test"</span>
</code></pre>
<p>Strings are reference types, which means if you pass a string to a function, the <strong>reference</strong> to the string will be copied, not its value. But since strings are immutable, in this case it’s not a big difference in practice with passing an <code>int</code>, for example.</p>
<p>You can concatenate two strings using the <code>+</code> operator:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> first = <span class="hljs-string">"first"</span>
<span class="hljs-keyword">var</span> second = <span class="hljs-string">"second"</span>

<span class="hljs-keyword">var</span> word = first + <span class="hljs-string">" "</span> + second  <span class="hljs-comment">//"first second"</span>
</code></pre>
<p>Go provides several string utilities in the the <code>strings</code> package.</p>
<p>We already saw how to import a package in the “Hello, World!” example.</p>
<p>Here’s how you can import <code>strings</code>:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"strings"</span>
)
</code></pre>
<p>And then you can use it.</p>
<p>For example we can use the <code>HasPrefix()</code> function to see if a string starts with a specific substring:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"strings"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    strings.HasPrefix(<span class="hljs-string">"test"</span>, <span class="hljs-string">"te"</span>) <span class="hljs-comment">// true</span>
}
</code></pre>
<p>You can find the full list of methods here: <a target="_blank" href="https://pkg.go.dev/strings">https://pkg.go.dev/strings</a>.</p>
<p>Here’s a list of methods you might use frequently:</p>
<ul>
<li><code>strings.ToUpper()</code> returns a new string, uppercase</li>
<li><code>strings.ToLower()</code> returns a new string, lowercase</li>
<li><code>strings.HasSuffix()</code> checks if a string ends with a substring</li>
<li><code>strings.HasPrefix()</code> checks if a string starts with a substring</li>
<li><code>strings.Contains()</code> checks if a string contains a substring</li>
<li><code>strings.Count()</code> counts how many times a substring appears in a string</li>
<li><code>strings.Join()</code> used to join multiple strings and create a new one</li>
<li><code>strings.Split()</code> used to create an array of strings from a string, dividing the original one on a specific character, like a comma or a space</li>
<li><code>strings.ReplaceAll()</code> used to replace a portion in a string and replace it with a new one</li>
</ul>
<h2 id="heading-arrays-in-go">Arrays in Go</h2>
<p>Arrays are a sequence of items of a single type.</p>
<p>We define an array in this way:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> myArray [<span class="hljs-number">3</span>]<span class="hljs-keyword">string</span> <span class="hljs-comment">//an array of 3 strings</span>
</code></pre>
<p>and you can initialize the array with values using:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> myArray = [<span class="hljs-number">3</span>]<span class="hljs-keyword">string</span>{<span class="hljs-string">"First"</span>, <span class="hljs-string">"Second"</span>, <span class="hljs-string">"Third"</span>}
</code></pre>
<p>In this case you can also let Go do some work and count the items for you:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> myArray = [...]<span class="hljs-keyword">string</span>{<span class="hljs-string">"First"</span>, <span class="hljs-string">"Second"</span>, <span class="hljs-string">"Third"</span>}
</code></pre>
<p>An array can only contain values of the same type.</p>
<p>The array cannot be resized – you have to explicitly define the length of an array in Go. That’s part of the <em>type</em> of an array. Also, you cannot use a variable to set the length of the array.</p>
<p>Due to this limitation, arrays are rarely used directly in Go. Instead we use <strong>slices</strong> (more on them later). Slices use arrays under the hood, so it’s still necessary to know how they work.</p>
<p>You can access an item in the array with the square brackets notation we already used in strings to access a single character:</p>
<pre><code class="lang-go">myArray[<span class="hljs-number">0</span>] <span class="hljs-comment">//indexes start at 0</span>
myArray[<span class="hljs-number">1</span>]
</code></pre>
<p>You can set a new value for a specific position in the array:</p>
<pre><code class="lang-go">myArray[<span class="hljs-number">2</span>] = <span class="hljs-string">"Another"</span>
</code></pre>
<p>And you can get the length of an array using the <code>len()</code> function:</p>
<pre><code class="lang-go"><span class="hljs-built_in">len</span>(myArray)
</code></pre>
<p>Arrays are <strong>value types</strong>. This means copying an array:</p>
<pre><code class="lang-go">anotherArray := myArray
</code></pre>
<p>or passing an array to a function, or returning it from a function, creates a copy of the original array.</p>
<p>This is different from other programming languages out there.</p>
<p>Let’s make a simple example where we assign a new value to an array item after copying it. See, the copy doesn't change:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> myArray = [<span class="hljs-number">3</span>]<span class="hljs-keyword">string</span>{<span class="hljs-string">"First"</span>, <span class="hljs-string">"Second"</span>, <span class="hljs-string">"Third"</span>}
myArrayCopy := myArray
myArray[<span class="hljs-number">2</span>] = <span class="hljs-string">"Another"</span>

myArray[<span class="hljs-number">2</span>]     <span class="hljs-comment">//"Another"</span>
myArrayCopy[<span class="hljs-number">2</span>] <span class="hljs-comment">//"Third"</span>
</code></pre>
<p>Remember you can only add a single type of items in an array, so setting the <code>myArray[2] = 2</code> for example will raise an error.</p>
<p>Low-level elements are stored continuously in memory.</p>
<h2 id="heading-slices-in-go">Slices in Go</h2>
<p>A slice is a data structure similar to an array, but it can change in size.</p>
<p>Under the hood, slices use an array and they are an abstraction built on top of them that makes them more flexible and useful (think about arrays as lower level).</p>
<p>You will use slices in a way that’s very similar to how you use arrays in higher level languages.</p>
<p>You define a slice similarly to an array, omitting the length:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> mySlice []<span class="hljs-keyword">string</span> <span class="hljs-comment">//a slice of strings</span>
</code></pre>
<p>You can initialize the slice with values:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> mySlice = []<span class="hljs-keyword">string</span>{<span class="hljs-string">"First"</span>, <span class="hljs-string">"Second"</span>, <span class="hljs-string">"Third"</span>}

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

mySlice := []<span class="hljs-keyword">string</span>{<span class="hljs-string">"First"</span>, <span class="hljs-string">"Second"</span>, <span class="hljs-string">"Third"</span>}
</code></pre>
<p>You can create an empty slice of a specific length using the <code>make()</code> function:</p>
<pre><code class="lang-go">mySlice := <span class="hljs-built_in">make</span>([]<span class="hljs-keyword">string</span>, <span class="hljs-number">3</span>) <span class="hljs-comment">//a slice of 3 empty strings</span>
</code></pre>
<p>You can create a new slice from an existing slice, appending one or more items to it:</p>
<pre><code class="lang-go">mySlice := []<span class="hljs-keyword">string</span>{<span class="hljs-string">"First"</span>, <span class="hljs-string">"Second"</span>, <span class="hljs-string">"Third"</span>}

newSlice := <span class="hljs-built_in">append</span>(mySlice, <span class="hljs-string">"Fourth"</span>, <span class="hljs-string">"Fifth"</span>)
</code></pre>
<p>Note that we need to assign the result of <code>append()</code> to a new slice, otherwise we’ll get a compiler error. The original slice is not modified – we’ll get a brand new one.</p>
<p>You can also use the <code>copy()</code> function to duplicate a slice so it does not share the same memory of the other one and is independent:</p>
<pre><code class="lang-go">mySlice := []<span class="hljs-keyword">string</span>{<span class="hljs-string">"First"</span>, <span class="hljs-string">"Second"</span>, <span class="hljs-string">"Third"</span>}

newSlice := <span class="hljs-built_in">make</span>([]<span class="hljs-keyword">string</span>, <span class="hljs-number">3</span>)

<span class="hljs-built_in">copy</span>(newSlice, mySlice)
</code></pre>
<p>If the slice you’re copying to does not have enough space (is shorter than the original) only the first items (until there’s space) will be copied.</p>
<p>You can initialize a slice from an array:</p>
<pre><code class="lang-go">myArray := [<span class="hljs-number">3</span>]<span class="hljs-keyword">string</span>{<span class="hljs-string">"First"</span>, <span class="hljs-string">"Second"</span>, <span class="hljs-string">"Third"</span>}

mySlice = myArray[:]
</code></pre>
<p>Multiple slices can use the same array as the underlying array:</p>
<pre><code class="lang-go">myArray := [<span class="hljs-number">3</span>]<span class="hljs-keyword">string</span>{<span class="hljs-string">"First"</span>, <span class="hljs-string">"Second"</span>, <span class="hljs-string">"Third"</span>}

mySlice := myArray[:]
mySlice2 := myArray[:]

mySlice[<span class="hljs-number">0</span>] = <span class="hljs-string">"test"</span>

fmt.Println(mySlice2[<span class="hljs-number">0</span>]) <span class="hljs-comment">//"test"</span>
</code></pre>
<p>Those 2 slices now share the same memory. Modifying one slice modifies the underlying array and causes the other slice generated from the array to be modified, too.</p>
<p>As with arrays, each item in a slice is stored in memory in consecutive memory locations.</p>
<p>If you know you need to perform operations on the slice, you can request it to have more capacity than initially needed. This way, when you need more space, the space will be readily available (instead of finding and moving the slice to a new memory location with more space to grow and dispose via garbage collection of the old location).</p>
<p>We can specify the <strong>capacity</strong> by adding a third parameter to <code>make()</code>:</p>
<pre><code class="lang-go">newSlice := <span class="hljs-built_in">make</span>([]<span class="hljs-keyword">string</span>, <span class="hljs-number">0</span>, <span class="hljs-number">10</span>)
<span class="hljs-comment">//an empty slice with capacity 10</span>
</code></pre>
<p>As with strings, you can get a portion of a slice using this syntax:</p>
<pre><code class="lang-go">mySlice := []<span class="hljs-keyword">string</span>{<span class="hljs-string">"First"</span>, <span class="hljs-string">"Second"</span>, <span class="hljs-string">"Third"</span>}

newSlice := mySlice[:<span class="hljs-number">2</span>] <span class="hljs-comment">//get the first 2 items</span>
newSlice2 := mySlice[<span class="hljs-number">2</span>:] <span class="hljs-comment">//ignore the first 2 items</span>
newSlice3 := mySlice[<span class="hljs-number">1</span>:<span class="hljs-number">3</span>] <span class="hljs-comment">//new slice with items in position 1-2</span>
</code></pre>
<h2 id="heading-maps-in-go">Maps in Go</h2>
<p>A map is a very useful data type in Go.</p>
<p>In other language it’s also called a <em>dictionary</em> or <em>hash map</em> or <em>associative array</em>.</p>
<p>Here’s how you create a map:</p>
<pre><code class="lang-go">agesMap := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>)
</code></pre>
<p>You don’t need to set how many items the map will hold.</p>
<p>You can add a new item to the map in this way:</p>
<pre><code class="lang-go">agesMap[<span class="hljs-string">"flavio"</span>] = <span class="hljs-number">39</span>
</code></pre>
<p>You can also initialize the map with values directly using this syntax:</p>
<pre><code class="lang-go">agesMap := <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>{<span class="hljs-string">"flavio"</span>: <span class="hljs-number">39</span>}
</code></pre>
<p>You can get the value associated with a key using:</p>
<pre><code class="lang-go">age := agesMap[<span class="hljs-string">"flavio"</span>]
</code></pre>
<p>You can delete an item from the map using the <code>delete()</code> function in this way:</p>
<pre><code class="lang-go"><span class="hljs-built_in">delete</span>(agesMap, <span class="hljs-string">"flavio"</span>)
</code></pre>
<h2 id="heading-loops-in-go">Loops in Go</h2>
<p>One of Go’s best features is to give you fewer choices.</p>
<p>We have one loop statement: <code>for</code>.</p>
<p>You can use it like this:</p>
<pre><code class="lang-go"><span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++ {
    fmt.Println(i)
}
</code></pre>
<p>We first initialize a loop variable, then we set the <em>condition</em> we check for with each iteration to decide if the loop should end. Finally we have the <em>post statement</em>, executed at the end of each iteration, which in this case increments <code>i</code>.</p>
<p><code>i++</code> increments the <code>i</code> variable.</p>
<p>The <code>&lt;</code> <em>operator</em> is used to compare <code>i</code> to the number <code>10</code> and returns <code>true</code> or <code>false</code>, determining if the loop body should be executed or not.</p>
<p>We don’t need parentheses around this block, unlike other languages like C or JavaScript.</p>
<p>Other languages offer different kind of loop structures, but Go only has this one. We can simulate a <code>while</code> loop, if you’re familiar with a language that has it, like this:</p>
<pre><code class="lang-go">i := <span class="hljs-number">0</span>

<span class="hljs-keyword">for</span> i &lt; <span class="hljs-number">10</span> {
    fmt.Println(i)
  i++
}
</code></pre>
<p>We can also completely omit the condition and use <code>break</code> to end the loop when we want:</p>
<pre><code class="lang-go">i := <span class="hljs-number">0</span>

<span class="hljs-keyword">for</span> {
    fmt.Println(i)

    <span class="hljs-keyword">if</span> i &lt; <span class="hljs-number">10</span> {
        <span class="hljs-keyword">break</span>
    }

  i++
}
</code></pre>
<p>I used a <code>if</code> statement inside the loop body, but we haven’t seen <em>conditionals</em> yet! We’ll do that next.</p>
<p>One thing I want to introduce now is <code>range</code>.</p>
<p>We can use <code>for</code> to iterate through an array using this syntax:</p>
<pre><code class="lang-go">numbers := []<span class="hljs-keyword">int</span>{<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>}

<span class="hljs-keyword">for</span> i, num := <span class="hljs-keyword">range</span> numbers {
    fmt.Printf(<span class="hljs-string">"%d: %d\n"</span>, i, num)
}

<span class="hljs-comment">//0: 1</span>
<span class="hljs-comment">//1: 2</span>
<span class="hljs-comment">//2: 3</span>
</code></pre>
<p>Note: I used <code>fmt.Printf()</code> which allows us to print any value to the terminal using the <em>verbs</em> <code>%d</code> which mean <em>decimal integer</em> and <code>\n</code> means add a line terminator.</p>
<p>It’s common to use this syntax when you don’t need to use the index:</p>
<pre><code class="lang-go"><span class="hljs-keyword">for</span> _, num := <span class="hljs-keyword">range</span> numbers {
  <span class="hljs-comment">//...</span>
}
</code></pre>
<p>We're using the special <code>_</code> character that means “ignore this” to avoid the Go compiler raising an error saying “you’re not using the <code>i</code> variable!”.</p>
<h2 id="heading-conditionals-in-go">Conditionals in Go</h2>
<p>We use the <code>if</code> statement to execute different instructions depending on a condition:</p>
<pre><code class="lang-go"><span class="hljs-keyword">if</span> age &lt; <span class="hljs-number">18</span> {
    <span class="hljs-comment">//underage</span>
}
</code></pre>
<p>The <code>else</code> part is optional:</p>
<pre><code class="lang-go"><span class="hljs-keyword">if</span> age &lt; <span class="hljs-number">18</span> {
    <span class="hljs-comment">//underage</span>
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">//adult</span>
}
</code></pre>
<p>and can be combined with other <code>if</code>s:</p>
<pre><code class="lang-go"><span class="hljs-keyword">if</span> age &lt; <span class="hljs-number">12</span> {
    <span class="hljs-comment">//child</span>
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> age &lt; <span class="hljs-number">18</span>  {
  <span class="hljs-comment">//teen</span>
} <span class="hljs-keyword">else</span> {
    <span class="hljs-comment">//adult</span>
}
</code></pre>
<p>If you define any variable inside the <code>if</code>, that’s only visible inside the <code>if</code> (same applies to <code>else</code> and anywhere you open a new block with <code>{}</code>).</p>
<p>If you’re going to have many different if statements to check a single condition, it’s probably better to use <code>switch</code>:</p>
<pre><code class="lang-go"><span class="hljs-keyword">switch</span> age {
<span class="hljs-keyword">case</span> <span class="hljs-number">0</span>: fmt.Println(<span class="hljs-string">"Zero years old"</span>)
<span class="hljs-keyword">case</span> <span class="hljs-number">1</span>: fmt.Println(<span class="hljs-string">"One year old"</span>)
<span class="hljs-keyword">case</span> <span class="hljs-number">2</span>: fmt.Println(<span class="hljs-string">"Two years old"</span>)
<span class="hljs-keyword">case</span> <span class="hljs-number">3</span>: fmt.Println(<span class="hljs-string">"Three years old"</span>)
<span class="hljs-keyword">case</span> <span class="hljs-number">4</span>: fmt.Println(<span class="hljs-string">"Four years old"</span>)
<span class="hljs-keyword">default</span>: fmt.Println(i + <span class="hljs-string">" years old"</span>)
}
</code></pre>
<p>Compared to C, JavaScript, and other languages, you don’t need to have a <code>break</code> after each <code>case</code>.</p>
<h2 id="heading-operators-in-go">Operators in Go</h2>
<p>We've used some operators so far in our code examples, like <code>=</code>, <code>:=</code> and <code>&lt;</code>.</p>
<p>Let’s talk a bit more about them.</p>
<p>We have assignment operators <code>=</code> and <code>:=</code> we use to declare and initialize variables:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> a = <span class="hljs-number">1</span>

b := <span class="hljs-number">1</span>
</code></pre>
<p>We have comparison operators <code>==</code> and <code>!=</code> that take 2 arguments and return a boolean:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> num = <span class="hljs-number">1</span>
num == <span class="hljs-number">1</span> <span class="hljs-comment">//true</span>
num != <span class="hljs-number">1</span> <span class="hljs-comment">//false</span>
</code></pre>
<p>and <code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, <code>&gt;=</code>:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> num = <span class="hljs-number">1</span>
num &gt; <span class="hljs-number">1</span> <span class="hljs-comment">//false</span>
num &gt;= <span class="hljs-number">1</span> <span class="hljs-comment">//true</span>
num &lt; <span class="hljs-number">1</span> <span class="hljs-comment">//false</span>
num &lt;= <span class="hljs-number">1</span> <span class="hljs-comment">//true</span>
</code></pre>
<p>We have binary (require two arguments) arithmetic operators, like <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>, <code>%</code>.</p>
<pre><code class="lang-go"><span class="hljs-number">1</span> + <span class="hljs-number">1</span> <span class="hljs-comment">//2</span>
<span class="hljs-number">1</span> - <span class="hljs-number">1</span> <span class="hljs-comment">//0</span>
<span class="hljs-number">1</span> * <span class="hljs-number">2</span> <span class="hljs-comment">//2</span>
<span class="hljs-number">2</span> / <span class="hljs-number">2</span> <span class="hljs-comment">//1</span>
<span class="hljs-number">2</span> % <span class="hljs-number">2</span> <span class="hljs-comment">//0</span>
</code></pre>
<p><code>+</code> can also join strings:</p>
<pre><code class="lang-go"><span class="hljs-string">"a"</span> + <span class="hljs-string">"b"</span> <span class="hljs-comment">//"ab"</span>
</code></pre>
<p>We have unary operators <code>++</code> and <code>--</code> to increment or decrement a number:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> num = <span class="hljs-number">1</span>
num++ <span class="hljs-comment">// num == 2</span>
num-- <span class="hljs-comment">// num == 1</span>
</code></pre>
<p>Note that unlike C or JavaScript we can’t prepend them to a number like <code>++num</code>. Also, the operation does not return any value.</p>
<p>We have boolean operators that help us with making decisions based on <code>true</code> and <code>false</code> values: <code>&amp;&amp;</code>, <code>||</code> and <code>!</code>:</p>
<pre><code class="lang-go"><span class="hljs-literal">true</span> &amp;&amp; <span class="hljs-literal">true</span>  <span class="hljs-comment">//true</span>
<span class="hljs-literal">true</span> &amp;&amp; <span class="hljs-literal">false</span> <span class="hljs-comment">//false</span>
<span class="hljs-literal">true</span> || <span class="hljs-literal">false</span> <span class="hljs-comment">//true</span>
<span class="hljs-literal">false</span> || <span class="hljs-literal">false</span> <span class="hljs-comment">//false</span>
!<span class="hljs-literal">true</span>  <span class="hljs-comment">//false</span>
!<span class="hljs-literal">false</span> <span class="hljs-comment">//true</span>
</code></pre>
<p>Those are the main ones.</p>
<h2 id="heading-structs-in-go">Structs in Go</h2>
<p>A <strong>struct</strong> is a <em>type</em> that contains one or more variables. It’s like a collection of variables. We call them <em>fields</em>. And they can have different types.</p>
<p>Here’s an example of a struct definition:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> Person <span class="hljs-keyword">struct</span> {
    Name <span class="hljs-keyword">string</span>
    Age <span class="hljs-keyword">int</span>
}
</code></pre>
<p>Note that I used uppercase names for the fields, otherwise those will be <em>private</em> to the package. And when you pass the struct to a function provided by another package, like the ones we use to work with JSON or database, those fields cannot be accessed.</p>
<p>Once we define a struct we can initialize a variable with that type:</p>
<pre><code class="lang-go">flavio := Person{<span class="hljs-string">"Flavio"</span>, <span class="hljs-number">39</span>}
</code></pre>
<p>and we can access the individual fields using the dot syntax:</p>
<pre><code class="lang-go">flavio.Age <span class="hljs-comment">//39</span>
flavio.Name <span class="hljs-comment">//"Flavio"</span>
</code></pre>
<p>You can also initialize a new variable from a struct in this way:</p>
<pre><code class="lang-go">flavio := Person{Age: <span class="hljs-number">39</span>, Name: <span class="hljs-string">"Flavio"</span>}
</code></pre>
<p>This lets you initialize only one field, too:</p>
<pre><code class="lang-go">flavio := Person{Age: <span class="hljs-number">39</span>}
</code></pre>
<p>or even initialize it without any value:</p>
<pre><code class="lang-go">flavio := Person{}

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

<span class="hljs-keyword">var</span> flavio Person
</code></pre>
<p>and set the values later:</p>
<pre><code class="lang-go">flavio.Name = <span class="hljs-string">"Flavio"</span>
flavio.Age = <span class="hljs-number">39</span>
</code></pre>
<p>Structs are useful because you can group unrelated data and pass it around to/from functions, store in a slice, and more.</p>
<p>Once defined, a struct is a type like <code>int</code> or <code>string</code> and this means you can use it inside other structs, too:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> FullName <span class="hljs-keyword">struct</span> {
    FirstName <span class="hljs-keyword">string</span>
    LastName <span class="hljs-keyword">string</span>
}

<span class="hljs-keyword">type</span> Person <span class="hljs-keyword">struct</span> {
    Name FullName
    Age <span class="hljs-keyword">int</span>
}
</code></pre>
<h2 id="heading-functions-in-go">Functions in Go</h2>
<p>A function is a block of code that’s assigned a name, and contains some instructions.</p>
<p>In the “Hello, World!” example we created a <code>main</code> function, which is the entry point of the program.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

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

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    fmt.Println(<span class="hljs-string">"Hello, World!"</span>)
}
</code></pre>
<p>That’s a special function.</p>
<p>Usually we define functions with a custom name:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">doSomething</span><span class="hljs-params">()</span></span> {

}
</code></pre>
<p>and then you can call them, like this:</p>
<pre><code class="lang-go">doSomething()
</code></pre>
<p>A function can accept parameters, and we have to set the type of the parameters like this:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">doSomething</span><span class="hljs-params">(a <span class="hljs-keyword">int</span>, b <span class="hljs-keyword">int</span>)</span></span> {

}

doSomething(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)
</code></pre>
<p><code>a</code> and <code>b</code> are the names we associate to the parameters internally to the function.</p>
<p>A function can return a value, like this:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">sumTwoNumbers</span><span class="hljs-params">(a <span class="hljs-keyword">int</span>, b <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
    <span class="hljs-keyword">return</span> a + b
}

result := sumTwoNumbers(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)
</code></pre>
<p>Note that we specified the return value <em>type</em>.</p>
<p>A function in Go can return more than one value:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">performOperations</span><span class="hljs-params">(a <span class="hljs-keyword">int</span>, b <span class="hljs-keyword">int</span>)</span> <span class="hljs-params">(<span class="hljs-keyword">int</span>, <span class="hljs-keyword">int</span>)</span></span> {
    <span class="hljs-keyword">return</span> a + b, a - b
}

sum, diff := performOperations(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)
</code></pre>
<p>It’s interesting because many languages only allow one return value.</p>
<p>Any variable defined inside the function is local to the function.</p>
<p>A function can also accept an unlimited number of parameters, and in this case we call it a <em>variadic function</em>:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">sumNumbers</span><span class="hljs-params">(numbers ...<span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
    sum := <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> _, number := <span class="hljs-keyword">range</span> numbers {
        sum += number
    }
    <span class="hljs-keyword">return</span> sum
}

total := sumNumbers(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>)
</code></pre>
<h2 id="heading-pointers-in-go">Pointers in Go</h2>
<p>Go supports pointers.</p>
<p>Suppose you have a variable:</p>
<pre><code class="lang-go">age := <span class="hljs-number">20</span>
</code></pre>
<p>Using <code>&amp;age</code> you get the pointer to the variable, its memory address.</p>
<p>When you have the pointer to the variable, you can get the value it points to by using the <code>*</code> operator:</p>
<pre><code class="lang-go">age := <span class="hljs-number">20</span>
ageptr = &amp;age
agevalue = *ageptr
</code></pre>
<p>This is useful when you want to call a function and pass the variable as a parameter. Go by default copies the value of the variable inside the function, so this will not change the value of <code>age</code>:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">increment</span><span class="hljs-params">(a <span class="hljs-keyword">int</span>)</span></span> {
    a = a + <span class="hljs-number">1</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    age := <span class="hljs-number">20</span>
    increment(age)

    <span class="hljs-comment">//age is still 20</span>
}
</code></pre>
<p>You can use pointers for this:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">increment</span><span class="hljs-params">(a *<span class="hljs-keyword">int</span>)</span></span> {
    *a = *a + <span class="hljs-number">1</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    age := <span class="hljs-number">20</span>
    increment(&amp;age)

    <span class="hljs-comment">//age is now 21</span>
}
</code></pre>
<h2 id="heading-methods-in-go">Methods in Go</h2>
<p>You can assign a function to a struct, and in this case we call it a <em>method</em>.</p>
<p>Example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> Person <span class="hljs-keyword">struct</span> {
    Name <span class="hljs-keyword">string</span>
    Age <span class="hljs-keyword">int</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(p Person)</span> <span class="hljs-title">Speak</span><span class="hljs-params">()</span></span> {
    fmt.Println(<span class="hljs-string">"Hello from "</span> + p.Name)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    flavio := Person{Age: <span class="hljs-number">39</span>, Name: <span class="hljs-string">"Flavio"</span>}
    flavio.Speak()
}
</code></pre>
<p>You can declare methods to be pointer receiver or value receiver.</p>
<p>The above example shows a value receiver. It receives a copy of the struct instance.</p>
<p>This would be a pointer receiver that receives the pointer to the struct instance:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(p *Person)</span> <span class="hljs-title">Speak</span><span class="hljs-params">()</span></span> {
    fmt.Println(<span class="hljs-string">"Hello from "</span> + p.Name)
}
</code></pre>
<h2 id="heading-interfaces-in-go">Interfaces in Go</h2>
<p>An interface is a <em>type</em> that defines one or more <em>method signatures</em>.</p>
<p>Methods are not implemented, just their signature: the name, parameter types and return value type.</p>
<p>Something like this:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> Speaker <span class="hljs-keyword">interface</span> {
    Speak()
}
</code></pre>
<p>Now you could have a function accept any type that implements all the methods defined by the interface:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">SaySomething</span><span class="hljs-params">(s Speaker)</span></span> {
    s.Speak()
}
</code></pre>
<p>And we can pass it any struct that implements those methods:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> Speaker <span class="hljs-keyword">interface</span> {
    Speak()
}

<span class="hljs-keyword">type</span> Person <span class="hljs-keyword">struct</span> {
    Name <span class="hljs-keyword">string</span>
    Age <span class="hljs-keyword">int</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(p Person)</span> <span class="hljs-title">Speak</span><span class="hljs-params">()</span></span> {
    fmt.Println(<span class="hljs-string">"Hello from "</span> + p.Name)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">SaySomething</span><span class="hljs-params">(s Speaker)</span></span> {
    s.Speak()
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    flavio := Person{Age: <span class="hljs-number">39</span>, Name: <span class="hljs-string">"Flavio"</span>}
    SaySomething(flavio)
}
</code></pre>
<h2 id="heading-where-to-go-from-here">Where to Go from Here</h2>
<p>This handbook is an introduction to the Go programming language.</p>
<p>Beside these basics, there are many things to learn now.</p>
<p>Garbage collection, error handling, concurrency and networking, the filesystem APIs, and much more.</p>
<p>The sky is the limit.</p>
<p>My suggestion is to pick a program you want to build and just start, learning the things you need along the way.</p>
<p>It will be fun and rewarding.</p>
<p>Note: <a target="_blank" href="https://thevalleyofcode.com/download/go/">you can get a PDF and ePub version of this Go Beginner's Handbook here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The PHP Handbook – Learn PHP for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ PHP is an incredibly popular programming language. Statistics say it’s used by 80% of all websites. It’s the language that powers WordPress, the widely used content management system for websites. And it also powers a lot of different frameworks that... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-php-handbook/</link>
                <guid isPermaLink="false">66bb5ab5f55324ca867c8905</guid>
                
                    <category>
                        <![CDATA[ PHP ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Flavio Copes ]]>
                </dc:creator>
                <pubDate>Thu, 07 Jul 2022 16:35:35 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/07/Group-13--2-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>PHP is an incredibly popular programming language.</p>
<p>Statistics say it’s used by 80% of all websites. It’s the language that powers WordPress, the widely used content management system for websites.</p>
<p>And it also powers a lot of different frameworks that make Web Development easier, like Laravel. Speaking of Laravel, it may be one of the most compelling reasons to learn PHP these days.</p>
<h2 id="heading-why-learn-php">Why Learn PHP?</h2>
<p>PHP is quite a polarizing language. Some people love it, and some people hate it. If we move a step above the emotions and look at the language as a tool, PHP has a lot to offer.</p>
<p>Sure it’s not perfect. But let me tell you – no language is.</p>
<p>In this handbook, I’m going to help you learn PHP.</p>
<p>This book is a perfect introduction if you’re new to the language. It’s also perfect if you’ve done “some PHP” in the past and you want to get back to it.</p>
<p>I’ll explain modern PHP, version 8+.</p>
<p>PHP has evolved a lot in the last few years. So if the last time you tried it was PHP 5 or even PHP 4, you’ll be surprised at all the good things that PHP now offers.</p>
<p>Let’s go!</p>
<p>Here's what we'll cover in this handbook:</p>
<ol>
<li><a class="post-section-overview" href="#heading-introduction-to-php">Introduction to PHP</a></li>
<li><a class="post-section-overview" href="#heading-what-kind-of-language-is-php">What Kind of Language is PHP?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-setup-php">How to Setup PHP</a></li>
<li><a class="post-section-overview" href="#heading-how-to-code-your-first-php-program">How to Code Your First PHP Program</a></li>
<li><a class="post-section-overview" href="#heading-php-language-basics">PHP Language Basics</a></li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-strings-in-php">How to Work with Strings in PHP</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-built-in-functions-for-numbers-in-php">How to Use Built-in Functions for Numbers in PHP</a></li>
<li><a class="post-section-overview" href="#heading-how-arrays-work-in-php">How Arrays Work in PHP</a></li>
<li><a class="post-section-overview" href="#heading-how-conditionals-work-in-php">How Conditionals Work in PHP</a></li>
<li><a class="post-section-overview" href="#heading-how-loops-work-in-php">How Loops Work in PHP</a></li>
<li><a class="post-section-overview" href="#heading-how-functions-work-in-php">How Functions Work in PHP</a></li>
<li><a class="post-section-overview" href="#id=&quot;how-to-loop-through-arrays-with-map-filter-and-reduce-in-php">How to Loop Through Arrays with <code>map()</code>, <code>filter()</code>, and <code>reduce()</code> in PHP</a></li>
<li><a class="post-section-overview" href="#heading-object-oriented-programming-in-php">Object Oriented Programming in PHP</a></li>
<li><a class="post-section-overview" href="#heading-how-to-include-other-php-files">How to Include Other PHP Files</a></li>
<li><a class="post-section-overview" href="#heading-useful-constants-functions-and-variables-for-filesystem-in-php">Useful Constants, Functions and Variables for Filesystem in PHP</a></li>
<li><a class="post-section-overview" href="#heading-how-to-handle-errors-in-php">How to Handle Errors in PHP</a></li>
<li><a class="post-section-overview" href="#heading-how-to-handle-exceptions-in-php">How to Handle Exceptions in PHP</a></li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-dates-in-php">How to Work with Dates in PHP</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-constants-and-enums-in-php">How to Use Constants and Enums in PHP</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-php-as-a-web-app-development-platform">How to Use PHP as a Web App Development Platform</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-composer-and-packagist">How to Use Composer and Packagist</a></li>
<li><a class="post-section-overview" href="#heading-how-to-deploy-a-php-application">How to Deploy a PHP Application</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<p>Note that you can get a <a target="_blank" href="https://thevalleyofcode.com/download/php/">PDF, ePub, or Mobi</a> version of this handbook for easier reference, or for reading on your Kindle or tablet.</p>
<h2 id="heading-introduction-to-php">Introduction to PHP</h2>
<p>PHP is a programming language that many devs use to create Web Applications, among other things.</p>
<p>As a language, it had a humble beginning. It was first created in 1994 by Rasmus Lerdorf to build his personal website. He didn’t know at the time it would eventually become one of the most popular programming languages in the world. It became popular later on, in 1997/8, and exploded in the 2000s when PHP 4 landed.</p>
<p>You can use PHP to add a little interactivity to an HTML page.</p>
<p>Or you can use it as a Web Application engine that creates HTML pages dynamically and sends them to the browser.</p>
<p>It can scale to millions of page views.</p>
<p>Did you know Facebook is powered by PHP? Ever heard of Wikipedia? Slack? Etsy?</p>
<h2 id="heading-what-kind-of-language-is-php">What Kind of Language is PHP?</h2>
<p>Let’s get into some technical jargon.</p>
<p>Programming languages are divided into groups depending on their characteristics. For example interpreted/compiled, strongly/loosely typed, dynamically/statically typed.</p>
<p>PHP is often called a “scripting language” and it’s an <strong>interpreted language</strong>. If you’ve used compiled languages like C or Go or Swift, the main difference is that you don’t need to compile a PHP program before you run it.</p>
<p>Those languages are compiled and the compiler generates an executable program that you then run. It’s a 2-steps process.</p>
<p>The PHP <em>interpreter</em> is responsible for interpreting the instructions written in a PHP program when it’s executed. It’s just one step. You tell the interpreter to run the program. It's a completely different workflow.</p>
<p>PHP is a <strong>dynamically typed language</strong>. The types of variables are checked at runtime, rather than before the code is executed as happens for statically typed languages. (These also happen to be compiled – the two characteristics often go hand in hand.)</p>
<p>PHP is also loosely (weakly) typed. Compared to strongly typed languages like Swift, Go, C or Java, you don’t need to declare the types of your variables.</p>
<p>Being interpreted and loosely/dynamically typed will make bugs harder to find before they happen at runtime.</p>
<p>In compiled languages, you can often catch errors at compile time, something that does not happen in interpreted languages.</p>
<p>But on the other hand, an interpreted language has more flexibility.</p>
<p>Fun fact: PHP is written internally in C, a compiled and statically typed language.</p>
<p>In its nature, PHP is similar to JavaScript, another dynamically typed, loosely typed, and interpreted language.</p>
<p>PHP supports object-oriented programming, and also functional programming. You can use it as you prefer.</p>
<h2 id="heading-how-to-setup-php">How to Setup PHP</h2>
<p>There are many ways to install PHP on your local machine.</p>
<p>The most convenient way I’ve found to install PHP locally is to use MAMP.</p>
<p>MAMP is a tool that’s freely available for all the Operating Systems – Mac, Windows and Linux. It is a package that gives you all the tools you need to get up and running.</p>
<p>PHP is run by a HTTP Server, which is responsible for responding to HTTP requests, the ones made by the browser. So you access a URL with your browser, Chrome or Firefox or Safari, and the HTTP server responds with some HTML content.</p>
<p>The server is typically Apache or NGINX.</p>
<p>Then to do anything non-trivial you’ll need a database, like MySQL.</p>
<p>MAMP is a package that provides all of that, and more, and gives you a nice interface to start/stop everything at once.</p>
<p>Of course, you can set up each piece on its own if you like, and many tutorials explain how to do that. But I like simple and practical tools, and MAMP is one of those.</p>
<p>You can follow this handbook with any kind of PHP installation method, not just MAMP.</p>
<p>That said, if you don’t have PHP installed yet and you want to use MAMP, go to <a target="_blank" href="https://www.mamp.info/">https://www.mamp.info</a> and install it.</p>
<p>The process will depend on your operating system, but once you’re done with the installation, you will have a “MAMP” application installed.</p>
<p>Start that, and you will see a window similar to this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-24_at_15.14.05.jpg" alt="Screen Shot 2022-06-24 at 15.14.05.jpg" width="600" height="400" loading="lazy"></p>
<p>Make sure the PHP version selected is the latest available.</p>
<p>At the time of writing MAMP lets you pick 8.0.8.</p>
<p>NOTE: I noticed MAMP has a version that’s a bit behind, not the latest. You can install a more recent version of PHP by enabling the MAMP PRO Demo, then install the latest release from the MAMP PRO settings (in my case it was 8.1.0). Then close it and reopen MAMP (non-pro version). MAMP PRO has more features so you might want to use it, but it’s not necessary to follow this handbook.</p>
<p>Press the Start button at the top right. This will start the Apache HTTP server, with PHP enabled, and the MySQL database.</p>
<p>Go to the URL <a target="_blank" href="http://localhost:8888/">http://localhost:8888</a> and you will see a page similar to this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-24_at_15.19.05.jpg" alt="Screen Shot 2022-06-24 at 15.19.05.jpg" width="600" height="400" loading="lazy"></p>
<p>We’re ready to write some PHP!</p>
<p>Open the folder listed as “Document root”. If you're using MAMP on a Mac it’s by default <code>/Applications/MAMP/htdocs</code>.</p>
<p>On Windows it’s <code>C:\MAMP\htdocs</code>.</p>
<p>Yours might be different depending on your configuration. Using MAMP you can find it in the user interface of the application.</p>
<p>In there, you will find a file named <code>index.php</code>.</p>
<p>That is responsible for printing the page shown above.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-24_at_15.17.58.jpg" alt="Screen Shot 2022-06-24 at 15.17.58.jpg" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-code-your-first-php-program">How to Code Your First PHP Program</h2>
<p>When learning a new programming language we have this tradition of creating a “Hello, World!” application. Something that prints those strings.</p>
<p>Make sure MAMP is running, and open the <code>htdocs</code> folder as explained above.</p>
<p>Open the <code>index.php</code> file in a code editor.</p>
<p>I recommend using <a target="_blank" href="https://code.visualstudio.com">VS Code</a>, as it’s a very simple and powerful code editor. You can check out <a target="_blank" href="https://flaviocopes.com/vscode/">https://flaviocopes.com/vscode/</a> for an introduction.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-24_at_15.37.36.jpg" alt="Screen Shot 2022-06-24 at 15.37.36.jpg" width="600" height="400" loading="lazy"></p>
<p>This is the code that generates the “Welcome to MAMP” page you saw in the browser.</p>
<p>Delete everything and replace it with:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
<span class="hljs-keyword">echo</span> <span class="hljs-string">'Hello World'</span>;
<span class="hljs-meta">?&gt;</span>
</code></pre>
<p>Save, refresh the page on <a target="_blank" href="http://localhost:8888">http://localhost:8888</a>, you should see this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-24_at_15.39.00.jpg" alt="Screen Shot 2022-06-24 at 15.39.00.jpg" width="600" height="400" loading="lazy"></p>
<p>Great! That was your first PHP program.</p>
<p>Let’s explain what is happening here.</p>
<p>We have the Apache HTTP server listening on port <code>8888</code> on localhost, your computer.</p>
<p>When we access <a target="_blank" href="http://localhost:8888">http://localhost:8888</a> with the browser, we’re making an HTTP request, asking for the content of the route <code>/</code>, the base URL.</p>
<p>Apache, by default, is configured to serve that route serving the <code>index.html</code> file included in the <code>htdocs</code> folder. That file does not exist – but as we have configured Apache to work with PHP, it will then search for an <code>index.php</code> file.</p>
<p>This file exists, and PHP code is executed server-side before Apache sends the page back to the browser.</p>
<p>In the PHP file, we have a <code>&lt;?php</code> opening, which says “here starts some PHP code”.</p>
<p>We have an ending <code>?&gt;</code> that closes the PHP code snippet, and inside it, we use the <code>echo</code> instruction to print the string enclosed into quotes into the HTML.</p>
<p>A semicolon is required at the end of every statement.</p>
<p>We have this opening/closing structure because we can embed PHP inside HTML. PHP is a scripting language, and its goal is to be able to “decorate” an HTML page with dynamic data.</p>
<p>Note that with modern PHP, we generally avoid mixing PHP into the HTML. Instead, we use PHP as a “framework to generate the HTML” – for example using tools like Laravel. But we'll discuss <em>plain PHP</em> in this book, so it makes sense to start from the basics.</p>
<p>For example, something like this will give you the same result in the browser:</p>
<pre><code class="lang-php">Hello
<span class="hljs-meta">&lt;?php</span>
<span class="hljs-keyword">echo</span> <span class="hljs-string">'World'</span>;
<span class="hljs-meta">?&gt;</span>
</code></pre>
<p>To the final user, who looks at the browser and has no idea of the code behind the scenes, there’s no difference at all.</p>
<p>The page is technically an HTML page, even though it does not contain HTML tags but just a <code>Hello World</code> string. But the browser can figure out how to display that in the window.</p>
<h2 id="heading-php-language-basics">PHP Language Basics</h2>
<p>After the first “Hello World”, it’s time to dive into the language features with more details.</p>
<h3 id="heading-how-variables-work-in-php">How Variables Work in PHP</h3>
<p>Variables in PHP start with the dollar sign <code>$</code>, followed by an identifier, which is a set of alphanumeric chars and the underscore <code>_</code> char.</p>
<p>You can assign a variable any type of value, like strings (defined using single or double quotes):</p>
<pre><code class="lang-php">$name = <span class="hljs-string">'Flavio'</span>;

$name = <span class="hljs-string">"Flavio"</span>;
</code></pre>
<p>Or numbers:</p>
<pre><code class="lang-php">$age = <span class="hljs-number">20</span>;
</code></pre>
<p>or any other type that PHP allows, as we’ll later see.</p>
<p>Once a variable is assigned a value, for example a string, we can reassign it a different type of value, like a number:</p>
<pre><code class="lang-php">$name = <span class="hljs-number">3</span>;
</code></pre>
<p>PHP won’t complain that now the type is different.</p>
<p>Variable names are case-sensitive. <code>$name</code> is different from <code>$Name</code>.</p>
<p>It’s not a hard rule, but generally variable names are written in camelCase format, like this: <code>$brandOfCar</code> or <code>$ageOfDog</code>. We keep the first letter lowercase, and the letters of the subsequent words uppercase.</p>
<h3 id="heading-how-to-write-comments-in-php">How to Write Comments in PHP</h3>
<p>A very important part of any programming language is how you write comments.</p>
<p>You write single-line comments in PHP in this way:</p>
<pre><code class="lang-php"><span class="hljs-comment">// single line comment</span>
</code></pre>
<p>Multi-line comments are defined in this way:</p>
<pre><code class="lang-php"><span class="hljs-comment">/*

this is a comment

*/</span>

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

<span class="hljs-comment">/*
 *
 * this is a comment
 *
 */</span>

<span class="hljs-comment">//or to comment out a portion of code inside a line:</span>

<span class="hljs-comment">/* this is a comment */</span>
</code></pre>
<h3 id="heading-what-are-types-in-php">What are Types in PHP?</h3>
<p>I mentioned strings and numbers.</p>
<p>PHP has the following types:</p>
<ul>
<li><code>bool</code> boolean values (true/false)</li>
<li><code>int</code> integer numbers (no decimals)</li>
<li><code>float</code> floating-point numbers (decimals)</li>
<li><code>string</code> strings</li>
<li><code>array</code> arrays</li>
<li><code>object</code> objects</li>
<li><code>null</code> a value that means “no value assigned”</li>
</ul>
<p>and a few other more advanced ones.</p>
<h3 id="heading-how-to-print-the-value-of-a-variable-in-php">How to Print the Value of a Variable in PHP</h3>
<p>We can use the <code>var_dump()</code> built-in function to get the value of a variable:</p>
<pre><code class="lang-php">$name = <span class="hljs-string">'Flavio'</span>;

var_dump($name);
</code></pre>
<p>The <code>var_dump($name)</code> instruction will print <code>string(6) "Flavio"</code> to the page, which tells us the variable is a string of 6 characters.</p>
<p>If we used this code:</p>
<pre><code class="lang-php">$age = <span class="hljs-number">20</span>;

var_dump($age);
</code></pre>
<p>we’d have <code>int(20)</code> back, saying the value is 20 and it’s an integer.</p>
<p><code>var_dump()</code> is one of the essential tools in your PHP debugging tool belt.</p>
<h3 id="heading-how-operators-work-in-php">How Operators Work in PHP</h3>
<p>Once you have a few variables you can make operations with them:</p>
<pre><code class="lang-php">$base = <span class="hljs-number">20</span>;
$height = <span class="hljs-number">10</span>;

$area = $base * $height;
</code></pre>
<p>The <code>*</code> I used to multiply $base by $height is the multiplication operator.</p>
<p>We have quite a few operators – so let’s do a quick roundup of the main ones.</p>
<p>To start with, here are the arithmetic operators: <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code> (division), <code>%</code> (remainder) and <code>**</code> (exponential).</p>
<p>We have the assignment operator <code>=</code>, which we already used to assign a value to a variable.</p>
<p>Next up we have comparison operators, like <code>&lt;</code>, <code>&gt;</code>, <code>&lt;=</code>, <code>&gt;=</code>. Those work like they do in math.</p>
<pre><code class="lang-php"><span class="hljs-number">2</span> &lt; <span class="hljs-number">1</span>; <span class="hljs-comment">//false</span>
<span class="hljs-number">1</span> &lt;= <span class="hljs-number">1</span>; <span class="hljs-comment">// true</span>
<span class="hljs-number">1</span> &lt;= <span class="hljs-number">2</span>; <span class="hljs-comment">// true</span>
</code></pre>
<p><code>==</code> returns true if the two operands are equal.</p>
<p><code>===</code> returns true if the two operands are identical.</p>
<p>What’s the difference?</p>
<p>You’ll find it with experience, but for example:</p>
<pre><code class="lang-php"><span class="hljs-number">1</span> == <span class="hljs-string">'1'</span>; <span class="hljs-comment">//true</span>
<span class="hljs-number">1</span> === <span class="hljs-string">'1'</span>; <span class="hljs-comment">//false</span>
</code></pre>
<p>We also have <code>!=</code> to detect if operands are <em>not</em> equal:</p>
<pre><code class="lang-php"><span class="hljs-number">1</span> != <span class="hljs-number">1</span>; <span class="hljs-comment">//false</span>
<span class="hljs-number">1</span> != <span class="hljs-string">'1'</span>; <span class="hljs-comment">//false</span>
<span class="hljs-number">1</span> != <span class="hljs-number">2</span>; <span class="hljs-comment">//true</span>

<span class="hljs-comment">//hint: &lt;&gt; works in the same way as !=, 1 &lt;&gt; 1</span>
</code></pre>
<p>and <code>!==</code> to detect if operands are not identical:</p>
<pre><code class="lang-php"><span class="hljs-number">1</span> !== <span class="hljs-number">1</span>; <span class="hljs-comment">//false</span>
<span class="hljs-number">1</span> !== <span class="hljs-string">'1'</span>; <span class="hljs-comment">//true</span>
</code></pre>
<p>Logical operators work with boolean values:</p>
<pre><code class="lang-php"><span class="hljs-comment">// Logical AND with &amp;&amp; or "and"</span>

<span class="hljs-literal">true</span> &amp;&amp; <span class="hljs-literal">true</span>; <span class="hljs-comment">//true</span>
<span class="hljs-literal">true</span> &amp;&amp; <span class="hljs-literal">false</span>; <span class="hljs-comment">//false</span>
<span class="hljs-literal">false</span> &amp;&amp; <span class="hljs-literal">true</span>; <span class="hljs-comment">//false</span>
<span class="hljs-literal">false</span> &amp;&amp; <span class="hljs-literal">false</span>; <span class="hljs-comment">//false</span>

<span class="hljs-literal">true</span> <span class="hljs-keyword">and</span> <span class="hljs-literal">true</span>; <span class="hljs-comment">//true</span>
<span class="hljs-literal">true</span> <span class="hljs-keyword">and</span> <span class="hljs-literal">false</span>; <span class="hljs-comment">//false</span>
<span class="hljs-literal">false</span> <span class="hljs-keyword">and</span> <span class="hljs-literal">true</span>; <span class="hljs-comment">//false</span>
<span class="hljs-literal">false</span> <span class="hljs-keyword">and</span> <span class="hljs-literal">false</span>; <span class="hljs-comment">//false</span>

<span class="hljs-comment">// Logical OR with || or "or"</span>

<span class="hljs-literal">true</span> || <span class="hljs-literal">true</span>; <span class="hljs-comment">// true</span>
<span class="hljs-literal">true</span> || <span class="hljs-literal">false</span> <span class="hljs-comment">//true</span>
<span class="hljs-literal">false</span> || <span class="hljs-literal">true</span> <span class="hljs-comment">//true</span>
<span class="hljs-literal">false</span> || <span class="hljs-literal">false</span> <span class="hljs-comment">//false</span>

<span class="hljs-literal">true</span> <span class="hljs-keyword">or</span> <span class="hljs-literal">true</span>; <span class="hljs-comment">// true</span>
<span class="hljs-literal">true</span> <span class="hljs-keyword">or</span> <span class="hljs-literal">false</span> <span class="hljs-comment">//true</span>
<span class="hljs-literal">false</span> <span class="hljs-keyword">or</span> <span class="hljs-literal">true</span> <span class="hljs-comment">//true</span>
<span class="hljs-literal">false</span> <span class="hljs-keyword">or</span> <span class="hljs-literal">false</span> <span class="hljs-comment">//false</span>

<span class="hljs-comment">// Logical XOR (one of the two is true, but not both)</span>

<span class="hljs-literal">true</span> <span class="hljs-keyword">xor</span> <span class="hljs-literal">true</span>; <span class="hljs-comment">// false</span>
<span class="hljs-literal">true</span> <span class="hljs-keyword">xor</span> <span class="hljs-literal">false</span> <span class="hljs-comment">//true</span>
<span class="hljs-literal">false</span> <span class="hljs-keyword">xor</span> <span class="hljs-literal">true</span> <span class="hljs-comment">//true</span>
<span class="hljs-literal">false</span> <span class="hljs-keyword">xor</span> <span class="hljs-literal">false</span> <span class="hljs-comment">//false</span>
</code></pre>
<p>We also have the <em>not</em> operator:</p>
<pre><code class="lang-php">$test = <span class="hljs-literal">true</span>

!$test <span class="hljs-comment">//false</span>
</code></pre>
<p>I used the boolean values <code>true</code> and <code>false</code> here, but in practice you’ll use expressions that evaluate to either true or false, for example:</p>
<pre><code class="lang-php"><span class="hljs-number">1</span> &gt; <span class="hljs-number">2</span> || <span class="hljs-number">2</span> &gt; <span class="hljs-number">1</span>; <span class="hljs-comment">//true</span>

<span class="hljs-number">1</span> !== <span class="hljs-number">2</span> &amp;&amp; <span class="hljs-number">2</span> &gt; <span class="hljs-number">2</span>; <span class="hljs-comment">//false</span>
</code></pre>
<p>All of the operators listed above are <em>binary</em>, meaning they involve 2 operands.</p>
<p>PHP also has 2 unary operators: <code>++</code> and <code>--</code>:</p>
<pre><code class="lang-php">$age = <span class="hljs-number">20</span>;
$age++;
<span class="hljs-comment">//age is now 21</span>

$age--;
<span class="hljs-comment">//age is now 20</span>
</code></pre>
<h2 id="heading-how-to-work-with-strings-in-php">How to Work with Strings in PHP</h2>
<p>I introduced the use of strings before when we talked about variables and we defined a string using this notation:</p>
<pre><code class="lang-php">$name = <span class="hljs-string">'Flavio'</span>; <span class="hljs-comment">//string defined with single quotes</span>

$name = <span class="hljs-string">"Flavio"</span>; <span class="hljs-comment">//string defined with double quotes</span>
</code></pre>
<p>The big difference between using single and double quotes is that with double quotes we can expand variables in this way:</p>
<pre><code class="lang-php">$test = <span class="hljs-string">'an example'</span>;

$example = <span class="hljs-string">"This is <span class="hljs-subst">$test</span>"</span>; <span class="hljs-comment">//This is an example</span>
</code></pre>
<p>and with double quotes we can use <em>escape characters</em> (think new lines <code>\n</code> or tabs <code>\t</code>):</p>
<pre><code class="lang-php">$example = <span class="hljs-string">"This is a line\nThis is a line"</span>;

<span class="hljs-comment">/*
output is:

This is a line
This is a line
*/</span>
</code></pre>
<p>PHP offers you a very comprehensive functions in its standard library (the library of functionalities that the language offers by default).</p>
<p>First, we can concatenate two strings using the <code>.</code> operator:</p>
<pre><code class="lang-php">$firstName = <span class="hljs-string">'Flavio'</span>;
$lastName = <span class="hljs-string">'Copes'</span>;

$fullName = $firstName . <span class="hljs-string">' '</span> . $lastName;
</code></pre>
<p>We can check the length of a string using the <code>strlen()</code> function:</p>
<pre><code class="lang-php">$name = <span class="hljs-string">'Flavio'</span>;
strlen($name); <span class="hljs-comment">//6</span>
</code></pre>
<p>This is the first time we've used a function.</p>
<p>A function is composed of an identifier (<code>strlen</code> in this case) followed by parentheses. Inside those parentheses, we pass one or more arguments to the function. In this case, we have one argument.</p>
<p>The function does <em>something</em> and when it’s done it can return a value. In this case, it returns the number <code>6</code>. If there’s no value returned, the function returns <code>null</code>.</p>
<p>We’ll see how to define our own functions later.</p>
<p>We can get a portion of a string using <code>substr()</code>:</p>
<pre><code class="lang-php">$name = <span class="hljs-string">'Flavio'</span>;
substr($name, <span class="hljs-number">3</span>); <span class="hljs-comment">//"vio" - start at position 3, get all the rest</span>
substr($name, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">//"av" - start at position 2, get 2 items</span>
</code></pre>
<p>We can replace a portion of a string using <code>str_replace()</code>:</p>
<pre><code class="lang-php">$name = <span class="hljs-string">'Flavio'</span>;
str_replace(<span class="hljs-string">'avio'</span>, <span class="hljs-string">'ower'</span>, $name); <span class="hljs-comment">//"Flower"</span>
</code></pre>
<p>Of course we can assign the result to a new variable:</p>
<pre><code class="lang-php">$name = <span class="hljs-string">'Flavio'</span>;
$itemObserved = str_replace(<span class="hljs-string">'avio'</span>, <span class="hljs-string">'ower'</span>, $name); <span class="hljs-comment">//"Flower"</span>
</code></pre>
<p>There are a lot more built-in functions you can use to work with strings.</p>
<p>Here is a brief non-comprehensive list just to show you the possibilities:</p>
<ul>
<li><a target="_blank" href="https://www.php.net/manual/en/function.trim.php"><code>trim()</code></a> strips white space at the beginning and end of a string</li>
<li><a target="_blank" href="https://www.php.net/manual/en/function.strtoupper.php"><code>strtoupper()</code></a> makes a string uppercase</li>
<li><a target="_blank" href="https://www.php.net/manual/en/function.strtolower.php"><code>strtolower()</code></a> makes a string lowercase</li>
<li><a target="_blank" href="https://www.php.net/manual/en/function.ucfirst.php"><code>ucfirst()</code></a> makes the first character uppercase</li>
<li><a target="_blank" href="https://www.php.net/manual/en/function.strpos.php"><code>strpos()</code></a> finds the firsts occurrence of a substring in the string</li>
<li><a target="_blank" href="https://www.php.net/manual/en/function.explode.php"><code>explode()</code></a> to split a string into an array</li>
<li><a target="_blank" href="https://www.php.net/manual/en/function.implode.php"><code>implode()</code></a> to join array elements in a string</li>
</ul>
<p>You can find a full list <a target="_blank" href="https://www.php.net/manual/en/book.strings.php">here</a>.</p>
<h2 id="heading-how-to-use-built-in-functions-for-numbers-in-php">How to Use Built-in Functions for Numbers in PHP</h2>
<p>I previously listed the few functions we commonly use for strings.</p>
<p>Let’s make a list of the functions we use with numbers:</p>
<ul>
<li><a target="_blank" href="https://www.php.net/manual/en/function.round.php"><code>round()</code></a> to round a decimal number, up/down depending if the value is &gt; 0.5 or smaller</li>
<li><a target="_blank" href="https://www.php.net/manual/en/function.ceil.php"><code>ceil()</code></a> to round a a decimal number up</li>
<li><a target="_blank" href="https://www.php.net/manual/en/function.floor.php"><code>floor()</code></a> to round a decimal number down</li>
<li><a target="_blank" href="https://www.php.net/manual/en/function.rand.php"><code>rand()</code></a> generates a random integer</li>
<li><a target="_blank" href="https://www.php.net/manual/en/function.min.php"><code>min()</code></a> finds the lowest number in the numbers passed as arguments</li>
<li><a target="_blank" href="https://www.php.net/manual/en/function.max.php"><code>max()</code></a> finds the highest number in the numbers passed as arguments</li>
<li><a target="_blank" href="https://www.php.net/manual/en/function.is-nan.php"><code>is_nan()</code></a> returns true if the number is not a number</li>
</ul>
<p>There are a ton of different functions for all sorts of math operations like sine, cosine, tangents, logarithms, and so on. You can find a full list <a target="_blank" href="https://www.php.net/manual/en/book.math.php">here</a>.</p>
<h2 id="heading-how-arrays-work-in-php">How Arrays Work in PHP</h2>
<p>Arrays are lists of values grouped under a common name.</p>
<p>You can define an empty array in two different ways:</p>
<pre><code class="lang-php">$list = [];

$list = <span class="hljs-keyword">array</span>();
</code></pre>
<p>An array can be initialized with values:</p>
<pre><code class="lang-php">$list = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>];

$list = <span class="hljs-keyword">array</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
</code></pre>
<p>Arrays can hold values of any type:</p>
<pre><code class="lang-php">$list = [<span class="hljs-number">1</span>, <span class="hljs-string">'test'</span>];
</code></pre>
<p>Even other arrays:</p>
<pre><code class="lang-php">$list = [<span class="hljs-number">1</span>, [<span class="hljs-number">2</span>, <span class="hljs-string">'test'</span>]];
</code></pre>
<p>You can access the element in an array using this notation:</p>
<pre><code class="lang-php">$list = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>];
$list[<span class="hljs-number">0</span>]; <span class="hljs-comment">//'a' --the index starts at 0</span>
$list[<span class="hljs-number">1</span>]; <span class="hljs-comment">//'b'</span>
</code></pre>
<p>Once an array is created, you can append values to it in this way:</p>
<pre><code class="lang-php">$list = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>];
$list[] = <span class="hljs-string">'c'</span>;

<span class="hljs-comment">/*
$list == [
  "a",
  "b",
  "c",
]
*/</span>
</code></pre>
<p>You can use <code>array_unshift()</code> to add the item at the beginning of the array instead:</p>
<pre><code class="lang-php">$list = [<span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>];
array_unshift($list, <span class="hljs-string">'a'</span>);

<span class="hljs-comment">/*
$list == [
  "a",
  "b",
  "c",
]
*/</span>
</code></pre>
<p>Count how many items are in an array using the built-in <code>count()</code> function:</p>
<pre><code class="lang-php">$list = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>];

count($list); <span class="hljs-comment">//2</span>
</code></pre>
<p>Check if an array contains an item using the <code>in_array()</code> built-in function:</p>
<pre><code class="lang-php">$list = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>];

in_array(<span class="hljs-string">'b'</span>, $list); <span class="hljs-comment">//true</span>
</code></pre>
<p>If in addition to confirming existence, you need the index, use <code>array_search()</code>:</p>
<pre><code class="lang-php">$list = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>];

array_search(<span class="hljs-string">'b'</span>, $list) <span class="hljs-comment">//1</span>
</code></pre>
<h3 id="heading-useful-functions-for-arrays-in-php">Useful Functions for Arrays in PHP</h3>
<p>As with strings and numbers, PHP provides lots of very useful functions for arrays. We’ve seen <code>count()</code>, <code>in_array()</code>, <code>array_search()</code> – let’s see some more:</p>
<ul>
<li><code>is_array()</code> to check if a variable is an array</li>
<li><code>array_unique()</code> to remove duplicate values from an array</li>
<li><code>array_search()</code> to search a value in the array and return the key</li>
<li><code>array_reverse()</code> to reverse an array</li>
<li><code>array_reduce()</code> to reduce an array to a single value using a callback function</li>
<li><code>array_map()</code> to apply a callback function to each item in the array. Typically used to create a new array by modifying the values of an existing array, without altering it.</li>
<li><code>array_filter()</code> to filter an array to a single value using a callback function</li>
<li><code>max()</code> to get the maximum value contained in the array</li>
<li><code>min()</code> to get the minimum value contained in the array</li>
<li><code>array_rand()</code> to get a random item from the array</li>
<li><code>array_count_values()</code> to count all the values in the array</li>
<li><code>implode()</code> to turn an array into a string</li>
<li><code>array_pop()</code> to remove the last item of the array and return its value</li>
<li><code>array_shift()</code> same as <code>array_pop()</code> but removes the first item instead of the last</li>
<li><code>sort()</code> to sort an array</li>
<li><code>rsort()</code> to sort an array in reverse order</li>
<li><code>array_walk()</code> similarly to <code>array_map()</code> does something for every item in the array, but in addition it can change values in the existing array</li>
</ul>
<h3 id="heading-how-to-use-associative-arrays-in-php">How to Use Associative Arrays in PHP</h3>
<p>So far we’ve used arrays with an incremental, numeric index: 0, 1, 2…</p>
<p>You can also use arrays with named indexes (keys), and we call them associative arrays:</p>
<pre><code class="lang-php">$list = [<span class="hljs-string">'first'</span> =&gt; <span class="hljs-string">'a'</span>, <span class="hljs-string">'second'</span> =&gt; <span class="hljs-string">'b'</span>];

$list[<span class="hljs-string">'first'</span>] <span class="hljs-comment">//'a'</span>
$list[<span class="hljs-string">'second'</span>] <span class="hljs-comment">//'b'</span>
</code></pre>
<p>We have some functions that are especially useful for associative arrays:</p>
<ul>
<li><code>array_key_exists()</code> to check if a key exists in the array</li>
<li><code>array_keys()</code> to get all the keys from the array</li>
<li><code>array_values()</code> to get all the values from the array</li>
<li><code>asort()</code> to sort an associative array by value</li>
<li><code>arsort()</code> to sort an associative array in descending order by value</li>
<li><code>ksort()</code> to sort an associative array by key</li>
<li><code>krsort()</code> to sort an associative array in descending order by key</li>
</ul>
<p>You can see all array-related functions <a target="_blank" href="https://www.php.net/manual/en/ref.array.php">here</a>.</p>
<h2 id="heading-how-conditionals-work-in-php">How Conditionals Work in PHP</h2>
<p>I previously introduced comparison operators: <code>&lt;</code>, <code>&gt;</code>, <code>&lt;=</code>, <code>&gt;=</code>, <code>==</code>, <code>===</code> , <code>!=</code>, <code>!==</code>... and so on.</p>
<p>Those operators are going to be super useful for one thing: <strong>conditionals</strong>.</p>
<p>Conditionals are the first control structure we see.</p>
<p>We can decide to do something, or something else, based on a comparison.</p>
<p>For example:</p>
<pre><code class="lang-php">$age = <span class="hljs-number">17</span>;

<span class="hljs-keyword">if</span> ($age &gt; <span class="hljs-number">18</span>) {
  <span class="hljs-keyword">echo</span> <span class="hljs-string">'You can enter the pub'</span>;
}
</code></pre>
<p>The code inside the parentheses only executes if the condition evaluates to <code>true</code>.</p>
<p>Use <code>else</code> to do something <em>else</em> in case the condition is <code>false</code>:</p>
<pre><code class="lang-php">$age = <span class="hljs-number">17</span>;

<span class="hljs-keyword">if</span> ($age &gt; <span class="hljs-number">18</span>) {
  <span class="hljs-keyword">echo</span> <span class="hljs-string">'You can enter the pub'</span>;
} <span class="hljs-keyword">else</span> {
  <span class="hljs-keyword">echo</span> <span class="hljs-string">'You cannot enter the pub'</span>;
}
</code></pre>
<p>NOTE: I used <code>cannot</code> instead of <code>can't</code> because the single quote would terminate my string before it should. In this case you could escape the <code>'</code> in this way: <code>echo 'You can\'t enter the pub';</code></p>
<p>You can have multiple <code>if</code> statements chained using <code>elseif</code>:</p>
<pre><code class="lang-php">$age = <span class="hljs-number">17</span>;

<span class="hljs-keyword">if</span> ($age &gt; <span class="hljs-number">20</span>) {
  <span class="hljs-keyword">echo</span> <span class="hljs-string">'You are 20+'</span>;
} <span class="hljs-keyword">elseif</span> ($age &gt; <span class="hljs-number">18</span>) {
  <span class="hljs-keyword">echo</span> <span class="hljs-string">'You are 18+'</span>;
} <span class="hljs-keyword">else</span> {
  <span class="hljs-keyword">echo</span> <span class="hljs-string">'You are &lt;18'</span>;
}
</code></pre>
<p>In addition to <code>if</code>, we have the <code>switch</code> statement.</p>
<p>We use this when we have a variable that could have a few different values, and we don’t have to have a long if / elseif block:</p>
<pre><code class="lang-php">$age = <span class="hljs-number">17</span>

<span class="hljs-keyword">switch</span>($age) {
  <span class="hljs-keyword">case</span> <span class="hljs-number">15</span>:
        <span class="hljs-keyword">echo</span> <span class="hljs-string">'You are 15'</span>;
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-number">16</span>:
        <span class="hljs-keyword">echo</span> <span class="hljs-string">'You are 16'</span>;
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-number">17</span>:
        <span class="hljs-keyword">echo</span> <span class="hljs-string">'You are 17'</span>;
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-number">18</span>:
        <span class="hljs-keyword">echo</span> <span class="hljs-string">'You are 18'</span>;
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">default</span>:
    <span class="hljs-keyword">echo</span> <span class="hljs-string">"You are <span class="hljs-subst">$age</span>"</span>;
}
</code></pre>
<p>I know the example does not have any logic, but I think it can help you understand how <code>switch</code> works.</p>
<p>The <code>break;</code> statement after each case is essential. If you don’t add that and the age is 17, you’d see this:</p>
<pre><code class="lang-php">You are <span class="hljs-number">17</span>
You are <span class="hljs-number">18</span>
You are <span class="hljs-number">17</span>
</code></pre>
<p>Instead of just this:</p>
<pre><code class="lang-php">You are <span class="hljs-number">17</span>
</code></pre>
<p>as you’d expect.</p>
<h2 id="heading-how-loops-work-in-php">How Loops Work in PHP</h2>
<p>Loops are another super useful control structure.</p>
<p>We have a few different kinds of loops in PHP: <code>while</code>, <code>do while</code>, <code>for</code>, and <code>foreach</code>.</p>
<p>Let’s see them all!</p>
<h3 id="heading-how-to-use-a-while-loop-in-php">How to Use a <code>while</code> loop in PHP</h3>
<p>A <code>while</code> loop is the simplest one. It keeps iterating while the condition evaluates to <code>true</code>:</p>
<pre><code class="lang-php"><span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) {
  <span class="hljs-keyword">echo</span> <span class="hljs-string">'looping'</span>;
}
</code></pre>
<p>This would be an infinite loop, which is why we use variables and comparisons:</p>
<pre><code class="lang-php">$counter = <span class="hljs-number">0</span>;

<span class="hljs-keyword">while</span> ($counter &lt; <span class="hljs-number">10</span>) {
  <span class="hljs-keyword">echo</span> $counter;
  $counter++;
}
</code></pre>
<h3 id="heading-how-to-use-a-do-while-loop-in-php">How to Use a <code>do while</code> loop in PHP</h3>
<p><code>do while</code> is similar, but slightly different in how the first iteration is performed:</p>
<pre><code class="lang-php">$counter = <span class="hljs-number">0</span>;

<span class="hljs-keyword">do</span> {
  <span class="hljs-keyword">echo</span> $counter;
  $counter++;
} <span class="hljs-keyword">while</span> ($counter &lt; <span class="hljs-number">10</span>);
</code></pre>
<p>In the <code>do while</code> loop, first we do the first iteration, <em>then</em> we check the condition.</p>
<p>In the <code>while</code> loop, <em>first</em> we check the condition, then we do the iteration.</p>
<p>Do a simple test by setting <code>$counter</code> to 15 in the above examples, and see what happens.</p>
<p>You'll want to choose one kind of loop, or the other, depending on your use case.</p>
<h3 id="heading-how-to-use-a-foreach-loop-in-php">How to Use a <code>foreach</code> Loop in PHP</h3>
<p>You can use the <code>foreach</code> loop to easily iterate over an array:</p>
<pre><code class="lang-php">$list = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>];

<span class="hljs-keyword">foreach</span> ($list <span class="hljs-keyword">as</span> $value) {
  <span class="hljs-keyword">echo</span> $value;
}
</code></pre>
<p>You can also get the value of the index (or key in an associative array) in this way:</p>
<pre><code class="lang-php">$list = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>];

<span class="hljs-keyword">foreach</span> ($list <span class="hljs-keyword">as</span> $key =&gt; $value) {
  <span class="hljs-keyword">echo</span> $key;
}
</code></pre>
<h3 id="heading-how-to-use-a-for-loop-in-php">How to Use a <code>for</code> Loop in PHP</h3>
<p>The <code>for</code> loop is similar to while, but instead of defining the variable used in the conditional before the loop, and instead of incrementing the index variable manually, it’s all done in the first line:</p>
<pre><code class="lang-php"><span class="hljs-keyword">for</span> ($i = <span class="hljs-number">0</span>; $i &lt; <span class="hljs-number">10</span>; $i++) {
  <span class="hljs-keyword">echo</span> $i;
}

<span class="hljs-comment">//result: 0123456789</span>
</code></pre>
<p>You can use the for loop to iterate over an array in this way:</p>
<pre><code class="lang-php">$list = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>];

<span class="hljs-keyword">for</span> ($i = <span class="hljs-number">0</span>; $i &lt; count($list); $i++) {
  <span class="hljs-keyword">echo</span> $list[$i];
}

<span class="hljs-comment">//result: abc</span>
</code></pre>
<h3 id="heading-how-to-use-the-break-and-continue-statements-in-php">How to Use the <code>break</code> and <code>continue</code> Statements in PHP</h3>
<p>In many cases you want the ability to stop a loop on demand.</p>
<p>For example you want to stop a <code>for</code> loop when the value of the variable in the array is <code>'b'</code>:</p>
<pre><code class="lang-php">$list = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>];

<span class="hljs-keyword">for</span> ($i = <span class="hljs-number">0</span>; $i &lt; count($list); $i++) {
    <span class="hljs-keyword">if</span> ($list[$i] == <span class="hljs-string">'b'</span>) {
    <span class="hljs-keyword">break</span>;
  }
  <span class="hljs-keyword">echo</span> $list[$i];
}

<span class="hljs-comment">//result: a</span>
</code></pre>
<p>This makes the loop completely stop at that point, and the program execution continues at the next instruction after the loop.</p>
<p>If you just want to skip the current loop iteration and keep looking, use <code>continue</code> instead:</p>
<pre><code class="lang-php">$list = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>];

<span class="hljs-keyword">for</span> ($i = <span class="hljs-number">0</span>; $i &lt; count($list); $i++) {
    <span class="hljs-keyword">if</span> ($list[$i] == <span class="hljs-string">'b'</span>) {
    <span class="hljs-keyword">continue</span>;
  }
  <span class="hljs-keyword">echo</span> $list[$i];
}

<span class="hljs-comment">//result: ac</span>
</code></pre>
<h2 id="heading-how-functions-work-in-php">How Functions Work in PHP</h2>
<p>Functions are one of the most important concepts in programming.</p>
<p>You can use functions to group together multiple instructions or multiple lines of code, and give them a name.</p>
<p>For example you can make a function that sends an email. Let’s call it <code>sendEmail</code>, and we'll define it like this:</p>
<pre><code class="lang-php"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sendEmail</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">//send an email</span>
}
</code></pre>
<p>And you can <em>call it</em> anywhere else by using this syntax:</p>
<pre><code class="lang-php">sendEmail();
</code></pre>
<p>You can also pass arguments to a function. For example when you send an email, you want to send it to someone – so you add the email as the first argument:</p>
<pre><code class="lang-php">sendEmail(<span class="hljs-string">'test@test.com'</span>);
</code></pre>
<p>Inside the function definition we get this parameter in this way (we call them <em>parameters</em> inside the function definition, and <em>arguments</em> when we call the function):</p>
<pre><code class="lang-php"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sendEmail</span>(<span class="hljs-params">$to</span>) </span>{
  <span class="hljs-keyword">echo</span> <span class="hljs-string">"send an email to <span class="hljs-subst">$to</span>"</span>;
}
</code></pre>
<p>You can send multiple arguments by separating them with commas:</p>
<pre><code class="lang-php">sendEmail(<span class="hljs-string">'test@test.com'</span>, <span class="hljs-string">'subject'</span>, <span class="hljs-string">'body of the email'</span>);
</code></pre>
<p>And we can get those parameters in the order they were defined:</p>
<pre><code class="lang-php"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sendEmail</span>(<span class="hljs-params">$to, $subject, $body</span>) </span>{
  <span class="hljs-comment">//...</span>
}
</code></pre>
<p>We can <strong>optionally</strong> set the type of parameters:</p>
<pre><code class="lang-php"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sendEmail</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> $to, <span class="hljs-keyword">string</span> $subject, <span class="hljs-keyword">string</span> $body</span>) </span>{
  <span class="hljs-comment">//...</span>
}
</code></pre>
<p>Parameters can have a default value, so if they are omitted we can still have a value for them:</p>
<pre><code class="lang-php"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sendEmail</span>(<span class="hljs-params">$to, $subject = <span class="hljs-string">'test'</span>, $body = <span class="hljs-string">'test'</span></span>) </span>{
  <span class="hljs-comment">//...</span>
}

sendEmail(<span class="hljs-string">'test@test.com'</span>)
</code></pre>
<p>A function can return a value. Only one value can be returned from a function, not more than one. You do that using the <code>return</code> keyword. If omitted, the function returns <code>null</code>.</p>
<p>The returned value is super useful as it tells you the result of the work done in the function, and lets you use its result after calling it:</p>
<pre><code class="lang-php"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sendEmail</span>(<span class="hljs-params">$to</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
}

$success = sendEmail(<span class="hljs-string">'test@test.com'</span>);

<span class="hljs-keyword">if</span> ($success) {
  <span class="hljs-keyword">echo</span> <span class="hljs-string">'email sent successfully'</span>;
} <span class="hljs-keyword">else</span> {
  <span class="hljs-keyword">echo</span> <span class="hljs-string">'error sending the email'</span>;
}
</code></pre>
<p>We can <strong>optionally</strong> set the return type of a function using this syntax:</p>
<pre><code class="lang-php"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sendEmail</span>(<span class="hljs-params">$to</span>): <span class="hljs-title">bool</span> </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
}
</code></pre>
<p>When you define a variable inside a function, that variable is <strong>local</strong> to the function, which means it’s not visible from outside. When the function ends, it just stops existing:</p>
<pre><code class="lang-php"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sendEmail</span>(<span class="hljs-params">$to</span>) </span>{
    $test = <span class="hljs-string">'a'</span>;
}

var_dump($test); <span class="hljs-comment">//PHP Warning:  Undefined variable $test</span>
</code></pre>
<p>Variables defined outside of the function are <strong>not</strong> accessible inside the function.</p>
<p>This enforces a good programming practice as we can be sure the function does not modify external variables and cause “side effects”.</p>
<p>Instead you return a value from the function, and the outside code that calls the function will take responsibility for updating the outside variable.</p>
<p>Like this:</p>
<pre><code class="lang-php">$character = <span class="hljs-string">'a'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">test</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">'b'</span>;
}

$character = test();
</code></pre>
<p>You can pass the value of a variable by passing it as an argument to the function:</p>
<pre><code class="lang-php">$character = <span class="hljs-string">'a'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">test</span>(<span class="hljs-params">$c</span>) </span>{
  <span class="hljs-keyword">echo</span> $c;
}

test($character);
</code></pre>
<p>But you can’t modify that value from within the function.</p>
<p>It’s <strong>passed by value</strong>, which means the function receives a copy of it, not the reference to the original variable.</p>
<p>That is still possible using this syntax (notice I used <code>&amp;</code> in the parameter definition):</p>
<pre><code class="lang-php">$character = <span class="hljs-string">'a'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">test</span>(<span class="hljs-params">&amp;$c</span>) </span>{
  $c = <span class="hljs-string">'b'</span>;
}

test($character);

<span class="hljs-keyword">echo</span> $character; <span class="hljs-comment">//'b'</span>
</code></pre>
<p>The functions we've defined so far are <strong>named functions</strong>.</p>
<p>They have a name.</p>
<p>We also have <strong>anonymous functions</strong>, which can be useful in a lot of cases.</p>
<p>They don’t have a name, per se, but they are assigned to a variable. To call them, you invoke the variable with parentheses at the end:</p>
<pre><code class="lang-php">$myfunction = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">//do something here</span>
};

$myfunction()
</code></pre>
<p>Note that you need a semicolon after the function definition, but then they work like named functions for return values and parameters.</p>
<p>Interestingly, they offer a way to access a variable defined outside the function through <code>use()</code>:</p>
<pre><code class="lang-php">$test = <span class="hljs-string">'test'</span>;

$myfunction = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) <span class="hljs-title">use</span> (<span class="hljs-params">$test</span>) </span>{
  <span class="hljs-keyword">echo</span> $test;
  <span class="hljs-keyword">return</span> <span class="hljs-string">'ok'</span>;
};

$myfunction()
</code></pre>
<p>Another kind of function is an <strong>arrow function</strong>.</p>
<p>An arrow function is an anonymous function that’s just one expression (one line), and implicitly returns the value of that expression.</p>
<p>You define it in this way:</p>
<pre><code class="lang-php"><span class="hljs-function"><span class="hljs-keyword">fn</span> (<span class="hljs-params">arguments</span>) =&gt; <span class="hljs-title">expression</span></span>;
</code></pre>
<p>Here’s an example:</p>
<pre><code class="lang-php">$printTest = <span class="hljs-function"><span class="hljs-keyword">fn</span>(<span class="hljs-params"></span>) =&gt; '<span class="hljs-title">test</span>'</span>;

$printTest(); <span class="hljs-comment">//'test'</span>
</code></pre>
<p>You can pass parameters to an arrow function:</p>
<pre><code class="lang-php">$multiply = <span class="hljs-function"><span class="hljs-keyword">fn</span>(<span class="hljs-params">$a, $b</span>) =&gt; $<span class="hljs-title">a</span> * $<span class="hljs-title">b</span></span>;

$multiply(<span class="hljs-number">2</span>, <span class="hljs-number">4</span>) <span class="hljs-comment">//8</span>
</code></pre>
<p>Note that as the next example shows, arrow functions have automatic access to the variables of the enclosing scope, without the need of <code>use()</code>.</p>
<pre><code class="lang-php">$a = <span class="hljs-number">2</span>;
$b = <span class="hljs-number">4</span>;

$multiply = <span class="hljs-function"><span class="hljs-keyword">fn</span>(<span class="hljs-params"></span>) =&gt; $<span class="hljs-title">a</span> * $<span class="hljs-title">b</span></span>;

$multiply()
</code></pre>
<p>Arrow functions are super useful when you need to pass a callback function. We’ll see how to use them to perform some array operations later.</p>
<p>So we have in total 3 kinds of functions: <strong>named functions</strong>, <strong>anonymous functions</strong>, and <strong>arrow functions</strong>.</p>
<p>Each of them has its place, and you’ll learn how to use them properly over time, with practice.</p>
<h2 id="heading-how-to-loop-through-arrays-with-map-filter-and-reduce-in-php">How to Loop Through Arrays with <code>map()</code>, <code>filter()</code>, and <code>reduce()</code> in PHP</h2>
<p>Another important set of looping structures, often used in functional programming, is the set of <code>array_map()</code> / <code>array_filter()</code> / <code>array_reduce()</code>.</p>
<p>Those 3 built-in PHP functions take an array, and a callback function that in each iteration takes each item in the array.</p>
<p><code>array_map()</code> returns a new array that contains the result of running the callback function on each item in the array:</p>
<pre><code class="lang-php">$numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];
$doubles = array_map(<span class="hljs-function"><span class="hljs-keyword">fn</span>(<span class="hljs-params">$value</span>) =&gt; $<span class="hljs-title">value</span> * 2, $<span class="hljs-title">numbers</span>)</span>;

<span class="hljs-comment">//$doubles is now [2, 4, 6, 8]</span>
</code></pre>
<p><code>array_filter()</code> generates a new array by only getting the items whose callback function returns <code>true</code>:</p>
<pre><code class="lang-php">$numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];
$even = array_filter($numbers, <span class="hljs-function"><span class="hljs-keyword">fn</span>(<span class="hljs-params">$value</span>) =&gt; $<span class="hljs-title">value</span> % 2 === 0)

//$<span class="hljs-title">even</span> <span class="hljs-title">is</span> <span class="hljs-title">now</span> [2, 4]</span>
</code></pre>
<p><code>array_reduce()</code> is used to <em>reduce</em> an array to a single value.</p>
<p>For example we can use it to multiply all items in an array:</p>
<pre><code class="lang-php">$numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];

$result = array_reduce($numbers, <span class="hljs-function"><span class="hljs-keyword">fn</span>(<span class="hljs-params">$carry, $value</span>) =&gt; $<span class="hljs-title">carry</span> * $<span class="hljs-title">value</span>, 1)</span>
</code></pre>
<p>Notice the last parameter – it’s the initial value. If you omit that, the default value is <code>0</code> but that would not work for our multiplication example.</p>
<p>Note that in <code>array_map()</code> the order of the arguments is reversed. First you have the callback function and then the array. This is because we can pass multiple arrays using commas (<code>array_map(fn($value) =&gt; $value * 2, $numbers, $otherNumbers, $anotherArray);</code>). Ideally we’d like more consistency, but that’s what it is.</p>
<h2 id="heading-object-oriented-programming-in-php">Object Oriented Programming in PHP</h2>
<p>Let’s now jump head first into a big topic: object-oriented programming with PHP.</p>
<p>Object-oriented programming lets you create useful abstractions and make your code simpler to understand and manage.</p>
<h3 id="heading-how-to-use-classes-and-objects-in-php">How to Use Classes and Objects in PHP</h3>
<p>To start with, you have classes and objects.</p>
<p>A class is a blueprint, or type, of object.</p>
<p>For example you have the class <code>Dog</code>, defined in this way:</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> </span>{

}
</code></pre>
<p>Note that the class must be defined in uppercase.</p>
<p>Then you can create objects from this class – specific, individual dogs.</p>
<p>An object is assigned to a variable, and it’s instantiated using the <code>new Classname()</code> syntax:</p>
<pre><code class="lang-php">$roger = <span class="hljs-keyword">new</span> Dog();
</code></pre>
<p>You can create multiple objects from the same class, by assigning each object to a different variable:</p>
<pre><code class="lang-php">$roger = <span class="hljs-keyword">new</span> Dog();
$syd = <span class="hljs-keyword">new</span> Dog();
</code></pre>
<h3 id="heading-how-to-use-properties-in-php">How to Use Properties in PHP</h3>
<p>Those objects will all share the same characteristics defined by the class. But once they are instantiated, they will have a life of their own.</p>
<p>For example, a Dog has a name, an age, and a fur color.</p>
<p>So we can define those as properties in the class:</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> </span>{
  <span class="hljs-keyword">public</span> $name;
  <span class="hljs-keyword">public</span> $age;
  <span class="hljs-keyword">public</span> $color;
}
</code></pre>
<p>They work like variables, but they are attached to the object, once it's instantiated from the class. The <code>public</code> keyword is the <em>access modifier</em> and sets the property to be publicly accessible.</p>
<p>You can assign values to those properties in this way:</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> </span>{
  <span class="hljs-keyword">public</span> $name;
  <span class="hljs-keyword">public</span> $age;
  <span class="hljs-keyword">public</span> $color;
}

$roger = <span class="hljs-keyword">new</span> Dog();

$roger-&gt;name = <span class="hljs-string">'Roger'</span>;
$roger-&gt;age = <span class="hljs-number">10</span>;
$roger-&gt;color = <span class="hljs-string">'gray'</span>;

var_dump($roger);

<span class="hljs-comment">/*
object(Dog)#1 (3) {
  ["name"]=&gt; string(5) "Roger"
    ["age"]=&gt; int(10)
    ["color"]=&gt; string(4) "gray"
}
*/</span>
</code></pre>
<p>Notice that the property is defined as <code>public</code>.</p>
<p>That is called an access modifier. You can use two other kinds of access modifiers: <code>private</code> and <code>protected</code>. Private makes the property inaccessible from outside the object. Only methods defined inside the object can access it.</p>
<p>We’ll see more about protected when we’ll talk about inheritance.</p>
<h3 id="heading-how-to-use-methods-in-php">How to Use Methods in PHP</h3>
<p>Did I say method? What is a method?</p>
<p>A method is a function defined inside the class, and it’s defined in this way:</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> </span>{
  <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bark</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">echo</span> <span class="hljs-string">'woof!'</span>;
  }
}
</code></pre>
<p>Methods are very useful to attach a behavior to an object. In this case we can make a dog bark.</p>
<p>Notice that I use the <code>public</code> keyword. That’s to say that you can invoke a method from outside the class. Like for properties, you can mark methods as <code>private</code> too, or <code>protected</code>, to restrict their access.</p>
<p>You invoke a method on the object instance like this:</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> </span>{
  <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bark</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">echo</span> <span class="hljs-string">'woof!'</span>;
  }
}

$roger = <span class="hljs-keyword">new</span> Dog();

$roger-&gt;bark();
</code></pre>
<p>A method, just like a function, can define parameters and a return value, too.</p>
<p>Inside a method we can access the object’s properties using the special built-in <code>$this</code> variable, which, when referenced inside a method, points to the current object instance:</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> </span>{
  <span class="hljs-keyword">public</span> $name;

  <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bark</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">echo</span> <span class="hljs-keyword">$this</span>-&gt;name . <span class="hljs-string">' barked!'</span>;
  }
}

$roger = <span class="hljs-keyword">new</span> Dog();
$roger-&gt;name = <span class="hljs-string">'Roger'</span>;
$roger-&gt;bark();
</code></pre>
<p>Notice I used <code>$this-&gt;name</code> to set and access the <code>$name</code> property, and not <code>$this-&gt;$name</code>.</p>
<h3 id="heading-how-to-use-the-constructor-method-in-php">How to Use the Constructor Method in PHP</h3>
<p>A special kind of method named <code>__construct()</code> is called a <strong>constructor</strong>.</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> </span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params"></span>) </span>{

  }
}
</code></pre>
<p>You use this method to initialize the properties of an object when you create it, as it’s automatically invoked when calling <code>new Classname()</code>.</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> </span>{
  <span class="hljs-keyword">public</span> $name;

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">$name</span>) </span>{
        <span class="hljs-keyword">$this</span>-&gt;name = $name;
  }

  <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bark</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">echo</span> <span class="hljs-keyword">$this</span>-&gt;name . <span class="hljs-string">' barked!'</span>;
  }
}

$roger = <span class="hljs-keyword">new</span> Dog(<span class="hljs-string">'Roger'</span>);
$roger-&gt;bark();
</code></pre>
<p>This is such a common thing that PHP (starting in PHP 8) includes something called <strong>constructor promotion</strong> where it automatically does this thing:</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> </span>{
  <span class="hljs-keyword">public</span> $name;

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">$name</span>) </span>{
        <span class="hljs-keyword">$this</span>-&gt;name = $name;
  }

  <span class="hljs-comment">//...</span>
</code></pre>
<p>By using the access modifier, the assignment from the parameter of the constructor to the local variable happens automatically:</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> </span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params"><span class="hljs-keyword">public</span> $name</span>) </span>{
  }

  <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bark</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">echo</span> <span class="hljs-keyword">$this</span>-&gt;name . <span class="hljs-string">' barked!'</span>;
  }
}

$roger = <span class="hljs-keyword">new</span> Dog(<span class="hljs-string">'Roger'</span>);
$roger-&gt;name; <span class="hljs-comment">//'Roger'</span>
$roger-&gt;bark(); <span class="hljs-comment">//'Roger barked!'</span>
</code></pre>
<p>Properties can be <strong>typed</strong>.</p>
<p>You can require the name to be a string using <code>public string $name</code>:</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> </span>{
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $name;

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">$name</span>) </span>{
        <span class="hljs-keyword">$this</span>-&gt;name = $name;
  }

  <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bark</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">echo</span> <span class="hljs-keyword">$this</span>-&gt;name . <span class="hljs-string">' barked!'</span>;
  }
}

$roger = <span class="hljs-keyword">new</span> Dog(<span class="hljs-string">'Roger'</span>);
$roger-&gt;name; <span class="hljs-comment">//'Roger'</span>
$roger-&gt;bark(); <span class="hljs-comment">//'Roger barked!'</span>
</code></pre>
<p>Now all works fine in this example, but try changing that to <code>public int $name</code> to require it to be an integer.</p>
<p>PHP will raise an error if you initialize <code>$name</code> with a string:</p>
<pre><code><span class="hljs-built_in">TypeError</span>: Dog::__construct():
Argument #<span class="hljs-number">1</span> ($name) must be <span class="hljs-keyword">of</span> type int,
string given on line <span class="hljs-number">14</span>
</code></pre><p>Interesting, right?</p>
<p>We can enforce properties to have a specific type between <code>string</code>, <code>int</code>, <code>float</code>, <code>string</code>, <code>object</code>, <code>array</code>, <code>bool</code> and <a target="_blank" href="https://www.php.net/manual/en/language.types.declarations.php">others</a>.</p>
<h3 id="heading-what-is-inheritance-in-php">What is Inheritance in PHP?</h3>
<p>The fun in object oriented programming starts when we allow classes to inherit properties and methods from other classes.</p>
<p>Suppose you have an <code>Animal</code> class:</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{

}
</code></pre>
<p>Every animal has an age, and every animal can eat. So we add an <code>age</code> property and an <code>eat()</code> method:</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{
  <span class="hljs-keyword">public</span> $age;

  <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">eat</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">echo</span> <span class="hljs-string">'the animal is eating'</span>;
  }
}
</code></pre>
<p>A dog is an animal and has an age and can eat too, so the <code>Dog</code> class – instead of reimplementing the same things we have in <code>Animal</code> – can extend that class:</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>{

}
</code></pre>
<p>We can now instantiate a new object of class <code>Dog</code> and we have access to the properties and methods defined in <code>Animal</code>:</p>
<pre><code class="lang-php">$roger = <span class="hljs-keyword">new</span> Dog();
$roger-&gt;eat();
</code></pre>
<p>In this case we call Dog the <strong>child class</strong> and Animal the <strong>parent class</strong>.</p>
<p>Inside the child class we can use <code>$this</code> to reference any property or method defined in the parent, as if they were defined inside the child class.</p>
<p>It’s worth noting that while we can access the parent’s properties and methods from the child, we can’t do the reverse.</p>
<p>The parent class knows nothing about the child class.</p>
<h3 id="heading-protected-properties-and-methods-in-php"><code>protected</code> Properties and Methods in PHP</h3>
<p>Now that we've introduced inheritance, we can discuss <code>protected</code>. We already saw how we can use the <code>public</code> access modifier to set properties and methods callable from outside of a class, by the <em>public.</em></p>
<p><code>private</code> properties and methods can only be accessed from within the class.</p>
<p><code>protected</code> properties and methods can be accessed from within the class and from child classes.</p>
<h3 id="heading-how-to-override-methods-in-php">How to Override Methods in PHP</h3>
<p>What happens if we have an <code>eat()</code> method in <code>Animal</code> and we want to customize it in <code>Dog</code>? We can <strong>override</strong> that method.</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{
  <span class="hljs-keyword">public</span> $age;

  <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">eat</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">echo</span> <span class="hljs-string">'the animal is eating'</span>;
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>{
  <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">eat</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">echo</span> <span class="hljs-string">'the dog is eating'</span>;
  }
}
</code></pre>
<p>Now any instance of <code>Dog</code> will use the <code>Dog</code>'s implementation of the <code>eat()</code> method.</p>
<h3 id="heading-static-properties-and-methods-in-php">Static Properties and Methods in PHP</h3>
<p>We’ve seen how to define properties and methods that belong <strong>to the instance of a class</strong>, an object.</p>
<p>Sometimes it’s useful to assign those to the class itself.</p>
<p>When this happens we call them <strong>static</strong>, and to reference or call them we don’t need to create an object from the class.</p>
<p>Let’s start with static properties. We define them with the <code>static</code> keyword:</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Utils</span> </span>{
  <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> $version = <span class="hljs-string">'1.0'</span>;
}
</code></pre>
<p>We reference them from inside the class using the keyword <code>self</code>, which points to the class:</p>
<pre><code class="lang-php"><span class="hljs-built_in">self</span>::$version;
</code></pre>
<p>and from outside the class using:</p>
<pre><code class="lang-php">
Utils::version
</code></pre>
<p>This is what happens for static methods:</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Utils</span> </span>{
  <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">version</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">'1.0'</span>;
  }
}
</code></pre>
<p>From the outside of the class we can call them in this way:</p>
<pre><code class="lang-php">Utils::version();
</code></pre>
<p>From inside the class, we can reference them using the <code>self</code> keyword, which refers to the current class:</p>
<pre><code class="lang-php"><span class="hljs-built_in">self</span>::version();
</code></pre>
<h3 id="heading-how-to-compare-objects-in-php">How to Compare Objects in PHP</h3>
<p>When we talked about operators I mentioned we have the <code>==</code> operator to check if two values are equal and <code>===</code> to check if they are identical.</p>
<p>Mainly the difference is that <code>==</code> checks the object content, for example the <code>'5'</code> string is equal to the number <code>5</code>, but it’s not identical to it.</p>
<p>When we use those operators to compare objects, <code>==</code> will check if the two objects have the same class and have the same values assigned to them.</p>
<p><code>===</code> on the other hand will check if they also refer to the same instance (object).</p>
<p>For example:</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> </span>{
  <span class="hljs-keyword">public</span> $name = <span class="hljs-string">'Good dog'</span>;
}

$roger = <span class="hljs-keyword">new</span> Dog();
$syd = <span class="hljs-keyword">new</span> Dog();

<span class="hljs-keyword">echo</span> $roger == $syd; <span class="hljs-comment">//true</span>

<span class="hljs-keyword">echo</span> $roger === $syd; <span class="hljs-comment">//false</span>
</code></pre>
<h3 id="heading-how-to-iterate-over-object-properties-in-php">How to Iterate over Object Properties in PHP</h3>
<p>You can loop over all the public properties in an object using a <code>foreach</code> loop, like this:</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> </span>{
  <span class="hljs-keyword">public</span> $name = <span class="hljs-string">'Good dog'</span>;
  <span class="hljs-keyword">public</span> $age = <span class="hljs-number">10</span>;
  <span class="hljs-keyword">public</span> $color = <span class="hljs-string">'gray'</span>;
}

$dog = <span class="hljs-keyword">new</span> Dog();

<span class="hljs-keyword">foreach</span> ($dog <span class="hljs-keyword">as</span> $key =&gt; $value) {
  <span class="hljs-keyword">echo</span> $key . <span class="hljs-string">': '</span> . $value . <span class="hljs-string">'&lt;br&gt;'</span>;
}
</code></pre>
<h3 id="heading-how-to-clone-objects-in-php">How to Clone Objects in PHP</h3>
<p>When you have an object, you can clone it using the <code>clone</code> keyword:</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> </span>{
  <span class="hljs-keyword">public</span> $name;
}

$roger = <span class="hljs-keyword">new</span> Dog();
$roger-&gt;name = <span class="hljs-string">'Roger'</span>;

$syd = <span class="hljs-keyword">clone</span> $roger;
</code></pre>
<p>This performs a <em>shallow clone</em>, which means that references to other variables will be copied as references – there will not a “recursive cloning” of them.</p>
<p>To do a <em>deep clone</em> you will need to do some more work.</p>
<h3 id="heading-what-are-magic-methods-in-php">What are Magic Methods in PHP?</h3>
<p>Magic methods are special methods that we define in classes to perform some behavior when something special happens.</p>
<p>For example when a property is set, or accessed, or when the object is cloned.</p>
<p>We’ve seen <code>__construct()</code> before.</p>
<p>That’s a magic method.</p>
<p>There are others. For example we can set a “cloned” boolean property to true when the object is cloned:</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> </span>{
  <span class="hljs-keyword">public</span> $name;

  <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__clone</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">$this</span>-&gt;cloned = <span class="hljs-literal">true</span>;
  }
}

$roger = <span class="hljs-keyword">new</span> Dog();
$roger-&gt;name = <span class="hljs-string">'Roger'</span>;

$syd = <span class="hljs-keyword">clone</span> $roger;
<span class="hljs-keyword">echo</span> $syd-&gt;cloned;
</code></pre>
<p>Other magic methods include <code>__call()</code>, <code>__get()</code>, <code>__set()</code>, <code>__isset()</code>, <code>__toString()</code> and others.</p>
<p>You can see the full list <a target="_blank" href="https://www.php.net/manual/en/language.oop5.magic.php">here</a></p>
<h2 id="heading-how-to-include-other-php-files">How to Include Other PHP Files</h2>
<p>We’re now done talking about the object oriented features of PHP.</p>
<p>Let’s now explore some other interesting topics!</p>
<p>Inside a PHP file you can include other PHP files. We have the following methods, all used for this use case, but they're all slightly different: <code>include</code>, <code>include_once</code>, <code>require</code>, and <code>require_once</code>.</p>
<p><code>include</code> loads the content of another PHP file, using a relative path.</p>
<p><code>require</code> does the same, but if there’s any error doing so, the program halts. <code>include</code> will only generate a warning.</p>
<p>You can decide to use one or the other depending on your use case. If you want your program to exit if it can’t import the file, use <code>require</code>.</p>
<p><code>include_once</code> and <code>require_once</code> do the same thing as their corresponding functions without <code>_once</code>, but they make sure the file is included/required only once during the execution of the program.</p>
<p>This is useful if, for example, you have multiple files loading some other file, and you typically want to avoid loading that more than once.</p>
<p>My rule of thumb is to never use <code>include</code> or <code>require</code> because you might load the same file twice. <code>include_once</code> and <code>require_once</code> help you avoid this problem.</p>
<p>Use <code>include_once</code> when you want to conditionally load a file, for example “load this file instead of that”. In all other cases, use <code>require_once</code>.</p>
<p>Here’s an example:</p>
<pre><code class="lang-php"><span class="hljs-keyword">require_once</span>(<span class="hljs-string">'test.php'</span>);

<span class="hljs-comment">//now we have access to the functions, classes</span>
<span class="hljs-comment">//and variables defined in the `test.php` file</span>
</code></pre>
<p>The above syntax includes the <code>test.php</code> file from the current folder, the file where this code is.</p>
<p>You can use relative paths:</p>
<pre><code class="lang-php"><span class="hljs-keyword">require_once</span>(<span class="hljs-string">'../test.php'</span>);
</code></pre>
<p>to include a file in the parent folder or to go in a subfolder:</p>
<pre><code class="lang-php"><span class="hljs-keyword">require_once</span>(<span class="hljs-string">'test/test.php'</span>);
</code></pre>
<p>You can use absolute paths:</p>
<pre><code class="lang-php"><span class="hljs-keyword">require_once</span>(<span class="hljs-string">'/var/www/test/file.php'</span>);
</code></pre>
<p>In modern PHP codebases that use a framework, files are generally loaded automatically so you’ll have less need to use the above functions.</p>
<h2 id="heading-useful-constants-functions-and-variables-for-filesystem-in-php">Useful Constants, Functions and Variables for Filesystem in PHP</h2>
<p>Speaking of paths, PHP offers you several utilities to help you work with paths.</p>
<p>You can get the full path of the current file using:</p>
<ul>
<li><code>__FILE__</code>, a <em>magic constant</em></li>
<li><code>$_SERVER['SCRIPT_FILENAME']</code> (more on <code>$_SERVER</code> later!)</li>
</ul>
<p>You can get the full path of the folder where the current file is using:</p>
<ul>
<li>the <a target="_blank" href="https://www.php.net/manual/en/function.getcwd.php"><code>getcwd()</code></a> built-in function</li>
<li><code>__DIR__</code>, another magic constant</li>
<li>combine <code>__FILE__</code> with <code>dirname()</code> to get the current folder full path: <code>dirname(__FILE__)</code></li>
<li>use <code>$_SERVER['DOCUMENT_ROOT']</code></li>
</ul>
<h2 id="heading-how-to-handle-errors-in-php">How to Handle Errors in PHP</h2>
<p>Every programmer makes errors. We’re humans, after all.</p>
<p>We might forget a semicolon. Or use the wrong variable name. Or pass the wrong argument to a function.</p>
<p>In PHP we have:</p>
<ul>
<li>Warnings</li>
<li>Notices</li>
<li>Errors</li>
</ul>
<p>The first two are minor errors, and they do not stop the program execution. PHP will print a message, and that’s it.</p>
<p>Errors terminate the execution of the program, and will print a message telling you why.</p>
<p>There are many different kinds of errors, like parse errors, runtime fatal errors, startup fatal errors, and more.</p>
<p>They’re all errors.</p>
<p>I said “PHP will print a message”, but.. where?</p>
<p>This depends on your configuration.</p>
<p>In development mode it’s common to log PHP errors directly into the Web page, but also in an error log.</p>
<p>You <em>want</em> to see those errors as early as possible, so you can fix them.</p>
<p>In production, on the other hand, you don’t want to show them in the Web page, but you still want to know about them.</p>
<p>So what do you do? You log them to the error log.</p>
<p>This is all decided in the PHP configuration.</p>
<p>We haven’t talked about this yet, but there’s a file in your server configuration that decides a lot of things about how PHP runs.</p>
<p>It’s called <code>php.ini</code>.</p>
<p>The exact location of this file depends on your setup.</p>
<p>To find out where is yours, the easiest way is to add this to a PHP file and run it in your browser:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
phpinfo();
<span class="hljs-meta">?&gt;</span>
</code></pre>
<p>You will then see the location under “Loaded Configuration File”:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-27_at_13.42.41.jpg" alt="Screen Shot 2022-06-27 at 13.42.41.jpg" width="600" height="400" loading="lazy"></p>
<p>In my case it’s <code>/Applications/MAMP/bin/php/php8.1.0/conf/php.ini</code>.</p>
<p>Note that the information generated by <code>phpinfo()</code> contains a lot of other useful information. Remember that.</p>
<p>Using MAMP you can open the MAMP application folder and open <code>bin/php</code>. Go in your specific PHP version (8.1.0 in my case) then go in <code>conf</code>. In there you’ll find the <code>php.ini</code> file:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-27_at_12.11.28.jpg" alt="Screen Shot 2022-06-27 at 12.11.28.jpg" width="600" height="400" loading="lazy"></p>
<p>Open that file in an editor.</p>
<p>It contains a really long list of settings, with a great inline documentation for each one.</p>
<p>We’re particularly interested in <code>display_errors</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-27_at_12.13.16.jpg" alt="Screen Shot 2022-06-27 at 12.13.16.jpg" width="600" height="400" loading="lazy"></p>
<p>In production you want its value to be <code>Off</code>, as the docs above it say.</p>
<p>The errors will not show up anymore in the website, but you will see them in the <code>php_error.log</code> file in the <code>logs</code> folder of MAMP in this case:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-27_at_12.16.01.jpg" alt="Screen Shot 2022-06-27 at 12.16.01.jpg" width="600" height="400" loading="lazy"></p>
<p>This file will be in a different folder depending on your setup.</p>
<p>You set this location in your <code>php.ini</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-27_at_12.17.12.jpg" alt="Screen Shot 2022-06-27 at 12.17.12.jpg" width="600" height="400" loading="lazy"></p>
<p>The error log will contain all the error messages your application generates:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-27_at_12.17.55.jpg" alt="Screen Shot 2022-06-27 at 12.17.55.jpg" width="600" height="400" loading="lazy"></p>
<p>You can add information to the error log by using the <a target="_blank" href="https://www.php.net/manual/en/function.error-log.php"><code>error_log()</code></a> function:</p>
<pre><code class="lang-php">error_log(<span class="hljs-string">'test'</span>);
</code></pre>
<p>It’s common to use a logger service for errors, like <a target="_blank" href="https://github.com/Seldaek/monolog">Monolog</a>.</p>
<h2 id="heading-how-to-handle-exceptions-in-php">How to Handle Exceptions in PHP</h2>
<p>Sometimes errors are unavoidable. Like if something completely unpredictable happens.</p>
<p>But many times, we can think ahead, and write code that can intercept an error, and do something sensible when this happens. Like showing a useful error message to the user, or trying a workaround.</p>
<p>We do so using <strong>exceptions</strong>.</p>
<p>Exceptions are used to make us, developers, aware of a problem.</p>
<p>We wrap some code that can potentially raise an exception into a <code>try</code> block, and we have a <code>catch</code> block right after that. That catch block will be executed if there’s an exception in the try block:</p>
<pre><code class="lang-php"><span class="hljs-keyword">try</span> {
  <span class="hljs-comment">//do something</span>
} <span class="hljs-keyword">catch</span> (<span class="hljs-built_in">Throwable</span> $e) {
  <span class="hljs-comment">//we can do something here if an exception happens</span>
}
</code></pre>
<p>Notice that we have an <code>Exception</code> object <code>$e</code> being passed to the <code>catch</code> block, and we can inspect that object to get more information about the exception, like this:</p>
<pre><code class="lang-php"><span class="hljs-keyword">try</span> {
  <span class="hljs-comment">//do something</span>
} <span class="hljs-keyword">catch</span> (<span class="hljs-built_in">Throwable</span> $e) {
  <span class="hljs-keyword">echo</span> $e-&gt;getMessage();
}
</code></pre>
<p>Let’s look at an example.</p>
<p>Let's say that by mistake I divide a number by zero:</p>
<pre><code class="lang-php"><span class="hljs-keyword">echo</span> <span class="hljs-number">1</span> / <span class="hljs-number">0</span>;
</code></pre>
<p>This will trigger a fatal error and the program is halted on that line:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-26_at_20.12.59.jpg" alt="Screen Shot 2022-06-26 at 20.12.59.jpg" width="600" height="400" loading="lazy"></p>
<p>Wrapping the operation in a try block and printing the error message in the catch block, the program ends successfully, telling me the problem:</p>
<pre><code class="lang-php"><span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">echo</span> <span class="hljs-number">1</span> / <span class="hljs-number">0</span>;
} <span class="hljs-keyword">catch</span> (<span class="hljs-built_in">Throwable</span> $e) {
  <span class="hljs-keyword">echo</span> $e-&gt;getMessage();
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-26_at_20.13.36.jpg" alt="Screen Shot 2022-06-26 at 20.13.36.jpg" width="600" height="400" loading="lazy"></p>
<p>Of course this is a simple example but you can see the benefit: I can intercept the issue.</p>
<p>Each exception has a different class. For example we can catch this as <a target="_blank" href="https://www.php.net/manual/en/class.divisionbyzeroerror.php"><code>DivisionByZeroError</code></a> and this lets me filter the possible problems and handle them differently.</p>
<p>I can have a catch-all for any throwable error at the end, like this:</p>
<pre><code class="lang-php"><span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">echo</span> <span class="hljs-number">1</span> / <span class="hljs-number">0</span>;
} <span class="hljs-keyword">catch</span> (<span class="hljs-built_in">DivisionByZeroError</span> $e) {
  <span class="hljs-keyword">echo</span> <span class="hljs-string">'Ooops I divided by zero!'</span>;
} <span class="hljs-keyword">catch</span> (<span class="hljs-built_in">Throwable</span> $e) {
  <span class="hljs-keyword">echo</span> $e-&gt;getMessage();
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-26_at_20.15.47.jpg" alt="Screen Shot 2022-06-26 at 20.15.47.jpg" width="600" height="400" loading="lazy"></p>
<p>And I can also append a <code>finally {}</code> block at the end of this try/catch structure to execute some code after the code is either executed successfully without problems, or there was a <em>catch</em>:</p>
<pre><code class="lang-php"><span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">echo</span> <span class="hljs-number">1</span> / <span class="hljs-number">0</span>;
} <span class="hljs-keyword">catch</span> (<span class="hljs-built_in">DivisionByZeroError</span> $e) {
  <span class="hljs-keyword">echo</span> <span class="hljs-string">'Ooops I divided by zero!'</span>;
} <span class="hljs-keyword">catch</span> (<span class="hljs-built_in">Throwable</span> $e) {
  <span class="hljs-keyword">echo</span> $e-&gt;getMessage();
} <span class="hljs-keyword">finally</span> {
  <span class="hljs-keyword">echo</span> <span class="hljs-string">' ...done!'</span>;
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-26_at_20.17.33.jpg" alt="Screen Shot 2022-06-26 at 20.17.33.jpg" width="600" height="400" loading="lazy"></p>
<p>You can use the <a target="_blank" href="https://www.php.net/manual/en/reserved.exceptions.php">built-in exceptions</a> provided by PHP but you can also create your own exceptions.</p>
<h2 id="heading-how-to-work-with-dates-in-php">How to Work with Dates in PHP</h2>
<p>Working with dates and times is very common in programming. Let’s see what PHP provides.</p>
<p>We can get the current timestamp (number of seconds since Jan 1 1970 00:00:00 GMT) using <a target="_blank" href="https://www.php.net/manual/en/function.time.php"><code>time()</code></a>:</p>
<pre><code class="lang-php">$timestamp = time();
</code></pre>
<p>When you have a timestamp you can format that as a date using <a target="_blank" href="https://www.php.net/manual/en/function.date.php"><code>date()</code></a>, in the format you prefer:</p>
<pre><code class="lang-php"><span class="hljs-keyword">echo</span> date(<span class="hljs-string">'Y-m-d'</span>, $timestamp);
</code></pre>
<p><code>Y</code> is the 4-digit representation of the year, <code>m</code> is the month number (with a leading zero) and <code>d</code> is the number of the day of the month, with a leading zero.</p>
<p>See the <a target="_blank" href="https://www.php.net/manual/en/datetime.format.php">full list of characters you can use to format the date here</a>.</p>
<p>We can convert any date into a timestamp using <a target="_blank" href="https://www.php.net/manual/en/function.strtotime.php"><code>strtotime()</code></a>, which takes a string with a textual representation of a date and converts it into the number of seconds since Jan 1 1970:</p>
<pre><code class="lang-php"><span class="hljs-keyword">echo</span> strtotime(<span class="hljs-string">'now'</span>);
<span class="hljs-keyword">echo</span> strtotime(<span class="hljs-string">'4 May 2020'</span>);
<span class="hljs-keyword">echo</span> strtotime(<span class="hljs-string">'+1 day'</span>);
<span class="hljs-keyword">echo</span> strtotime(<span class="hljs-string">'+1 month'</span>);
<span class="hljs-keyword">echo</span> strtotime(<span class="hljs-string">'last Sunday'</span>);
</code></pre>
<p>...it’s pretty flexible.</p>
<p>For dates, it’s common to use libraries that offer a lot more functionality than what the language can. A good option is <a target="_blank" href="https://carbon.nesbot.com">Carbon</a>.</p>
<h2 id="heading-how-to-use-constants-and-enums-in-php">How to Use Constants and Enums in PHP</h2>
<p>We can define constants in PHP using the <code>define()</code> built-in function:</p>
<pre><code class="lang-php">define(<span class="hljs-string">'TEST'</span>, <span class="hljs-string">'some value'</span>);
</code></pre>
<p>And then we can use <code>TEST</code> as if it was a variable, but without the <code>$</code> sign:</p>
<pre><code class="lang-php">define(<span class="hljs-string">'TEST'</span>, <span class="hljs-string">'some value'</span>);

<span class="hljs-keyword">echo</span> TEST;
</code></pre>
<p>We use uppercase identifiers as a convention for constants.</p>
<p>Interestingly, inside classes we can define constant properties using the <code>const</code> keyword:</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> </span>{
  <span class="hljs-keyword">const</span> BREED = <span class="hljs-string">'Siberian Husky'</span>;
}
</code></pre>
<p>By default they are <code>public</code> but we can mark them as <code>private</code> or <code>protected</code>:</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> </span>{
  <span class="hljs-keyword">private</span> <span class="hljs-keyword">const</span> BREED = <span class="hljs-string">'Siberian Husky'</span>;
}
</code></pre>
<p>Enums allow you to group constants under a common “root”. For example you want to have a <code>Status</code> enum that has 3 states: <code>EATING</code> <code>SLEEPING</code> <code>RUNNING</code>, the 3 states of a dog’s day.</p>
<p>So you have:</p>
<pre><code class="lang-php">enum Status {
  <span class="hljs-keyword">case</span> EATING;
  <span class="hljs-keyword">case</span> SLEEPING;
  <span class="hljs-keyword">case</span> RUNNING;
}
</code></pre>
<p>Now we can reference those constants in this way:</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> </span>{
  <span class="hljs-keyword">public</span> Status $status;
}

$dog = <span class="hljs-keyword">new</span> Dog();

$dog-&gt;status = Status::RUNNING;

<span class="hljs-keyword">if</span> ($dog-&gt;status == Status::SLEEPING) {
  <span class="hljs-comment">//...</span>
}
</code></pre>
<p>Enums are objects, they can have methods and lots more features than we can get into here in this short introduction.</p>
<h2 id="heading-how-to-use-php-as-a-web-app-development-platform">How to Use PHP as a Web App Development Platform</h2>
<p>PHP is a server-side language and it is typically used in two ways.</p>
<p>One is within an HTML page, so PHP is used to “add” stuff to the HTML which is manually defined in the <code>.php</code> file. This is a perfectly fine way to use PHP.</p>
<p>Another way considers PHP more like the engine that is responsible for generating an “application”. You don't write the HTML in a <code>.php</code> file, but instead you use a templating language to generate the HTML, and everything is managed by what we call the <strong>framework</strong>.</p>
<p>This is what happens when you use a modern framework like Laravel.</p>
<p>I would consider the first way a bit “out of fashion” these days, and if you’re just starting out you should know about those two different styles of using PHP. </p>
<p>But also consider using a framework like “easy mode” because frameworks give you tools to handle routing, tools to access data from a database, and they make it easier to build a more secure application. And they make it all faster to develop.</p>
<p>That said, we’re not going to talk about using frameworks in this handbook. But I will talk about the basic, fundamental building blocks of PHP. They are essentials that any PHP developer must know.</p>
<p>Just know that “in the real world” you might use your favorite framework’s way of doing things rather than the <em>lower level</em> features offered by PHP.</p>
<p>This does not apply just to PHP of course – it’s an “issue” that happens with any programming language.</p>
<h3 id="heading-how-to-handle-http-requests-in-php">How to Handle HTTP Requests in PHP</h3>
<p>Let’s start with handling HTTP requests.</p>
<p>PHP offers file-based routing by default. You create an <code>index.php</code> file and that responds on the <code>/</code> path.</p>
<p>We saw that when we made the Hello World example in the beginning.</p>
<p>Similarly, you can create a <code>test.php</code> file and automatically that will be the file that Apache serves on the <code>/test</code> route.</p>
<h3 id="heading-how-to-use-get-post-and-request-in-php">How to Use <code>$_GET</code>, <code>$_POST</code> and <code>$_REQUEST</code> in PHP</h3>
<p>Files respond to all HTTP requests, including GET, POST and other verbs.</p>
<p>For any request you can access all the query string data using the <code>$_GET</code> object. It's called <em>superglobal</em> and is automatically available in all our PHP files.</p>
<p>This is of course most useful in GET requests, but also other requests can send data as a query string.</p>
<p>For POST, PUT and DELETE requests you’re more likely to need the data posted as URL-encoded data or using the FormData object, which PHP makes available to you using <code>$_POST</code>.</p>
<p>There is also <code>$_REQUEST</code> which contains all of <code>$_GET</code> and <code>$_POST</code> combined in a single variable.</p>
<h3 id="heading-how-to-use-the-server-object-in-php">How to Use the <code>$_SERVER</code> Object in PHP</h3>
<p>We also have the superglobal variable <code>$_SERVER</code>, which you use to get a lot of useful information.</p>
<p>You saw how to use <code>phpinfo()</code> before. Let’s use it again to see what $_SERVER offers us.</p>
<p>In your <code>index.php</code> file in the root of MAMP run:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
phpinfo();
<span class="hljs-meta">?&gt;</span>
</code></pre>
<p>Then generate the page at <a target="_blank" href="http://localhost:8888">localhost:8888</a> and search <code>$_SERVER</code>. You will see all the configuration stored and the values assigned:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-27_at_13.46.50.jpg" alt="Screen Shot 2022-06-27 at 13.46.50.jpg" width="600" height="400" loading="lazy"></p>
<p>Important ones you might use are:</p>
<ul>
<li><code>$_SERVER['HTTP_HOST']</code></li>
<li><code>$_SERVER['HTTP_USER_AGENT']</code></li>
<li><code>$_SERVER['SERVER_NAME']</code></li>
<li><code>$_SERVER['SERVER_ADDR']</code></li>
<li><code>$_SERVER['SERVER_PORT']</code></li>
<li><code>$_SERVER['DOCUMENT_ROOT']</code></li>
<li><code>$_SERVER['REQUEST_URI']</code></li>
<li><code>$_SERVER['SCRIPT_NAME']</code></li>
<li><code>$_SERVER['REMOTE_ADDR']</code></li>
</ul>
<h3 id="heading-how-to-use-forms-in-php">How to Use Forms in PHP</h3>
<p>Forms are the way the Web platform allows users to interact with a page and send data to the server.</p>
<p>Here is a simple form in HTML:</p>
<pre><code class="lang-php">&lt;form&gt;
  &lt;input type=<span class="hljs-string">"text"</span> name=<span class="hljs-string">"name"</span> /&gt;
  &lt;input type=<span class="hljs-string">"submit"</span> /&gt;
&lt;/form&gt;
</code></pre>
<p>You can put this in your <code>index.php</code> file like it was called <code>index.html</code>.</p>
<p>A PHP file assumes you write HTML in it with some “PHP sprinkles” using <code>&lt;?php ?&gt;</code> so the Web Server can post that to the client. Sometimes the PHP part takes all of the page, and that’s when you generate all the HTML via PHP – it’s kind of the opposite of the approach we're taking here now.</p>
<p>So we have this <code>index.php</code> file that generates this form using plain HTML:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-27_at_13.53.47.jpg" alt="Screen Shot 2022-06-27 at 13.53.47.jpg" width="600" height="400" loading="lazy"></p>
<p>Pressing the Submit button will make a GET request to the same URL sending the data via query string. Notice that the URL changed to <a target="_blank" href="http://localhost:8888/?name=test">localhost:8888/?name=test</a>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-27_at_13.56.46.jpg" alt="Screen Shot 2022-06-27 at 13.56.46.jpg" width="600" height="400" loading="lazy"></p>
<p>We can add some code to check if that parameter is set using the <a target="_blank" href="https://www.php.net/manual/en/function.isset.php"><code>isset()</code></a> function:</p>
<pre><code class="lang-php">&lt;form&gt;
  &lt;input type=<span class="hljs-string">"text"</span> name=<span class="hljs-string">"name"</span> /&gt;
  &lt;input type=<span class="hljs-string">"submit"</span> /&gt;
&lt;/form&gt;

<span class="hljs-meta">&lt;?php</span>
<span class="hljs-keyword">if</span> (<span class="hljs-keyword">isset</span>($_GET[<span class="hljs-string">'name'</span>])) {
  <span class="hljs-keyword">echo</span> <span class="hljs-string">'&lt;p&gt;The name is '</span> . $_GET[<span class="hljs-string">'name'</span>];
}
<span class="hljs-meta">?&gt;</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-27_at_13.56.35.jpg" alt="Screen Shot 2022-06-27 at 13.56.35.jpg" width="600" height="400" loading="lazy"></p>
<p>See? We can get the information from the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET">GET request</a> query string through <code>$_GET</code>.</p>
<p>What you usually do with forms, though is you perform a POST request:</p>
<pre><code class="lang-php">&lt;form **method=<span class="hljs-string">"POST"</span>**&gt;
  &lt;input type=<span class="hljs-string">"text"</span> name=<span class="hljs-string">"name"</span> /&gt;
  &lt;input type=<span class="hljs-string">"submit"</span> /&gt;
&lt;/form&gt;

<span class="hljs-meta">&lt;?php</span>
<span class="hljs-keyword">if</span> (<span class="hljs-keyword">isset</span>($_POST[<span class="hljs-string">'name'</span>])) {
  <span class="hljs-keyword">echo</span> <span class="hljs-string">'&lt;p&gt;The name is '</span> . $_POST[<span class="hljs-string">'name'</span>];
}
<span class="hljs-meta">?&gt;</span>
</code></pre>
<p>See, now we got the same information but the URL didn’t change. The form information was not appended to the URL.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-27_at_13.59.54.jpg" alt="Screen Shot 2022-06-27 at 13.59.54.jpg" width="600" height="400" loading="lazy"></p>
<p>This is because we’re using a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST">POST request</a>, which sends the data to the server in a different way, through URL-encoded data.</p>
<p>As mentioned above, PHP will still serve the <code>index.php</code> file as we’re still sending data to the same URL the form is on.</p>
<p>We’re mixing a bunch of code and we could separate the form request handler from the code that generates the form.</p>
<p>So we can have this in <code>index.php</code>:</p>
<pre><code class="lang-php">&lt;form **method=<span class="hljs-string">"POST"</span> action=<span class="hljs-string">"/post.php"</span>**&gt;
  &lt;input type=<span class="hljs-string">"text"</span> name=<span class="hljs-string">"name"</span> /&gt;
  &lt;input type=<span class="hljs-string">"submit"</span> /&gt;
&lt;/form&gt;
</code></pre>
<p>and we can create a new <code>post.php</code> file with:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
<span class="hljs-keyword">if</span> (<span class="hljs-keyword">isset</span>($_POST[<span class="hljs-string">'name'</span>])) {
  <span class="hljs-keyword">echo</span> <span class="hljs-string">'&lt;p&gt;The name is '</span> . $_POST[<span class="hljs-string">'name'</span>];
}
<span class="hljs-meta">?&gt;</span>
</code></pre>
<p>PHP will display this content now after we submit the form, because we set the <code>action</code> HTML attribute on the form.</p>
<p>This example is very simple, but the <code>post.php</code> file is where we could, for example, save the data to the database, or to a file.</p>
<h3 id="heading-how-to-use-http-headers-in-php">How to Use HTTP Headers in PHP</h3>
<p>PHP lets us set the HTTP headers of a response through the <code>header()</code> function.</p>
<p><a target="_blank" href="https://flaviocopes.com/http-request-headers/">HTTP Headers</a> are a way to send information back to the browser.</p>
<p>We can say the page generates a 500 Internal Server Error:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
header(<span class="hljs-string">'HTTP/1.1 500 Internal Server Error'</span>);
<span class="hljs-meta">?&gt;</span>
</code></pre>
<p>Now you should see the status if you access the page with the <a target="_blank" href="https://flaviocopes.com/browser-dev-tools/">Browser Developer Tools</a> open:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-27_at_14.10.29.jpg" alt="Screen Shot 2022-06-27 at 14.10.29.jpg" width="600" height="400" loading="lazy"></p>
<p>We can set the <code>content/type</code> of a response:</p>
<pre><code class="lang-php">header(<span class="hljs-string">'Content-Type: text/json'</span>);
</code></pre>
<p>We can force a 301 redirect:</p>
<pre><code class="lang-php">header(<span class="hljs-string">'HTTP/1.1 301 Moved Permanently'</span>);
header(<span class="hljs-string">'Location: https://flaviocopes.com'</span>);
</code></pre>
<p>We can use headers to say to the browser “cache this page”, “don’t cache this page”, and a lot more.</p>
<h3 id="heading-how-to-use-cookies-in-php">How to Use Cookies in PHP</h3>
<p>Cookies are a browser feature.</p>
<p>When we send a response to the browser, we can set a cookie which will be stored by the browser, client-side.</p>
<p>Then, every request the browser makes will include the cookie back to us.</p>
<p>We can do many things with cookies. They are mostly used to create a personalized experience without you having to login to a service.</p>
<p>It’s important to note that cookies are domain-specific, so we can only read cookies we set on the current domain of our application, not other application’s cookies.</p>
<p>But JavaScript can read cookies (unless they are <em>HttpOnly cookies</em> but we’re starting to go into a rabbit hole) so cookies should not store any sensitive information.</p>
<p>We can use PHP to read the value of a cookie referencing the <code>$_COOKIE</code> superglobal:</p>
<pre><code class="lang-php"><span class="hljs-keyword">if</span> (<span class="hljs-keyword">isset</span>($_COOKIE[<span class="hljs-string">'name'</span>])) {
  $name = $_COOKIE[<span class="hljs-string">'name'</span>];
}
</code></pre>
<p>The <a target="_blank" href="https://www.php.net/manual/en/function.setcookie.php"><code>setcookie()</code></a> function allows you to set a cookie:</p>
<pre><code class="lang-php">setcookie(<span class="hljs-string">'name'</span>, <span class="hljs-string">'Flavio'</span>);
</code></pre>
<p>We can add a third parameter to say when the cookie will expire. If omitted, the cookie expires at the end of the session/when the browser is closed.</p>
<p>Use this code to make the cookie expire in 7 days:</p>
<pre><code class="lang-php">setcookie(<span class="hljs-string">'name'</span>, <span class="hljs-string">'Flavio'</span>, time() + <span class="hljs-number">3600</span> * <span class="hljs-number">24</span> * <span class="hljs-number">7</span>);
</code></pre>
<p>We can only store a limited amount of data in a cookie, and users can clear the cookies client-side when they clear the browser data.</p>
<p>Also, they are specific to the browser / device, so we can set a cookie in the user’s browser, but if they change browser or device, the cookie will not be available.</p>
<p>Let’s do a simple example with the form we used before. We’re going to store the name entered as a cookie:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
<span class="hljs-keyword">if</span> (<span class="hljs-keyword">isset</span>($_POST[<span class="hljs-string">'name'</span>])) {
  setcookie(<span class="hljs-string">'name'</span>, $_POST[<span class="hljs-string">'name'</span>]);
}
<span class="hljs-keyword">if</span> (<span class="hljs-keyword">isset</span>($_POST[<span class="hljs-string">'name'</span>])) {
  <span class="hljs-keyword">echo</span> <span class="hljs-string">'&lt;p&gt;Hello '</span> . $_POST[<span class="hljs-string">'name'</span>];
} <span class="hljs-keyword">else</span> {
  <span class="hljs-keyword">if</span> (<span class="hljs-keyword">isset</span>($_COOKIE[<span class="hljs-string">'name'</span>])) {
    <span class="hljs-keyword">echo</span> <span class="hljs-string">'&lt;p&gt;Hello '</span> . $_COOKIE[<span class="hljs-string">'name'</span>];
  }
}
<span class="hljs-meta">?&gt;</span>

&lt;form method=<span class="hljs-string">"POST"</span>&gt;
  &lt;input type=<span class="hljs-string">"text"</span> name=<span class="hljs-string">"name"</span> /&gt;
  &lt;input type=<span class="hljs-string">"submit"</span> /&gt;
&lt;/form&gt;
</code></pre>
<p>I added some conditionals to handle the case where the cookie was already set, and to display the name right after the form is submitted, when the cookie is not set yet (it will only be set for the next HTTP request).</p>
<p>If you open the Browser Developer Tools you should see the cookie in the Storage tab.</p>
<p>From there you can inspect its value, and delete it if you want.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-27_at_14.46.09.jpg" alt="Screen Shot 2022-06-27 at 14.46.09.jpg" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-use-cookie-based-sessions-in-php">How to Use Cookie-based Sessions in PHP</h3>
<p>One very interesting use case for cookies is cookie-based sessions.</p>
<p>PHP offers us a very easy way to create a cookie-based session using <code>session_start()</code>.</p>
<p>Try adding this:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
session_start();
<span class="hljs-meta">?&gt;</span>
</code></pre>
<p>in a PHP file, and load it in the browser.</p>
<p>You will see a new cookie named by default <code>PHPSESSID</code> with a value assigned.</p>
<p>That’s the session ID. This will be sent for every new request and PHP will use that to identify the session.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-27_at_14.51.53.jpg" alt="Screen Shot 2022-06-27 at 14.51.53.jpg" width="600" height="400" loading="lazy"></p>
<p>Similarly to how we used cookies, we can now use <code>$_SESSION</code> to store the information sent by the user – but this time it’s not stored client-side.</p>
<p>Only the session ID is.</p>
<p>The data is stored server-side by PHP.</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
session_start();

<span class="hljs-keyword">if</span> (<span class="hljs-keyword">isset</span>($_POST[<span class="hljs-string">'name'</span>])) {
  $_SESSION[<span class="hljs-string">'name'</span>] = $_POST[<span class="hljs-string">'name'</span>];
}
<span class="hljs-keyword">if</span> (<span class="hljs-keyword">isset</span>($_POST[<span class="hljs-string">'name'</span>])) {
  <span class="hljs-keyword">echo</span> <span class="hljs-string">'&lt;p&gt;Hello '</span> . $_POST[<span class="hljs-string">'name'</span>];
} <span class="hljs-keyword">else</span> {
  <span class="hljs-keyword">if</span> (<span class="hljs-keyword">isset</span>($_SESSION[<span class="hljs-string">'name'</span>])) {
    <span class="hljs-keyword">echo</span> <span class="hljs-string">'&lt;p&gt;Hello '</span> . $_SESSION[<span class="hljs-string">'name'</span>];
  }
}
<span class="hljs-meta">?&gt;</span>

&lt;form method=<span class="hljs-string">"POST"</span>&gt;
  &lt;input type=<span class="hljs-string">"text"</span> name=<span class="hljs-string">"name"</span> /&gt;
  &lt;input type=<span class="hljs-string">"submit"</span> /&gt;
&lt;/form&gt;
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-27_at_14.53.24.jpg" alt="Screen Shot 2022-06-27 at 14.53.24.jpg" width="600" height="400" loading="lazy"></p>
<p>This works for simple use cases, but of course for intensive data you will need a database.</p>
<p>To clear the session data you can call <code>session_unset()</code>.</p>
<p>To clear the session cookie use:</p>
<pre><code class="lang-php">setcookie(session_name(), <span class="hljs-string">''</span>);
</code></pre>
<h3 id="heading-how-to-work-with-files-and-folders-in-php">How to Work with Files and Folders in PHP</h3>
<p>PHP is a server-side language, and one of the handy things it provides is access to the filesystem.</p>
<p>You can check if a file exists using <code>file_exists()</code>:</p>
<pre><code class="lang-php">file_exists(<span class="hljs-string">'test.txt'</span>) <span class="hljs-comment">//true</span>
</code></pre>
<p>Get the size of a file using <code>filesize()</code>:</p>
<pre><code class="lang-php">filesize(<span class="hljs-string">'test.txt'</span>)
</code></pre>
<p>You can open a file using <code>fopen()</code>. Here we open the <code>test.txt</code> file in <strong>read-only mode</strong> and we get what we call a <strong>file descriptor</strong> in <code>$file</code>:</p>
<pre><code class="lang-php">$file = fopen(<span class="hljs-string">'test.txt'</span>, <span class="hljs-string">'r'</span>)
</code></pre>
<p>We can terminate the file access by calling <code>fclose($fd)</code>.</p>
<p>Read the content of a file into a variable like this:</p>
<pre><code class="lang-php">$file = fopen(<span class="hljs-string">'test.txt'</span>, <span class="hljs-string">'r'</span>)

fread($file, filesize(<span class="hljs-string">'test.txt'</span>));

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

<span class="hljs-keyword">while</span> (!feof($file)) {
    $data .= fgets($file, <span class="hljs-number">5000</span>);
}
</code></pre>
<p><code>feof()</code> checks that we haven’t reached the end of the file as <code>fgets</code> reads 5000 bytes at a time.</p>
<p>You can also read a file line by line using <code>fgets()</code>:</p>
<pre><code class="lang-php">$file = fopen(<span class="hljs-string">'test.txt'</span>, <span class="hljs-string">'r'</span>)

<span class="hljs-keyword">while</span>(!feof($file)) {
  $line = fgets($file);
  <span class="hljs-comment">//do something</span>
}
</code></pre>
<p>To write to a file you must first open it in <strong>write mode</strong>, then use <code>fwrite()</code>:</p>
<pre><code class="lang-php">$data = <span class="hljs-string">'test'</span>;
$file = fopen(<span class="hljs-string">'test.txt'</span>, <span class="hljs-string">'w'</span>)
fwrite($file, $data);
fclose($file);
</code></pre>
<p>We can delete a file using <code>unlink()</code>:</p>
<pre><code class="lang-php">unlink(<span class="hljs-string">'test.txt'</span>)
</code></pre>
<p>Those are the basics, but of course there are <a target="_blank" href="https://www.php.net/manual/en/ref.filesystem.php">more functions to work with files</a>.</p>
<h3 id="heading-php-and-databases">PHP and Databases</h3>
<p>PHP offers various built-in libraries to work with databases, for example:</p>
<ul>
<li><a target="_blank" href="https://www.php.net/manual/en/book.pgsql.php">PostgreSQL</a></li>
<li><a target="_blank" href="https://www.php.net/manual/en/set.mysqlinfo.php">MySQL</a> / MariaDB</li>
<li><a target="_blank" href="https://www.php.net/manual/en/set.mongodb.php">MongoDB</a></li>
</ul>
<p>I won't cover this in the handbook because I think this is a big topic and one that would also require you to learn SQL.</p>
<p>I am also tempted to say that if you need a database you should use a framework or ORM that would save you security issues with SQL injection. <a target="_blank" href="https://laravel.com/docs/eloquent">Laravel’s Eloquent</a> is a great example.</p>
<h3 id="heading-how-to-work-with-json-in-php">How to Work with JSON in PHP</h3>
<p><a target="_blank" href="https://flaviocopes.com/json/">JSON</a> is a portable data format we use to represent data and send data from client to server.</p>
<p>Here’s an example of a JSON representation of an object that contains a string and a number:</p>
<pre><code class="lang-php">{
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Flavio"</span>,
  <span class="hljs-string">"age"</span>: <span class="hljs-number">35</span>
}
</code></pre>
<p>PHP offers us two utility functions to work with JSON:</p>
<ul>
<li><code>json_encode()</code> to encode a variable into JSON</li>
<li><code>json_decode()</code> to decode a JSON string into a data type (object, array…)</li>
</ul>
<p>Example:</p>
<pre><code class="lang-php">$test = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>];

$encoded = json_encode($test); <span class="hljs-comment">// "["a","b","c"]" (a string)</span>

$decoded = json_decode($encoded); <span class="hljs-comment">// [ "a", "b", "c" ] (an array)</span>
</code></pre>
<h3 id="heading-how-to-send-emails-with-php">How to Send Emails with PHP</h3>
<p>One of the things that I like about PHP is the conveniences, like sending an email.</p>
<p>Send an email using <a target="_blank" href="https://www.php.net/manual/en/function.mail.php"><code>mail()</code></a>:</p>
<pre><code class="lang-php">mail(<span class="hljs-string">'test@test.com'</span>, <span class="hljs-string">'this subject'</span>, <span class="hljs-string">'the body'</span>);
</code></pre>
<p>To send emails at scale we can’t rely on this solution, as these emails tend to reach the spam folder more often than not. But for quick testing this is just helpful.</p>
<p>Libraries like <a target="_blank" href="https://github.com/PHPMailer/PHPMailer">https://github.com/PHPMailer/PHPMailer</a> will be super helpful for more solid needs, using an SMTP server.</p>
<h2 id="heading-how-to-use-composer-and-packagist">How to Use Composer and Packagist</h2>
<p><a target="_blank" href="https://getcomposer.org">Composer</a> is the package manager of PHP.</p>
<p>It allows you to easily install packages into your projects.</p>
<p>Install it on your machine (<a target="_blank" href="https://getcomposer.org/doc/00-intro.md#installation-linux-unix-macos">Linux/Mac</a> or <a target="_blank" href="https://getcomposer.org/doc/00-intro.md#installation-windows">Windows</a>) and once you’re done you should have a <code>composer</code> command available on your terminal.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-27_at_16.25.43.jpg" alt="Screen Shot 2022-06-27 at 16.25.43.jpg" width="600" height="400" loading="lazy"></p>
<p>Now inside your project you can run <code>composer require &lt;lib&gt;</code> and it will be installed locally. For example let's install <a target="_blank" href="https://carbon.nesbot.com">the Carbon library</a> that helps us work with dates in PHP</p>
<pre><code class="lang-php">composer <span class="hljs-keyword">require</span> nesbot/carbon
</code></pre>
<p>It will do some work:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-27_at_16.27.11.jpg" alt="Screen Shot 2022-06-27 at 16.27.11.jpg" width="600" height="400" loading="lazy"></p>
<p>Once it’s done, you will find some new things in the folder <code>composer.json</code> that lists the new configuration for the dependencies:</p>
<pre><code class="lang-php">{
    <span class="hljs-string">"require"</span>: {
        <span class="hljs-string">"nesbot/carbon"</span>: <span class="hljs-string">"^2.58"</span>
    }
}
</code></pre>
<p><code>composer.lock</code> is used to “lock” the versions of the package in time, so the exact same installation you have can be replicated on another server. The <code>vendor</code> folder contains the library just installed and its dependencies.</p>
<p>Now in the <code>index.php</code> file we can add this code at the top:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
<span class="hljs-keyword">require</span> <span class="hljs-string">'vendor/autoload.php'</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">Carbon</span>\<span class="hljs-title">Carbon</span>;
</code></pre>
<p>and then we can use the library!</p>
<pre><code class="lang-php"><span class="hljs-keyword">echo</span> Carbon::now();
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-27_at_16.34.47.jpg" alt="Screen Shot 2022-06-27 at 16.34.47.jpg" width="600" height="400" loading="lazy"></p>
<p>See? We didn’t have to manually download a package from the internet and install it somewhere...it was all fast, quick, and well organized.</p>
<p>The <code>require 'vendor/autoload.php';</code> line is what enables <strong>autoloading</strong>. Remember when we talked about <code>require_once()</code> and <code>include_once()</code>? This solves all of that – we don’t need to manually search for the file to include, we just use the <code>use</code> keyword to import the library into our code.</p>
<h2 id="heading-how-to-deploy-a-php-application">How to Deploy a PHP Application</h2>
<p>When you’ve got an application ready, it’s time to deploy it and make it accessible from anyone on the Web.</p>
<p>PHP is the programming language with the best deployment <em>story</em> across the Web.</p>
<p>Trust me, every single other programming language and ecosystem wishes they were as easy as PHP.</p>
<p>The great thing about PHP, the thing it got <em>right</em> and allowed it to have the incredible success it has had, is the instant deploy.</p>
<p>You put a PHP file on a folder served by a Web server, and <em>voilà</em> – it just works.</p>
<p>No need to restart the server, run an executable, nothing.</p>
<p>This is still something that a lot of people do. You get a shared hosting for $3/month, upload your files via FTP, and you're done.</p>
<p>These days, though, I think Git deploy is something that should be baked into every project, and shared hosting should be a thing of the past.</p>
<p>One solution is always having your own private VPS (Virtual Private Server), which you can get from services like DigitalOcean or Linode.</p>
<p>But managing your own VPS is no joke. It requires serious knowledge and time investment, and constant maintenance.</p>
<p>You can also use the so-called PaaS (Platform as a Service), which are platforms that focus on taking care of all the boring stuff (managing servers) and you just upload your app and it runs.</p>
<p>Solutions like <strong>DigitalOcean App Platform</strong> (which is different from a DigitalOcean VPS), Heroku, and many others are great for your first tests.</p>
<p>These services allow you to connect your GitHub account and deploy any time you push a new change to your <a target="_blank" href="https://flaviocopes.com/git/">Git</a> repository.</p>
<p>You can learn <a target="_blank" href="https://flaviocopes.com/github-setup-from-zero/">how to setup Git and GitHub from zero here</a>.</p>
<p>This is a much better workflow compared to FTP uploads.</p>
<p>Let’s do a bare bones example.</p>
<p>I created a simple PHP application with just an <code>index.php</code> file:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
<span class="hljs-keyword">echo</span> <span class="hljs-string">'Hello!'</span>;
<span class="hljs-meta">?&gt;</span>
</code></pre>
<p>I add the parent folder to my GitHub Desktop app, I initialize a Git repo, and I push it to GitHub:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-27_at_17.26.24.jpg" alt="Screen Shot 2022-06-27 at 17.26.24.jpg" width="600" height="400" loading="lazy"></p>
<p>Now go on <a target="_blank" href="http://digitalocean.com">digitalocean.com</a>.</p>
<p>If you don’t have an account yet, <a target="_blank" href="https://m.do.co/c/bd0657b4877c">use my referral code to sign up get $100 free credits over the next 60 days</a> and you can work on your PHP app for free.</p>
<p>I connect to my DigitalOcean account and I go to Apps → Create App.</p>
<p>I connect my GitHub Account and select the repo of my app.</p>
<p>Make sure “Autodeploy” is checked, so the app will automatically redeploy on changes:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-27_at_17.31.54.jpg" alt="Screen Shot 2022-06-27 at 17.31.54.jpg" width="600" height="400" loading="lazy"></p>
<p>Click “Next” then Edit Plan:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-27_at_17.32.24.jpg" alt="Screen Shot 2022-06-27 at 17.32.24.jpg" width="600" height="400" loading="lazy"></p>
<p>By default the Pro plan is selected.</p>
<p>Use Basic and pick the $5/month plan.</p>
<p>Note that you pay $5 per month, but billing is per hour – so you can stop the app any time you want.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-27_at_17.32.28.jpg" alt="Screen Shot 2022-06-27 at 17.32.28.jpg" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-27_at_17.33.15.jpg" alt="Screen Shot 2022-06-27 at 17.33.15.jpg" width="600" height="400" loading="lazy"></p>
<p>Then go back and press “Next” until the “Create Resources” button appears to create the app. You don’t need any database, otherwise that would be another $7/month on top.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-27_at_17.33.46.jpg" alt="Screen Shot 2022-06-27 at 17.33.46.jpg" width="600" height="400" loading="lazy"></p>
<p>Now wait until the deployment is ready:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-27_at_17.35.00.jpg" alt="Screen Shot 2022-06-27 at 17.35.00.jpg" width="600" height="400" loading="lazy"></p>
<p>The app is now up and running!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Screen_Shot_2022-06-27_at_17.35.31.jpg" alt="Screen Shot 2022-06-27 at 17.35.31.jpg" width="600" height="400" loading="lazy"></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>You’ve reached the end of the PHP Handbook!</p>
<p>Thank you for reading through this introduction to the wonderful world of PHP development. I hope it will help you get your web development job, become better at your craft, and empower you to work on your next big idea.</p>
<p>Note: you can get a <a target="_blank" href="https://thevalleyofcode.com/download/php/">PDF, ePub, or Mobi</a> version of this handbook for easier reference, or for reading on your Kindle or tablet.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Start a Blog [Free 70-Page Book] ]]>
                </title>
                <description>
                    <![CDATA[ What follows is a full-length book on how to create a successful blog. I am a software developer and I've written 1,500 posts on my blog over the past few years. Millions of people have read my writing. And my blog is now one of the top 20,000 websit... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-start-a-blog-book/</link>
                <guid isPermaLink="false">66bb5a7eb6e566d0c2aea609</guid>
                
                    <category>
                        <![CDATA[ blog ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Blogging ]]>
                    </category>
                
                    <category>
                        <![CDATA[ writing ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Flavio Copes ]]>
                </dc:creator>
                <pubDate>Mon, 11 Oct 2021 17:21:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/10/how-to-start-a-blog.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>What follows is a full-length book on how to create a successful blog.</p>
<p>I am a software developer and I've written 1,500 posts on my blog over the past few years. Millions of people have read my writing. And my blog is now one of the top 20,000 websites on earth (according to Amazon's Alexa website ranking tool).</p>
<p>In this book, we will not focus on the "how to install WordPress" aspect of blogging. We will also not discuss how to build your own blogging software. (That's a fun exercise, but not as important as what I'd like to discuss.)</p>
<p>This book will instead focus on developing the right mindset. It will also show you how to get systems in place so that you can run your blog over a long period of time.</p>
<p>The hard part of blogging is doing it sustainably. How do you blog in such a way that you can publish consistently? How do you become a household name in your field? How do you hold your audience's attention over time?</p>
<p>A lot of bloggers struggle with these challenges. There are so many blogs out there with 1 or 2 posts. Or the last post is from 2018 saying "Sorry I haven't published for a long time." With planning and execution, you can prevent this from happening to your blog.</p>
<p>Also, you may be wondering how relevant blogging is in the 2020s. After all, YouTube, TikTok, and Instagram get a lot of headlines in the news. Well I'm here to tell you that blogs are still powerful when it comes to content marketing and getting organic traffic from Google.</p>
<p>The main goal of the book (and yes, you can read the book in its entirety here) is to help you get started with blogging in the right way. So grab a beverage and a comfortable chair. And bookmark this page so you can come back and review, in case you can't finish it in one sitting.</p>
<p>And if you prefer, <a target="_blank" href="https://flaviocopes.com/page/book-blog/">you can download a PDF and ePub version of this <strong>How to Start a Blog</strong> book here</a>.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-framing-your-blog-for-success">Framing your blog for success</a></li>
<li><a class="post-section-overview" href="#heading-the-benefits-of-having-a-successful-blog">The benefits of having a successful blog</a></li>
<li><a class="post-section-overview" href="#heading-pick-a-goal-for-your-blog">Pick a goal for your blog</a></li>
<li><a class="post-section-overview" href="#heading-own-your-platform">Own your platform</a></li>
<li><a class="post-section-overview" href="#heading-make-the-first-step">Make the first step</a></li>
<li><a class="post-section-overview" href="#heading-solutions-to-common-problems">Solutions to common problems</a></li>
<li><a class="post-section-overview" href="#heading-content-is-king">Content is king</a></li>
<li><a class="post-section-overview" href="#heading-practical-content-suggestions">Practical content suggestions</a></li>
<li><a class="post-section-overview" href="#heading-create-a-system">Create a system</a></li>
<li><a class="post-section-overview" href="#heading-how-to-get-people-to-your-blog">How to get people to your blog</a></li>
<li><a class="post-section-overview" href="#heading-expand-your-reach-with-an-email-list">Expand your reach with an email list</a></li>
<li><a class="post-section-overview" href="#heading-ups-and-downs">Ups and downs</a></li>
<li><a class="post-section-overview" href="#heading-making-money-with-a-blog">Making money with a blog</a></li>
<li><a class="post-section-overview" href="#heading-final-words">Final words</a></li>
</ol>
<h2 id="heading-framing-your-blog-for-success">Framing your blog for success</h2>
<p>People communicate and share information over the internet. We use it to look for help. Maybe we try to find the perfect recipe for dinner or the best book we should read this month.</p>
<p>A blog is a tiny website, made by one or a handful of people, with the goal of creating information that will help people.</p>
<p>On this blog, you will write posts. A post is a single page of the website containing some information.</p>
<p>The concept of a blog I'll talk about in this book is different from a diary, where you write about everyday things as they happen. That is something you can definitely do, but it's not what I'll be talking about here.</p>
<p>By blog, I mean a personal site, or a product/company site, where you regularly produce interesting content that can be beneficial to other people.</p>
<p>You want people to be able to find the solution to their problem on your blog.</p>
<p>I want to highlight this point because it's central. Your blog should be useful to other people. Without this fundamental concept, your blog has no reason to exist.</p>
<h3 id="heading-why-a-blog-does-matter">Why a blog does matter</h3>
<p>Blogs are the fundamental building block of today's internet. Think about it: we have giant corporations that create walled gardens that people are constantly drawn to, like Facebook, YouTube, Instagram, and Twitter.</p>
<p>Those are places that are engineered get you addicted so that you consume, debate, consume, debate, consume. And if you are in the lucky 1‰, you will be one of the stars of those walled gardens, and you will profit from other people consuming, debating, consuming, debating, consuming.</p>
<p>What are those people consuming? Well, aside from the content, they're consuming their time.</p>
<p>With notable exceptions, much of the content created and shared on the internet isn't useful. </p>
<p>But a blog is one of those rare places on the Internet where you can create something of value without a giant corporation benefitting from your work. You are the owner of your little corner of the world.</p>
<p>I'll soon tell you more about the "own your platform" concept, but here's the gist: a blog matters because it's 100% yours.</p>
<h3 id="heading-is-blogging-still-relevant">Is blogging still relevant?</h3>
<p>This is a legit question. Is blogging still relevant in today's world, dominated by social media and big platforms?</p>
<p>Can the underdog still find some space on the Internet? Don't we have too many sites already?</p>
<p>First, we'll never have too many sites. There's less than 1 person creating content for every 100 people. This is a rule for all media consumption: there are ~100 TV or radio stations in a country with 100 million people. Same for newspapers.</p>
<p>The same goes for the Internet. If you start creating, and you do your job well, eventually your content will surface and you will have success. Whatever success means to you.</p>
<p>This is possible with videos on YouTube, podcasts, and blogs, of course.</p>
<p>So why should you start a blog instead of making videos? It's a choice. We can't all be good at making videos, and we can't all have a voice made for podcasts. Similarly, we can't all be good at writing.</p>
<p>But if you happen to enjoy writing and you like the idea of having your own little corner on the Internet, then creating a blog might be what you are looking for.</p>
<h3 id="heading-should-i-have-a-personal-blog-or-a-companyproduct-blog">Should I have a personal blog or a company/product blog?</h3>
<p>If you are a freelancer, working solo, or you are a solopreneur, a company of one, you might have a tough decision ahead: should you create a personal blog or a company blog?</p>
<p>There's a big distinction in this. In my opinion, a personal blog is way better because companies and projects come and go. You might sell your company in 3 years.</p>
<p>Your personal brand, however, will stick with you wherever you go. The advantage I find in a personal brand is that you have the ability to experiment and pivot, if necessary. </p>
<p>If you create a brand that's too tied to a product or area, you can't switch without changing the name and domain, so it can be very confusing to people and it's very hard to make it work nicely.</p>
<p>And most likely you'll have a hard time finding a good idea, at first, so it’s always good to have more than one option. That way you don't have to start from zero.</p>
<h3 id="heading-why-a-blog-and-not-videos-or-podcasts">Why a blog and not videos or podcasts?</h3>
<p>In the last few years, videos and podcasts have grown tremendously.</p>
<p>Videos, in particular, are very popular. Kids want to become YouTubers when they grow up.</p>
<p>Both videos and podcasts are awesome. I watch YouTube every day and I am subscribed to several podcasts, too.</p>
<p>There's one thing I noticed about those platforms, however. Podcasts are very hard to discover. I only discover new podcasts if I see one mentioned somewhere. Or by word of mouth.</p>
<p>And in addition to having great content, as a podcast owner, a person's voice tone is a differentiating factor that makes me like a podcast or not. You are either born with a great podcasting voice, or you're not.</p>
<p>With videos, it's the same thing. A creator's personality is a unique differentiating factor in a great YouTube channel.</p>
<p>Plus, videos, if made well, require a huge effort in time, energy and equipment you need.</p>
<p>A blog, on the other hand, is something you can make no matter who you are, as long as you can write. You don't need to have that uniqueness that makes you liked on YouTube, and you are not trapped on one platform (YouTube). You also have a great channel for organic discovery of your blog posts (Google). More on this later.</p>
<p>But you don't have to choose one over the other, of course.</p>
<p>Many times creators use a blog alongside a YouTube channel, or a podcast. This is helpful if you use it more than just to cross-post content from one channel to another, but as a complementary tool.</p>
<p>When done well, it's a powerful combination.</p>
<h3 id="heading-define-who-your-blogs-readers-are">Define who your blog's readers are</h3>
<p>A blog that's successful and useful to other people is a blog that has a readership in mind.</p>
<p>I'm sure you've stumbled upon those blogs or sites that talk about a little bit of everything.</p>
<p>It all seems very random, and you don't find a reason for coming back to that site, so you forget about it.</p>
<p>If you happen to visit a website that talks just about your favorite topic, you might save it for later in your bookmarks, or leave the tab open to go back to it later.</p>
<p>This happens because the owner of the site is not just writing about everything that comes to mind: they have a specific kind of person they are talking to.</p>
<p>And this is what you should do, as well. Carefully define the kind of person you want to talk to with your blog.</p>
<p>You have to pick a niche.</p>
<h3 id="heading-how-to-pick-a-blogging-niche">How to Pick a Blogging Niche</h3>
<p>Picking a niche is how you can define what your little corner of the internet will be all about.</p>
<p>It can be all about you, your hobbies, passions, and stories. But then not many people will find it very useful. Maybe one post can solve their problems, but will they ever come back? Probably not.</p>
<p>Because your blog's not about you, it's about your readers.</p>
<p>Pick a niche. A small subject.</p>
<p>Say you're a programmer. You can write a blog about the C++ programming language, write 2 posts a week, and never run out of topics for 20 years. It's probably even a niche that's too broad, not much of a niche.</p>
<p>A better niche would be C++ programming for embedded devices. Or using C++ to build games.</p>
<p>Then filter out this group of people a little bit more. Using C++ to build a 2D game engine. </p>
<p>You can write about that for years, too, but this time if a person is interested in this subject, they will bookmark the site and download everything they can because you are the expert (or at least more of an expert than they are) and they can get a lot of value from you.</p>
<h3 id="heading-blogging-is-a-a-marathon-not-a-sprint">Blogging is a a marathon, not a sprint</h3>
<p>I want to give you another concept that will frame your blog for success: it’s not a sprint, it's a marathon.</p>
<p>As with everything in life, creating a successful blog takes time.</p>
<p>Creating a blog, per se, is a matter of hours if not minutes. This is why everyone can start a blog.</p>
<p>But creating a successful blog, depending on what you consider "success", can take years, and not many people welcome this fact with joy.</p>
<p>People like immediate, fast success. It almost never happens, unless you are very lucky.</p>
<p>Consider blogging to be your marathon.</p>
<h2 id="heading-the-benefits-of-having-a-successful-blog">The benefits of having a successful blog</h2>
<p>We all have limited time to dedicate to our hobbies, families, and friends. So why should you set aside a number of hours every week to work on your blog? And it's not just a few hours here and there. If you want the blog to be successful, you have to dedicate a lot of time.</p>
<p>As with everything in life, you have to evaluate the pros and cons.</p>
<p>Let's analyze the benefits.</p>
<h3 id="heading-personal-satisfaction-and-gratification">Personal satisfaction and gratification</h3>
<p>First, blogging gives you personal satisfaction and gratification.</p>
<p>Many people like to build puzzles or to do crosswords during their free time. Or they like to tinker with woodworking or electronic gadgets.</p>
<p>Writing on your blog can give you the same feeling.</p>
<p>Plus, it gives you a sense of accomplishment.</p>
<p>Writing a blog post can be easy sometimes.</p>
<p>Other times it's really hard, maybe because of the subject, or maybe because you can't find your way through your writing.</p>
<p>But when you finally finish it, it's a really good feeling.</p>
<h3 id="heading-you-can-get-your-name-out">You can get your name out</h3>
<p>Another thing that a blog can give you is discoverability.</p>
<p>When people search your name on Google, if you write under your own name people will find your blog as the first result. This gives a great impression at a job interview, for example. </p>
<p>And even if you are currently employed, having a blog is like an extension of your personal brand that can help you be perceived as a more knowledgeable person.</p>
<p>It's like writing a book. A book that no one reads is one thing – but writing a successful book that is read by many people is a completely different thing.</p>
<p>Blogs follow the same rule. Some blogs are not very popular, maybe due to the subject or other factors (we'll see more about this later). But some blogs are successful, and others are wildly successful.</p>
<h3 id="heading-you-can-get-in-touch-with-more-people">You can get in touch with more people</h3>
<p>By writing on your blog, you can publish things that are read by people all around the world, and your work can possibly help them achieve what they want.</p>
<p>Not only this is great for personal satisfaction and fulfillment. It's also a great way to be perceived as an expert in your field.</p>
<p>And the more people you can reach and impact, the better it is for you (and them!).</p>
<h3 id="heading-a-blog-is-your-platform">A blog is your platform</h3>
<p>Your platform, your launchpad. In today's world, there's just too much noise.</p>
<p>We are bombarded with information from every medium, and it's really hard, as a creator, to stand out.</p>
<p>A blog can be a great starting point for your next project, your next adventure, your next (or first) company. It's yours.</p>
<p>The goal of any product is to be used by people.</p>
<p>Lots of people, possibly. Not everything can "change the world" Silicon Valley-style, but your little project, product, or service can have a big impact on a tiny slice of the people it targets.</p>
<p>But the first steps are always hard, including finding a good idea.</p>
<p>Your blog can be the way you find the initial users for something that you find worth creating.</p>
<p>Put the idea out there. See how people react to it.</p>
<h3 id="heading-you-can-become-an-active-part-of-the-community">You can become an active part of the community</h3>
<p>In every community, there is a small number of people that lead, a slightly bigger number of people that contribute, and a larger number of people following.</p>
<p>Think about the community you are in. The 1%, or 0.1%, work on the "core". They organize an event,  build a software project, host a podcast, work on a product. Another 9% will participate and be an active part of the community around it. 90% of the people will just consume.</p>
<p>As a blogger, even if you're not in the 1% that lead, because you don't want that responsibility or power or you can't make the commitment, you can still contribute. You can add your input, and be heard in a world that is eager for people that want to stand out.</p>
<p>Write about that thing you are so enthusiastic about. Create a helpful resource. People will be really grateful for that. Including the 1% or 0.1% that lead but that do not have time, resources, or will to create those resources.</p>
<p>A notable example is Jeffrey Way. He created Laracasts to build training screencasts for Laravel, a programming framework that was gaining traction.</p>
<p>He’s now an integral part of the framework ecosystem and a driving force for its popularity.</p>
<h2 id="heading-pick-a-goal-for-your-blog">Pick a goal for your blog</h2>
<p>You can start a blog for multiple reasons. No one has the same ambitions, the same drive, or the same starting point.</p>
<h3 id="heading-you-want-to-get-a-job">You want to get a job</h3>
<p>One goal for a blog might be to help to get your first job.</p>
<p>Suppose you are getting ready for your first rounds of interviews as a Junior Frontend Developer. As you are learning the technology and experimenting, maybe following an online course, you document everything you are learning.</p>
<p>I think this is great for 3 reasons:</p>
<ol>
<li>you reinforce your learning</li>
<li>you build up an online presence</li>
<li>you get better at documenting and explaining technology</li>
</ol>
<p>As you approach the interview and send out applications, companies will see that you have a website. They'll find that you are great at explaining technology, you know how to communicate, and you definitely know your stuff.</p>
<p>And this is a great advantage over any other job applicant that does not have a website.</p>
<h3 id="heading-you-want-to-get-a-raise-or-a-better-job">You want to get a raise or a better job</h3>
<p>If you already have a job, you might want to step up your career and get better pay, or switch to another niche in the field you are interested in.</p>
<p>Having a blog that positions you as an expert in the thing you want to work on is definitely a big plus.</p>
<p>You can leverage your blog at your current company to reposition yourself as a senior developer.</p>
<p>Your colleagues will look up to you and your writing and will perceive you as an authority in the field.</p>
<h3 id="heading-you-want-to-get-bettermore-clients">You want to get better/more clients</h3>
<p>If you are not interested in getting a job and prefer being the independent freelancer with a queue of prospect clients lined up, blogging can be a game-changer for you.</p>
<p>I experienced this first-hand when I started my career in tech.</p>
<p>I started my career by finding work on freelancing sites. It was hard to compete with freelancers all around the world who were much more experienced than I was in many cases. And sometimes they were located in a lower cost of living area, which allowed them to provide the same service at a fraction of my rates.</p>
<p>I started a blog about the subject I was specializing on, an open-source CMS, written in Italian, my own language, and people from Italy slowly started to perceive me as an expert. They were more than willing to pay a premium to work with a person that spoke their language, worked in their timezone, and was one of the few experts in the field in the country.</p>
<p>My blog was key to this because people searched for topics they knew they needed help with – and they found me.</p>
<p>At some point, I was even able to turn down client proposals because I had too many requests. I could choose the ones that I believed were better for my business and more interesting to me.</p>
<h3 id="heading-you-want-to-demonstrate-your-expertise">You want to demonstrate your expertise</h3>
<p>A common benefit to either getting a job or freelancing clients is this: a blog helps you demonstrate your expertise and expose what you know to other people.</p>
<p>Some people are more naturally inclined to show off their abilities.</p>
<p>Sometimes, depending on culture and perception, we can even think of them as more capable than what they really are.</p>
<p>Some other people are less inclined, perhaps because of introversion or shyness.</p>
<p>Blogging is a great way to demonstrate your expertise even if you're not naturally inclined to raise your hand in public. This is because it's a medium that has very low friction compared to, for example, creating videos that show your face on YouTube.</p>
<h3 id="heading-you-want-to-document-your-learning">You want to document your learning</h3>
<p>A great goal for your blog could be to document your learning. Perhaps being more competitive in the job market is not something you are interested in right now, or you just want to write about your hobby.</p>
<p>A blog is a great track record for everything you learn.</p>
<p>I have a terrible memory, for example, and sometimes I just create a blog post to remember how I made something work.</p>
<p>I used to write notes on an app on my computer, but now I default to blog posts because I realized I can help other people by publishing my notes on the Internet.</p>
<h3 id="heading-you-want-to-structure-your-thoughts-and-learn-more">You want to structure your thoughts and learn more</h3>
<p>The way I used to learn best back in school was by creating very detailed notes about a subject.</p>
<p>However I only made them for subjects I was interested in, which in retrospect explains why I was good in some classes and bad in others.</p>
<p>You can use your blog as a way to learn better.</p>
<p>I am a huge proponent of learning through blogging because it works.</p>
<p>I use blogging as a way to learn a subject and at the same time help other people.</p>
<p>When I write a new blog post I am forced to create a mind map of the subject and I try to frame it, before writing about it.</p>
<p>In this way I learn much more than I do when I read a book or watch a course without taking organized notes about it. And as a side benefit, I end up with a new blog post I can publish.</p>
<h3 id="heading-you-want-to-become-better-at-explaining-things">You want to become better at explaining things</h3>
<p>A great benefit of blogging is that over time you'll become better at explaining things.</p>
<p>You will take fewer things for granted, and you'll think more from the point of view of the person who is listening to you, rather than just writing a bunch of words to be perceived as an expert.</p>
<p>This will help you tremendously in your career and as a person.</p>
<h3 id="heading-you-want-to-grow-your-audience">You want to grow your audience</h3>
<p>A great benefit of having your own blog is that over time you'll start to build an audience.</p>
<p>As with many things, the more time you dedicate to it, the more your audience will likely grow.</p>
<p>People might get to know you. Recognize your name. You will not become famous (except in rare cases), but this might not be what you want, either.</p>
<p>That's not what an audience is for. And honestly, I see many developers raise an eyebrow when marketing subjects come into play.</p>
<p>An audience is a great place to test your ideas. An audience can help you figure out something. An audience is your group of people, the people that trust you and that can help you move to the next level.</p>
<h3 id="heading-you-want-to-express-yourself">You want to express yourself</h3>
<p>A blog does not need to be a means to an end.</p>
<p>My favorite blogs are the ones that are playgrounds for creativity and expression. Especially when applied to programming and computers in general.</p>
<p>A blog is a great way to have a track record of all your past creative projects.</p>
<p>Your own centralized creative hub.</p>
<h2 id="heading-own-your-platform">Own your platform</h2>
<p>Your blog is the operational center for your future. Your platform, your headquarters. Everything else should bring you to your site. </p>
<p>Your Facebook page, YouTube channel, Twitter, Medium, your guest posts on other blogs, and the content you stream – all are tools to connect people with the content of your site on the Internet.</p>
<p>The website can be made with any technology you want. It does not really matter, provided that it’s on a domain that you own, and that you can change as desired.</p>
<p>You should have complete freedom over it: you have to be able to contact your users whenever you want, you must be able to extract all the data from this platform. Also, whenever you want to, you should be able to move away to a different platform with all your content.</p>
<p>Lastly, you do not have to be at the mercy of other people decisions.</p>
<h3 id="heading-the-platforms-of-other-people">The platforms of other people</h3>
<p>There are many ways to sell online. For each type of product, there are a number of options, and while sometimes you can sell things in the way you want, sometimes you need to work with a platform managed by someone else.</p>
<p>For example, if you sell digital books, you will, of course, sell them on Amazon Kindle, which probably represents 80% of the market.</p>
<p>Do you sell physical products? In addition to your own e-commerce, you will want to sell them on Amazon too, as it’s a huge market opportunity.</p>
<p>Do you make mobile apps? You will need to sell them on the App Store if you target Apple users, or on Google Play for Android.</p>
<p>Here, in some of these examples, it is clear that sometimes you have choices and sometimes you have to take a mandatory road to actually sell something. </p>
<p>You can’t distribute iPhone apps through your site. If you build desktop applications for Mac, on the other hand, this is possible, but you might also want to join the Mac App Store, which in this case is optional. Apple sets the rules, but it gives you some visibility that you would not get without being in the App Store.</p>
<p>All these great distribution systems such as the App Store, Amazon, Kindle, and many others like Etsy or Alibaba, are platforms. Other people’s platforms.</p>
<h3 id="heading-benefits-of-using-a-platform-managed-by-other-people">Benefits of using a platform managed by other people</h3>
<p>There are, of course, benefits to using a platform managed by other people. It provides a virtually limitless user base, customers visiting the platform already have an account, and in many cases they just need to press the buy button.</p>
<p>In general, not managing your own platform saves you worry about having to manage a huge number of things.</p>
<h3 id="heading-disadvantages-of-using-a-platform-managed-by-other-people">Disadvantages of using a platform managed by other people</h3>
<p>But there are disadvantages of using a platform, as well. You have to comply with the rules the owners impose, and the customers are not yours – they are the platform's customers. So you might struggle to create a relationship with your customers.</p>
<p>You also have little room for your branding, as everything could change from one day to the next. In some cases you have little control over your prices, and you'll have to pay commission to the platform for each sale you make.</p>
<h3 id="heading-the-platform-sets-the-rules">The platform sets the rules</h3>
<p>A platform is not just the place where people turn into customers, but it is also the place where you can find and interact with them. Facebook, Instagram, and Twitter are platforms, phenomenal platforms, but still platforms built by others.</p>
<p>A few years ago, having a Facebook page with 10,000 fans and writing a message on the page was enough to show this message to a vast percentage of those people. Unfortunately, this has changed today because the Facebook platform has changed. Now we are lucky if we reach 10% of our audience.</p>
<p>The only way to reach more people who like your page is to sponsor posts. So you have to pay Facebook to communicate with your own fans: this is an example of what it means to build on another property.</p>
<p>This is not to say that you should not have a Facebook page, that you don’t have to invest in Facebook Ads, or that you do not have to interact with people on Twitter.</p>
<p>You should do these things if you're trying to build an audience. The market imposes them on you, because you find people in these places. But always try to use these large containers to find people and bring them to you. </p>
<p>And it's important to always have a way out of a platform, and not to be completely dependent on it.</p>
<p>To do this, you have to push users to come to you through all the channels you can take advantage of.</p>
<p>You have to create your own platform.</p>
<h3 id="heading-use-your-own-domain-name">Use your own domain name</h3>
<p>Your domain name is very important. I use my own name for the domain: <a target="_blank" href="http://flaviocopes.com">flaviocopes.com</a>.</p>
<p>Your domain is like your address.</p>
<p>Except that a real-world address changes when you move somewhere else.</p>
<p>Your domain, on the other hand, is yours forever, regardless of your physical location. Like your email address.</p>
<p>When you publish things on your own website, under your own domain name, you are building virtual real estate and generating value that can last for years if not decades.</p>
<p>The way things work for search engines, now and for the foreseeable future, is that quality links pointing to your website make the domain more valuable.</p>
<p>If you publish under a domain name that's not yours, you are effectively working for other people, in exchange for something that might appear convenient for you, like a nice way to create the first page. </p>
<p>But if you take the time and put in some work beforehand to set up your own site and get your own domain, it can pay you a lot more in the future.</p>
<h2 id="heading-make-the-first-step">Make the first step</h2>
<p>The first step is always the hardest. In anything you want to do. Running. Coding. Cooking. Blogging.</p>
<p>In this chapter, I want to make sure you are well equipped for your first step when you’re ready to dive into blogging.</p>
<h3 id="heading-pick-a-domain-name">Pick a domain name</h3>
<p>There is one very important thing you need to do before you can create your blog. You need to choose a domain name.</p>
<p>You can notice 3 patterns for domain names. People have their own name/surname combination like I do with <a target="_blank" href="http://flaviocopes.com">flaviocopes.com</a>. Some people like to have a fantasy name or their nickname. Totally fine, too.</p>
<p>If it's cool and you can create a brand out of it, it's great. Like <a target="_blank" href="http://codinghorror.com">codinghorror.com</a>. Other people like to have a more general brand, like <a target="_blank" href="http://css-tricks.com">css-tricks.com</a>.</p>
<p>The good aspect of this is that people know the content of the blog just by looking at the domain. The downside is that you are kind of forced to stick to that topic forever. </p>
<p>For example, <a target="_blank" href="http://css-tricks.com">css-tricks.com</a> has long stopped talking exclusively about CSS, and other topics like JavaScript, SVG and others are very often covered.</p>
<p>This is kind of controversial, but I think your own name, or brand name with no direct attachment to anything specific, is the best and most future-proof way to create a domain name.</p>
<p>With one caveat: if you use your own name, you'll never be able to sell the site to someone else, or transform it into something "more" than just yourself with some guest posts here and there. But there are notable exceptions as well, like <a target="_blank" href="http://raywenderlich.com">raywenderlich.com</a>.</p>
<p>If you create a specific domain name that reminds people of a technology or hobby in particular, on the plus side you'll be able to sell it when it's successful to a bigger brand.</p>
<p>I started posting on my blog frequently by talking about the Go programming language. I later switched to a completely different programming language, JavaScript. </p>
<p>But because I used my own name and domain, I did not have to change anything. If I had a domain name like <em>startprogrammingingo.com</em> or something similar, there's no way I could've just switched to talking about JavaScript, or Arduino. </p>
<p>The whole project would have sunk because the day I stopped my work on Go, the site would just end its life with that very specific domain.</p>
<p>Since I use my own name for the domain, whatever I want to write about 10 or 20 years from now will be perfectly fine.</p>
<p>If you already have a domain, maybe used in old projects, and you think it can work fine, that's even better.</p>
<h3 id="heading-domain-authority">Domain Authority</h3>
<p>There's something called domain authority that is really important. Because that's how Google determines your site's value, and it's fundamental in how Google ranks web pages in its results.</p>
<p>One factor in domain authority is the domain's age. Older is more stable and more trustworthy to Google. </p>
<p>And when you're creating your domain, try to get the longest expiration date you can. That's a factor, too. Google basically detects your seriousness with the project. If your domain expires in 3 years and a competitor's in 3 days, maybe your domain is better in the long term. </p>
<p>I mean, we can't really know how the Google algorithms work, but we can try and make sure we tick all the checkboxes.</p>
<p>That can make the difference between a site that's never visited, and one that gets 10 visitors a day. Or one that gets a few hundred visits a day to one that gets tens of thousands.</p>
<h3 id="heading-choose-a-blogging-software-dont-build-it">Choose a blogging software (don't build it!)</h3>
<p>I personally use Hugo to power my blog. It is built using Go, it is very fast, and has some limitations on the things you can do. This means I can avoid distractions and I can focus on the writing.</p>
<p>I see many people, especially developers, who start creating their own blogging software from scratch.</p>
<p>I think that this a bad idea.</p>
<p>Why?</p>
<p>Because the moment you start is the time that you have the most energy. There will not be another moment in the lifetime of your blog where you'll have the same enthusiasm and drive to work on it.</p>
<p>And if you channel this energy towards something so futile, in this case, like building the software, then when it's time to actually write the content you'll have very little time, very little energy, and very little drive to craft great content.</p>
<p>Plus, you'll have to work on bugs, handle updates, and more, on your own. It's much easier to let others work on maintaining popular software used by thousands of people rather than reinventing the wheel.</p>
<h3 id="heading-choose-a-minimalistic-stock-design">Choose a minimalistic stock design</h3>
<p>The second mistake, I think, is to work on the design before working on the content.</p>
<p>Just as developers like to build their own software, design-oriented people want to create their own design. It's logical, I get it. But in this scenario, at the beginning, it's just a distraction.</p>
<p>My suggestion is: pick a stock theme, the simplest you can find.</p>
<p>The more minimal the theme is, the better.</p>
<p>Remember to keep the focus on the content. Not on the blog engine, not on the theme, not on plugins...on the content.</p>
<p>I have a couple blogs built using the default Ghost theme, which look very professional. In the niche they are built in no one knows what Ghost is – let alone do they know that it's the default theme.</p>
<p>Also, no one cares. Except you.</p>
<p>You can work on the design later on. There's always time for that.</p>
<h3 id="heading-create-the-first-3-posts">Create the first 3 posts</h3>
<p>Right after you have your blog idea, write the first 3 posts. You can write them in a normal plain text editor, and move them later to the blog platform you chose. </p>
<p>I like to use Bear (<a target="_blank" href="https://bear.app">https://bear.app</a>) to create my drafts. It autosaves, it is beautiful and intuitive to use. But it does not really matter. The thing I want you to focus on is those 3 posts.</p>
<p>Why exactly 3 posts?</p>
<p>Because now that you are so pumped to create your blog, it's the easiest time to write 3 great posts. If you create only one, maybe the second will be deferred until tomorrow, then to the day after.. and you'll be left with a blog with a single post.</p>
<p>Two posts... kinda the same. 3 posts seem like a good number to me.</p>
<p>Once you have those 3 posts, it's time to publish them. My advice, in this case, is not to publish them all together at the same time. Instead, you should schedule them.</p>
<h3 id="heading-schedule-the-first-3-posts-in-advance">Schedule the first 3 posts in advance</h3>
<p>I've had several people ask me how can I be so consistent with my blogging. The best suggestion I have is to create a habit. Habits are a very hip and popular topic nowadays, with many books published on the subject.</p>
<p>I'm not an expert, but I noticed that once a habit is established, it's really hard to break it.</p>
<p>Use this little hack to force yourself to write blog posts. Once you decide your perfect schedule (twice a week, once a week, twice a month, once a month...) then schedule the 3 posts you wrote so that you make a little buffer. </p>
<p>Suppose you write once a week. Publish the first post immediately, the second next week, the third the following week.</p>
<p>Now, you can relax and have a little party because you can launch the blog. Plus, you already have content written for the next 2 weeks and you can start planning other posts.</p>
<p>All the other posts you will write will be queued after the posts you wrote in the beginning.</p>
<p>Don't be tempted to add a new post in the middle of your planned schedule: there will be times when you can't write due to limited time, or you will have a low energy week. The buffer will be helpful to keep a consistent publishing schedule.</p>
<p>One thing that is key here is this: once the schedule gets full enough and you can look back at a long streak of posts, all very consistent in their publishing date, and you will start to feel a little pressure to not break the streak.</p>
<p>Transform this little pressure into a positive push towards staying consistent. If you have a weekly publishing routine, at the end of the year you will have 52 blog posts written, which would be a major accomplishment.</p>
<h3 id="heading-keep-going-this-way">Keep going this way</h3>
<p>If you do the things I mentioned in this chapter and you just keep going, you will have 99% more success with your blog than anyone else.</p>
<h2 id="heading-solutions-to-common-problems">Solutions to common problems</h2>
<h3 id="heading-who-am-i-to-write-about-this">Who am I to write about this?</h3>
<p>Let's say you are a student. By writing about the subject you are studying, you can reinforce your learning. Writing things down forces you to learn it really well.</p>
<p>Put your ego in chains: people don't care about you. People care about solving their problems. At least on their first point of contact with you, opinions, politics and controversial statements are detrimental to the user experience.</p>
<h3 id="heading-i-dont-know-enough-of-the-subject">I don't know enough of the subject</h3>
<p>You don't need to be an expert.</p>
<p>When I write a technical blog post, it does not really matter if I'm an expert at it. On the contrary, if I'm an expert in a field and I'm trying to write an introductory or beginner-friendly topic, I might not be able to explain that topic very well. This is because I cannot think like a beginner might when they don't know a topic, and so I might assume too many things and not explain that topic well.</p>
<p>If you're not an expert, do your best to absorb a topic and explain it to people that don't know about it. If you're an expert, on the other hand, writing content for other experts might be a good approach. Then you can mostly leave the entry-level content to people that might be in a position to explain it better.</p>
<h3 id="heading-analysis-paralysis">Analysis paralysis</h3>
<p>Just get it out there. Publishing a piece of content is much better than keeping it for months, revisiting it, thinking and thinking about it. Just do it.</p>
<p>It's ok to plan, but make sure you don't get trapped by analysis paralysis. The longer you think about it, the longer it will take you to start. Focus that energy on finding 3 good articles to write. That's the start.</p>
<h3 id="heading-dont-be-afraid-of-failing">Don't be afraid of failing</h3>
<p>Resistance is telling yourself that you are not good enough, that you will fail. This happens because you're about to do some creative work, you are about to be exposed to the public, to the opinions of others, and others will think you are not good enough.</p>
<p>Resistance is a powerful force. Especially if you write opinions or personal facts in your blog.</p>
<p>I have two suggestions.</p>
<p>The first is to talk about a topic that cannot be judged. Pick facts. No one can rant that a fact is not correct. Explain something you learned recently.</p>
<p>The second suggestion is to read <em>The War of Art</em> by Steven Pressfield, which is a mandatory read, in my opinion, for everyone trying to do creative work. It really goes into the root causes of resistance, and why you feel it.</p>
<h3 id="heading-i-am-not-good-at-writing">I am not good at writing</h3>
<p>Are you sure? Or is this just an excuse to bail out of the work that will open so many doors for you, and get back to your room?</p>
<p>This might be resistance kicking in, giving you a nice excuse for not writing.</p>
<p>Are you good at making videos, or feel great at talking to a microphone? Then make videos or start a podcast instead, but don't try to avoid any work that makes you vulnerable to the other people, just because you fear it.</p>
<p>But if you are <em>really</em> not good at writing, your writing will get better in just one way: by writing more.</p>
<h3 id="heading-i-dont-know-english-very-well">I don't know English very well</h3>
<p>If you want to write for an international audience in the western world, then you should blog in English. I highly recommend doing so, but in some cases, it might make more sense to write in your native language. </p>
<p>For example, if the niche you chose is too crowded and there's no one talking about it in your native language, then it might be an interesting opportunity to position yourself as an expert</p>
<p>If you'd like to blog in English, don't take a lack of English knowledge as an excuse. First, if you are reading this book, then it means you can read English and if you can read it, you can write it.</p>
<p>Also, unless you explicitly write for native English speakers, most of your readers might not be native English speakers, either.</p>
<p>If you are afraid your English is not good enough, and never start practicing, it will never become good.</p>
<p>My suggestion is to just start, and have someone who's really good at English review your posts, so you can learn over time.</p>
<h3 id="heading-dont-give-up-too-early">Don't give up too early</h3>
<p>Most blogs fail. This is a harsh truth. Blogs are abandoned, people forget to renew the domain name, people move on.</p>
<p>Blogs get into this situation because people gave up. They gave up on writing content consistently and frequently, because they did not see immediate gratification from doing so.</p>
<p>If you want your blog to have the chance to become successful, you have to give it the time it needs, and you need to be prepared right from the start.</p>
<h3 id="heading-dont-be-overwhelmed">Don’t be overwhelmed</h3>
<p>It's too easy to be overwhelmed by all the things you need to do. In addition to your day job and your family and friends, you need to find the time to blog. </p>
<p>But blogging is not just writing. You need to find the perfect image for that post, you need to share the post on social media, you need to reply to comments, think about future post topics, craft that perfect and eye-catching post title...the list never ends.</p>
<p>It's easy to feel overwhelmed.</p>
<p>That's why I take a minimalistic approach to blogging, which involves no pictures at all unless they're needed in the content of the post, and no comments. </p>
<p>Not having to manage comments frees up a lot of time and mental energy. It also has a nice side effect: I don't have to worry about what people think of my articles. I just focus on the writing.</p>
<h3 id="heading-one-step-at-a-time">One step at a time</h3>
<p>Don't think you have to rush and do everything at once: open the blog, write 100 posts, create a Twitter account, a Facebook page, an Instagram account, make YouTube videos… it's just too much. </p>
<p>Start with the simplest thing you can do, create a habit, make that habit stick in your day to day and expand from there.</p>
<h2 id="heading-content-is-king">Content is king</h2>
<p>Content matters. Content is the thing that matters the most, in the context of your blog.</p>
<p>Let's discuss some of the things I believe are fundamental pillars in a content-centered blog strategy.</p>
<h3 id="heading-write-to-your-people">Write to your people</h3>
<p>Let's say you are great at cooking. Write about your craft: cooking tips, ingredients, recipes, talking to other people that love cooking. Do you love knitting? Write for other knitters about techniques and everything new that you learn about knitting. Love dogs? Create a blog for dog owners.</p>
<p>Anything you do, the important thing is that you identify a group of people that are as passionate as you about a subject, and you write for them.</p>
<p>There's no value in what you write if it's not valuable to other people. Sure, you can write about something that's only appreciated by you, perhaps. But then there's no purpose in spending so much time and effort creating blog posts, is there?</p>
<h3 id="heading-focus-on-creating-value">Focus on creating value</h3>
<p>Once you identify the people you want to write to, it's key for you to focus on creating value. </p>
<p>Value can take many different forms, of course. It could be how-to posts. It could be sharing your specific experience with some technology. It could be teaching other people how your raw meat diet for your dog works. </p>
<p>It could be telling everyone about your recent trip and what you visited, in detail, so that when someone is searching for tips as they are organizing a vacation, they can find your useful information.</p>
<p>There is no fixed rule on what creates value.</p>
<p>Here's what I do to create value for the readers of my blog: I create easy-to-follow tutorials, written with a beginner's mindset. I do not take the perspective of an expert while writing them. </p>
<p>To do so, I learn a new thing, so I'm not an expert in it, and I create a practical guide. </p>
<p>I know it's very difficult as an expert to write for beginners about the thing we're expert in. This is because we've forgotten what it means to be a beginner and we make too many assumptions, forgetting to mention essential things that are key to understanding a topic.</p>
<p>Other times I describe how I fixed a problem that I just solved while working on some coding project. My memory is very fresh and I can remember what it's like to have the problem, so I can describe it very clearly.</p>
<p>Sometimes I create less practical posts where I talk about things that relate to my experience as a developer, or common struggles, or tips for productivity, for example. Those are the posts that are normally appreciated the most by my readers.</p>
<h3 id="heading-focus-on-being-useful-and-solving-problems">Focus on being useful and solving problems</h3>
<p>Your posts must solve a problem: each post on your blog must have a very specific goal.</p>
<p>This is key, and the post title must perfectly address the problem and solution.</p>
<p>When people search for how to solve that problem, you want your post to be in the top results.</p>
<p>And your content must be awesome.</p>
<p>Exactly what they are looking for.</p>
<p>Focus on creating the absolute best, most valuable content.</p>
<h3 id="heading-write-the-blog-post-that-would-have-helped-past-you">Write the blog post that would have helped past you</h3>
<p>One of my favorite things is writing a blog post that contains the solution to a problem I just solved.</p>
<p>Everyone else solves a problem and moves on.</p>
<p>If you dedicate 10 minutes to document how you solved the problem you had, you are helping other people that might have this problem next week, or next year, or 10 years from now.</p>
<p>They will be thankful that you wrote something that helped them.</p>
<p>And perhaps you can even help yourself in the future.</p>
<p>Sometimes I google for a problem and I find my own post, written many months ago. I completely forgot that I wrote it.</p>
<h3 id="heading-what-not-to-write-about">What not to write about</h3>
<p>One thing I recommend that you not write about is anything that doesn't help other people.</p>
<p>It's difficult to draw a line in the sand, but you should think about what you are writing.</p>
<p>Don't think of a blog like a diary. You <em>can</em> use it like a diary, posting your rants or opinions or what you ate for dinner.</p>
<p>But is it really helping or creating any value for other people?</p>
<p>I personally only try to write about things that I assume will help anyone. Even if a post helps just one person, then it's a good post for the blog.</p>
<h3 id="heading-teach-everything-you-know">Teach everything you know</h3>
<p>I learned this mantra, or motto, from Nathan Barry. He's famous for his book <em>Authority</em> and for being the founder of ConvertKit, a great tool for bloggers that have the need to build a newsletter.</p>
<p>He has this notion that building an audience is the secret hack to creating a successful business, and I really believe that. And to build an audience, the best way is to share, in one way or another, everything you know.</p>
<p>He did that in the form of books, first with two books about design, as that was his specialty. Then he wrote everything he learned about selling those books in another book.</p>
<p>I make my living teaching everything I know, and since there's a finite amount of things I do know at any finite point in time, I had to transition to teaching everything I learn. </p>
<p>I found that many people like the way I talk about stuff, with a very simple approach, and this beginner-oriented point of view has been beneficial to me.</p>
<p>Your approach can be different, but the “teach everything you know” mantra is one that you need to seriously think about.</p>
<h2 id="heading-practical-content-suggestions">Practical content suggestions</h2>
<p>After discussing why content matters, and why you should focus on creating great content, it's time to talk about some practical suggestions.</p>
<h3 id="heading-content-length-how-much-is-enough">Content length, how much is enough?</h3>
<p>It does not matter how long your articles are.</p>
<p>The Internet is full of marketing blogs that tell you the content must be 2000+ words long, 10000+ words long, and so on.</p>
<p>But it does not matter as long as your content solves a problem for a person.</p>
<p>I have posts that solve the problem in 50 words, and if this is the solution to someone's needs, that's great!</p>
<p>There is no need to dilute the content with useless words, and I'm sure you immediately notice when a blog post is trying to transform a 5-line answer into a 200-line one.</p>
<p>The same thing happens with videos, right? You are looking for something, but you need to watch 15 minutes of intro to get to the meat of the subject.</p>
<p>Do the opposite. Do what's great for your readers.</p>
<p>Plus, Google does not care.</p>
<h3 id="heading-keep-posts-focused">Keep posts focused</h3>
<p>When I say that Google does not care about content length, it's because I've observed this first-hand.</p>
<p>Some of my most visited blog posts are very short, yet they take a problem and they solve it, quickly.</p>
<p>And Google notices it. The key is solving a problem. Google notices that you are helping it help its users, and that's what happens when you keep your posts focused on a specific topic.</p>
<p>Some topics will perform better than others, some might be less popular, but as long as it's focused on a little problem and it solves it, it's great.</p>
<h3 id="heading-dont-try-to-appeal-to-everyone">Don't try to appeal to everyone</h3>
<p>You can't write great content for everyone. Pick your ideal person, or group of people, and write for them.</p>
<p>Pick your crowd.</p>
<p>Pick your tribe.</p>
<p>Ignore everything else.</p>
<h3 id="heading-dont-aim-for-perfection">Don't aim for perfection</h3>
<p>Done is better than perfect.</p>
<p>This is my mantra. As long as what I do is technically correct and does not have errors, it's all fine.</p>
<p>You don't need to overthink it. Focus on being good enough. That's when the point of diminishing returns starts.</p>
<p>Most of the time, good enough is already better than 95% of what's out there.</p>
<p>Don't let chasing perfection limit your production volume.</p>
<h3 id="heading-it-does-not-matter-if-someone-already-wrote-about-it">It does not matter if someone already wrote about it</h3>
<p>There are thousands of water brands. Thousands of brands of wine and beer. Thousands and thousands of hotels.</p>
<p>The more people write about a subject, the more interest there is around it, and the more people read about that subject.</p>
<p>If no one wrote about something, it might not mean you are a pioneer or “first", it might just mean no one cares about that topic.</p>
<h3 id="heading-you-dont-need-to-bring-something-new-to-the-table">You don't need to bring something new to the table</h3>
<p>If you worry that you don't have a unique spin on something, or a revolutionary idea, you might be limiting yourself.</p>
<p>Often, a 1% or 5% improvement over something that's already out there is enough.</p>
<p>Google was not the first search engine. It just worked better.</p>
<p>Basecamp was not the first project management tool. It just worked better.</p>
<p>Focus on being better, not new.</p>
<h3 id="heading-you-can-blog-about-anything">You can blog about anything</h3>
<p>I am a programmer and I blog about programming. If you’re a programmer too, you don’t just have to blog about programming.</p>
<p>There’s space for everything.</p>
<p>The topic does not matter, as long as you are passionate about it. There's no way you can force yourself to write about one subject for a long time without burning out.</p>
<p>Anywhere there’s a problem, you can bring solutions.</p>
<p>For me the niche was programming, for you it might be something else. Also, programming is even a bad niche as most developers consider even a little bit of marketing to be spam and mostly hate receiving emails (as they're using email every day and probably already receive a lot of it).</p>
<p>I think blogging, properly done, can be even more successful in less technical topics. It can work, as long as people search for those topics on the internet and have a place where you can find them like a big subreddit, a big Facebook group, or a popular online forum.</p>
<h2 id="heading-create-a-system">Create a system</h2>
<p>I am an engineer and I believe in systems. Humans are weak. Systems are strong. Humans with a system are on a good track.</p>
<p>If only we could have a system for our blog, everything would be simpler.</p>
<p>Turns out that we can definitely have a system, and in this section, I'm going to explain the system I use.</p>
<p>It might not be the perfect system for you, and I won’t pretend it’s a system that works in 100% of the cases. But it's a starting point, and by tweaking it you can create your own perfect system.</p>
<p>A system makes you consistent.</p>
<h3 id="heading-consistency-is-key">Consistency is key</h3>
<p>Why is consistency so important?</p>
<p>Because consistency is deeply entrenched in our lizard brains.</p>
<p>You are the one that makes one blog post every Tuesday. You're not the one that <em>tries</em> to write a blog post consistently each week. You're the one that just <em>does</em>.</p>
<p>It's not me, Flavio, saying so.</p>
<p>Let me share something from Robert Cialdini, author of the amazing book <em>Influence</em>: </p>
<blockquote>
<p><em>Once we have made a choice [...] we will encounter personal and interpersonal pressures to behave consistently with that behavior</em>.</p>
</blockquote>
<p>Once you have a series of 5, 10, 20 weeks of posting, you automatically become the one that posts every week. Or twice a week, or whatever schedule you chose.</p>
<p>That's the key to the system: consistency.</p>
<p>Have you ever heard of Rand Fishkin's Whiteboard Friday? That was a great video series about SEO that came out every Friday. Do you know about FunFunFunction? MPJ releases one video every Monday. Every one of his fans knows and waits for his "good Monday morning" every week. </p>
<p>I’m sure you know YouTubers that post on a pre-determined day. Like Saturday or Tuesday.</p>
<p>Everyone can find the time to create a blog post every week. But not everyone is willing to put in the work to create something every week. Will you?</p>
<h3 id="heading-schedule-posts-ahead-of-time">Schedule posts ahead of time</h3>
<p>As we just discussed, the single best thing you can do with your blog is stay consistent.</p>
<p>But staying consistent is hard.</p>
<p>One of the easiest ways to become inconsistent is to miss a day because you were sick, or because you went to a party, or because you took a vacation.</p>
<p>When you miss a day, and you forgive yourself for this, you will miss other days.</p>
<p>That's what I would do. If I let one day slip by without a post, well… nothing bad happens and I have a track record of missing one post.</p>
<p>Before I realize it, I am sure I will miss other posts, too. Just because I was too lazy one day, I ruined the consistency of my blog and now it's impossible to get that perfect streak of posts back.</p>
<p>How do you prevent that? By scheduling posts ahead of time.</p>
<p>Before you start publishing your blog, before unveiling it to the world and announcing it everyone, write 3 posts as we discussed before, and start building up your queue.</p>
<h3 id="heading-have-a-queue">Have a queue</h3>
<p>When I first started my blog, I discovered the notion of creating a queue by accident.</p>
<p>I happened to work on another project of mine, one that didn't take off as I expected it to.</p>
<p>This project involved creating some long guides, about topics I cared about.</p>
<p>So when I decided to shut down the project, I thought that it was a shame to abandon those long guides to their unknown fate.</p>
<p>So I cut each chapter into several blog posts, and I got about 15-20 of them.</p>
<p>I could have published them all on that day, but I randomly decided to queue them up. One today, one tomorrow, and so on.</p>
<p>A couple of days after that, I had an idea for a new post. I was a blogger now, right? And I queued it after all those posts.</p>
<p>The queue has never dried up since then, over 700 days ago. Some days I reached the end of the queue and I had to fill it up again from zero, but I never missed a day.</p>
<p>I just attribute this result to the system – the queue I've built up, and the shame that would result from having written all those posts in the past and then stopping.</p>
<p>I could not stop.</p>
<h3 id="heading-pick-a-schedule-frequency-you-can-sustain-over-the-long-run">Pick a schedule frequency you can sustain over the long run</h3>
<p>One key part of this scheduling and queuing system is frequency.</p>
<p>How frequently should you post?</p>
<p>My recommendation is to post with a frequency you can maintain over time, consistently.</p>
<p>Start with one day per week. Create a queue, as I suggested, and see if you can maintain this frequency over 2-3 months. Once you start having a queue that's too long, say a blog post you write today will be published 3 months from now, then you can start increasing the frequency.</p>
<p>It's always best to scale up the frequency than to post less frequently because you can't sustain the frequency you initially set.</p>
<p>The reason I focus a lot on consistency and frequency is that people get used to it and they learn to expect a post from you, and they look for it.</p>
<p>If you start missing posts and not sharing information as frequently, then people don't know when to expect a new post from you, and they feel lost and disconnected.</p>
<p>This happens with everything. I notice it with videos.</p>
<p>If you watch YouTube videos frequently, what do you think when a YouTuber that posts every day, and you watch every day, suddenly stops posting for a week?</p>
<p>I subscribe to a YouTuber that posts every Saturday, and every Saturday, unless I am out doing something, I'm there, at noon, watching his video.</p>
<h3 id="heading-ignore-quantity">Ignore quantity</h3>
<p>If you know beforehand that you have 3 hours a week to dedicate to blogging, don't force yourself to create too many posts.</p>
<p>Do one post a week, but do it well. Don't create many posts that are irrelevant or low quality, create one that you can be proud of.</p>
<p>Quality is perceived, and people will associate your worth with the quality of your work.</p>
<p>Be known for creating high quality and helpful content.</p>
<h3 id="heading-focus-on-the-process-not-the-outcome">Focus on the process, not the outcome</h3>
<p>One recommendation I have to be productive is to focus on the process.</p>
<p>I am focused on creating the blog post.</p>
<p>I am focused on creating ebooks.</p>
<p>I am not focused on how many people will read the blog post, or if they will like it.</p>
<p>That's not something I have control over. The best thing I can do is focus on my work and make sure it is the best work I can perform today.</p>
<h3 id="heading-keep-the-process-lean">Keep the process lean</h3>
<p>When thinking about my process, I like to simplify it.</p>
<p>I want to remove all the friction I can remove.</p>
<p>It all needs to be simple, fast, streamlined.</p>
<p>I don't want roadblocks.</p>
<p>I try my best to remove all the resistance and all that powers resistance.</p>
<p>There should be nothing between me and writing a great blog post.</p>
<h3 id="heading-keep-a-list-of-topics">Keep a list of topics</h3>
<p>I don't always have the time to write about something.</p>
<p>Sometimes I have an idea for a topic, and I write down the title of the article in my favorite writing application.</p>
<p>When it's time to write a new blog post, and I don't have an idea ready, I go through the list of titles and find one that is appealing to me in that specific moment.</p>
<h3 id="heading-capitalize-high-energy-days">Capitalize high energy days</h3>
<p>Some days I have really high energy for writing blog posts. Some days I have very little, if any, energy.</p>
<p>On those days when I have the fire, I can write a few blog posts in a row and code the rest of the day (as that's my job). I have fuel for everything.</p>
<p>I capitalize on those days. I sit there and I might write 5 posts, and put them in the queue.</p>
<p>The days I have low energy I am thankful for those high energy days and I am thankful that I did everything I could to get the most out of them.</p>
<h2 id="heading-how-to-get-people-to-your-blog">How to get people to your blog</h2>
<p>Having a blog is great and all, but having a blog that people actually read is deeply satisfying.</p>
<p>There’s a problem though: how do you get people to read your blog?</p>
<h3 id="heading-how-blog-traffic-works">How Blog Traffic Works</h3>
<p>In today's world, if you are not producing valuable and consistent content, you are invisible. There are just too many things pushed at us every day.</p>
<p>I dedicate from 30 minutes to 1 hour every day to the Internet. That means Social Media, mostly Twitter, RSS and content aggregators.</p>
<p>I always see the same people. Those people that are highly successful keep pushing out great content.</p>
<p>It might be an inspiring tweet, a great blog post that's shared a lot, or something that's just worth reading.</p>
<p>Unless you perform at the same level, you are not appearing in my feed because I only give it limited time. And I assume the vast majority of people do the same. People don't just spend the whole day on social media waiting for you.</p>
<h3 id="heading-share-your-work-where-the-people-are">Share your work where the people are</h3>
<p>Sharing your content is a great motivator especially when your blog is young and you don't have an audience yet (more on this later).</p>
<p>In this situation, you can't rely on organic traffic. To avoid losing motivation, it's key to get your first views by sharing your content. </p>
<p>You can do 2 things: share it with your own audience on social media, if you have an audience already, or use sites that provide an audience and try your luck.</p>
<p>Those sites include Reddit, Hacker News, Medium, and forums that specialize in the topic you are talking about. Word of caution: you might have your feelings hurt in some of those venues, so just be prepared for criticism.</p>
<h3 id="heading-organic-growth-is-the-only-reliable-solution-for-long-term-traffic">Organic growth is the only reliable solution for long term traffic</h3>
<p>You might have the proverbial lucky day, and your blog post goes viral in places like Reddit, Hacker News, or on Social Media.</p>
<p>But the key factor for your blog is organic traffic.</p>
<p>Organic traffic means Google will receive a search from a user and will decide that it should show them your blog post.</p>
<p>Organic traffic is a key factor to every website. Social media traffic is generally low quality, hard to get, and hard to maintain over time.</p>
<p>This is a long process. Google needs to trust you, and it can take some time.</p>
<p>My best suggestion to give Google a reason to show your blog posts is to consistently solve people’s problems.</p>
<h3 id="heading-solve-peoples-problems">Solve people’s problems</h3>
<p>How do you get Google (and other search engines) to send loads of traffic to your website?</p>
<p>What matters to Google is that it satisfies its own users.</p>
<p>And those are people searching.</p>
<p>People search in order to solve their own problems.</p>
<p>I see SEO people who suggest that you write 3000+ posts to rank on Google.</p>
<p>That’s a great tip if their goal is to discourage you from writing more. They call it long-form content.</p>
<p>Now, as a non-SEO person, but as a person that does things and observes what works and what doesn’t, I can say that if you solve a problem for a person with a 4-line blog post, Google will thank you by sending you more people who have that problem.</p>
<p>They know using their algorithms when a person found the answer they needed. This is Google’s job. Their job is to solve people’s problems by providing the perfect content they are looking for.</p>
<p>If you can provide that, Google will help you.</p>
<p>Not every post on your blog can solve a problem, of course. But if you have posts that solve problems, you’ll start to notice, as those are the posts that will get the most visitors.</p>
<p>Not every post must be small of course, and if long-form content is best for you, do that.</p>
<h3 id="heading-the-importance-of-links">The importance of links</h3>
<p>When we were talking before about choosing a good domain name, I mentioned domain authority. I said that an old domain name will likely have more domain authority.</p>
<p>What is domain authority?</p>
<p>Domain authority is a sort of score that search engines use to set the importance of a website, and it's determined by many different factors. The specific algorithms and metrics used are not publicly available, but there's one thing which is key to domain authority: links.</p>
<p>The more links to it that a website has, the more authority it has. But it's not that simple. The more authority the domain has that the link comes from, the more important the link is.</p>
<p>Links have very different weights. A link coming from Wikipedia has more power than a link from a random tweet. And search engines do take social metrics into consideration, too. We can't know for sure, but a link in a tweet from an influencer in your field has more weight than a tweet from a Twitter bot account.</p>
<p>Google (I say Google because it's the most important search engine, but others might do a similar thing) is also careful about the topic. If I link to a kitchen recipe site from my computer programming blog, that link is not going to have much value. </p>
<p>If a famous kitchen recipe blog links to a smaller kitchen recipe blog, then that's more relevant for Google, and it will give that link more meaning.</p>
<p>When it comes to links, it's important to get links from relevant and on-topic websites.</p>
<p>This is only something you can get by providing great and useful content.</p>
<h2 id="heading-expand-your-reach-with-an-email-list">Expand your reach with an email list</h2>
<p>Let’s discuss how to augment the experience you create for your blog visitors by using an email list.</p>
<h3 id="heading-what-is-an-email-list">What is an email list?</h3>
<p>Blogs are closely linked to newsletters and email lists. The two often go hand in hand.</p>
<p>A newsletter is the most effective way you can get in touch with your blog readers over time.</p>
<p>If you are not already familiar with the email list concept, you may be wondering whether in the era of Facebook, Instagram, Snapchat, and Twitter if you still need to use an old-style system like email.</p>
<p>In fact, email is a fundamental tool for any online business. Blogs are no exception.</p>
<p>Sending emails to a list of customers is not a system by which people commonly spam, as you might be thinking.</p>
<p>Especially if you're a developer, you need to realize that email is useful, you are not evil for sending emails, and that people want to hear from you.</p>
<p>Email is a cool system where people interested in your content or products can have more information about them, or about new products that you could provide in the future.</p>
<p>Email marketing is one of the most effective systems with which people are converted over time from visitors to customers: people in your list have explicitly asked to receive more information from you in the future.</p>
<p>This does not mean sending an email after 8 months asking them to buy your new product. Instead, the right way to approach this is to ask yourself how you can help your customers, in a consistent way.</p>
<p>Through the list, over time you can build customer loyalty, you create a relationship, and you keep in touch.</p>
<p>Your task with the list is to train people on the subject you are talking about, and to foster anticipation about upcoming news. But try to keep the focus on the customer rather than on you. Remember that a person will not be on your list forever – just as long as you can keep interest high.</p>
<p>So how do you get a person to join your email list in the first place?</p>
<p>With a small gift, called the lead magnet, which can be for example a report, a free ebook, exclusive access to premium content, an email course, or really any gift you can make.</p>
<p>The concept is simple, but it is crucial that the gears that make up this mechanism are calibrated to perfection and oiled regularly. Don't leave anything to chance if you do not want to be amateurish in the eyes of your customers.</p>
<p>It’s fundamental that you offer people what they want. The email list is considered by most online business owners as the most important asset of a business, and the only one that really is 100% yours.</p>
<h3 id="heading-a-typical-use-of-an-email-list">A typical use of an email list</h3>
<p>Let's look at an example. This is the system that most successful blogs use: </p>
<p>a person reaches your site coming from search engines or Facebook. Then a popup appears (more or less invasive) with the request that they enter their email to get a small gift. Then you’ll send them the gift via email, and the person enters this cycle where they will be offered a variety of products over time.</p>
<p>Usually, when a person gets on your list, they enter a phase called the <em>funnel</em>. The funnel is an automated process of warming, that is, the person get "heated" and is brought from being a random visitor to becoming a possible customer via a series of emails.</p>
<p>As soon as the person signs up, they will receive an email. The next day they will receive another, after 3 days another one, all according to predetermined logic. </p>
<p>Typically, these e-mail series terminate after 7-8 mails where a story is told and in the end, they will be offered a product to purchase. If the person doesn't buy right away, emails will continue to flow, and so on until the automated sequence ends.</p>
<p>There are many kinds of different sequence types and usually people do not invent anything new. Instead they use well-tested systems (which you can easily recognize once you are trained).</p>
<p>Once this sequence is over, the person's email is placed in another sequence, or in the general list, which is no longer automated. Then, the person managing the list (you, for example), will send an update email from time to time, say once a month, to make sure the person don’t forget about them.</p>
<p>In short, the author of the list tries to sell a product but if the recipient does not buy it, they will still remain in the list until they cancel the subscription. Because you never know – in the future they could decide to buy and become a customer.</p>
<h3 id="heading-how-to-use-an-email-list">How to use an email list</h3>
<p>Of course, there are several approaches to the list. Let's see some situations that you could apply in your case.</p>
<p>If you sell an ebook: your users are therefore your readers. You could add a link to your site, and use as a lead magnet a free ebook on a topic that you know the user is interested in. </p>
<p>On the list, you could initially present an upsell of other ebooks you've already written. Then you could insert the person into your monthly email, where you'll publish interesting links to the topic, and from time to time promote your new ebooks.</p>
<p>If you sell a product: for an info-product, it's the same process as a typical example used on blogs. Maybe as a lead magnet you use one or more chapters, or you have a video or something else related to the subject.</p>
<p>If you have a software product: the list could be made up of all the people who bought your software if you sell to them directly, which gets you their emails. Or you may want them to sign up for your application. </p>
<p>You could use the list to share updates, inform about the latest releases, cross-promote with other developers, and raise awareness on new products you’ll build over time.</p>
<h3 id="heading-where-to-host-your-email-list">Where to host your email list</h3>
<p>To manage an email list you need a specialized software.</p>
<p>There are many different kinds of email newsletter management tools.</p>
<p>Some are simple. Some are way too complex for your needs. You just need to find the perfect one for you.</p>
<p>The first separation I want to make is between self-hosted software and SAAS. Sendy (<a target="_blank" href="https://sendy.co">https://sendy.co</a>) is an example of a self-hosted software. You don't pay a monthly fee to use it, but you have to manage your own server, and you use a service, typically AWS, to actually send the emails.</p>
<p>ConvertKit is an example of a tool that is SAAS based. You pay them a monthly fee, and they take care of everything.</p>
<p>That tool, in particular, is targeted at bloggers, and it's really well made. I have used it for almost 2 years, and it's really great.</p>
<p>I have recently moved to Sendy, self-hosting my newsletter, because at some point the price, for me, was not sustainable.</p>
<p>To start with, I would definitely recommend ConvertKit. You don't need to overthink spending $29 or $49 a month if that's valuable to you.</p>
<p>But my list became big enough and I was not comfortable spending a lot of money on my email list hosting software.</p>
<p>And it's a business tool: I know several top-performing bloggers with great audiences that use it for lists in the hundreds of thousands, and I'm sure that the ROI (Return on Investment) is well worth not having to manage your own server.</p>
<p>Especially if you are new to managing servers.</p>
<p>ConvertKit is not the only service, of course. There's Mailchimp, Drip, and others.</p>
<p>Some tools let you start free. I think of TinyLetter (https://tinyletter.com/). That's what I started with, in the beginning, until I reached a few hundred subscribers. Then I moved to a tool called ButtonDown and I went from there.</p>
<h3 id="heading-keep-it-alive">Keep it alive</h3>
<p>As with blog posts frequency and consistency, the best advice I can give about mailing lists is to keep them consistent.</p>
<p>Do you write every 2 weeks? Fine. Keep doing it.</p>
<p>Do you write every month? Fine. Keep doing it.</p>
<p>The exact frequency is really personal. Some people write a new email for every post they make on their blog.</p>
<p>Some people email once a month with the list of posts. If you write once a month, however, people might forget who you are. This happened to me: I might subscribe to a newsletter and forget about it if you don't email me quite frequently.</p>
<p>Since I write one post per day, I found my sweet spot at one email every week, on Tuesday, and I always respect this frequency.</p>
<p>People know that Tuesday is "email from me" day.</p>
<h3 id="heading-the-lead-magnet">The lead magnet</h3>
<p>We discussed how having a newsletter is essential. It's also essential to have people signed up for it.</p>
<p>How can you have people decide to give a thing so precious as their email address to you?</p>
<p>The best way I know is to give them something in return. Don't expect people to sign up without a clear gain for them</p>
<p>You need to give an incentive to people to sign up for your newsletter.</p>
<p>This is the lead magnet that we discussed briefly earlier.</p>
<p>It can be a 1-page PDF cheat sheet. A report. A short mini-course of 10 videos. An email-based course.</p>
<p>The sky is the limit when it comes to what the lead magnet should be.</p>
<p>And there is no reason you should only have one lead magnet. You can have multiple.</p>
<p>In the ideal case, every blog post should have a specific lead magnet, but this is of course not always possible. I tend to create a lead magnet for each category of posts I'm writing.</p>
<h3 id="heading-how-i-discovered-lead-magnets">How I discovered lead magnets</h3>
<p>At the beginning of my blogging adventure (a little more than 2 years ago), my blog had zero traffic and Google ignored me.</p>
<p>I shared my posts on Reddit, and some people came and saw the site. I shared my posts on Twitter, where I had like 500 followers, many of them probably bots or inactive followers that I had collected in the 10 years I had been on Twitter.</p>
<p>If I had 10 or 15 visits a day, that was a good day.</p>
<p>After a while, I decided to create a newsletter, with a simple promise: every 2 weeks I'd send you links to all the posts I published. Like everyone does. That was good to get an email subscriber every other day, but that was it.</p>
<p>After some months, traffic grew a little and I was getting 4-5 subscribers every day. This was better.</p>
<p>Then I realized that people will not subscribe to a newsletter if they don't gain an advantage from that. This is a key point. I rarely subscribe to a newsletter just to “stay in touch”. Sometimes I do, and when this happens to you, that’s a quality email subscriber. Someone that really wants to hear from you.</p>
<p>But to get to this level requires people to have received a lot of value from you already, in one way or another. Maybe they already subscribe to your YouTube videos or your podcast. It’s hard for a complete stranger to subscribe.</p>
<p>So I changed my strategy from asking to "Join my newsletter" to offering people something of value. This lets the conversation begin with me offering a valuable asset.</p>
<p>In my case, the valuable asset, in the beginning, was a little PDF with a collection of the best blog posts I had written on a subject, nicely organized as an ebook. </p>
<p>Most people coming to my blog didn’t read more than one page, so I thought that creating a nice little ebook was a good way to show them what I had to offer. This increased signups a lot.</p>
<h2 id="heading-ups-and-downs">Ups and downs</h2>
<p>Having a blog is not all fun and games. There are many things that might give you a hard time on your journey.</p>
<p>Realizing this is a first step in the right direction.</p>
<h3 id="heading-writers-block">Writer's block</h3>
<p>Writer's block is a thing. I have no general advice on this, and whole books were written on the subject so there's a lot of better advice out there than what I could come up with.</p>
<p>My solution when it comes to not knowing what to write about is to pick a subject I want to learn, and start learning it in public. Right as I write this, I am learning a completely new thing (Arduino and electronics sensors) while re-discovering the old electronics topics I studied back in school.</p>
<p>I am shooting videos while I learn this thing, and writing blog posts on the topics that are better suited for blog posts (no, I'm not limiting myself to blogging, I also like doing videos).</p>
<p>If a topic is boring to me, I just don't write about it because if I'm bored writing, I will write a boring article. So I try to write about things I'm interested in and excited about.</p>
<h3 id="heading-imposter-syndrome">Imposter syndrome</h3>
<p>Every person, sooner or later, is going to suffer from this thing which we label <em>imposter syndrome.</em> You might have this feeling now, but you don’t know that it has a name attached.</p>
<p>Let me describe some situations where you might find imposter syndrome in the wild.</p>
<p>You are a developer, have no Computer Science degree, and you feel people that have the CS degree know a lot more than you, and you should get one too in order to be called a developer.</p>
<p>You work on a project and you call it a little side project, not a real project, because – you know – it’s just a simple app.</p>
<p>You constantly belittle yourself, and have low confidence in your abilities.</p>
<p>You think other developers know a lot more than you do.</p>
<p>You think someday someone will find out that you are not worth your job position, as you can’t solve the coding interview quiz #423 from a random book.</p>
<p>You think you don’t belong to the <em>coder’s club.</em></p>
<p>In the case of blogging, you’d like to start blogging but you fear other’s opinions and even think that you can’t add anything new to the table, so you don’t even start.</p>
<p>What's the solution to this problem?</p>
<p>I don't know if it applies to you, but when I start to feel this way, I try to put myself in the learner's shoes. I am not teaching. I am learning in public. Most of the time.</p>
<p>If this is not enough, realize how far you have come from where you started. Look back. There was a day when you could not even figure out how to start the computer. What code even was. You didn’t know you could actually create programs and make the computer do what you want.</p>
<p>Look at you now. You are the best version of yourself and yet you can be perfectly sure that tomorrow you’ll be an even better version. You are improving. Just like your blog posts.</p>
<h3 id="heading-working-in-public">Working in public</h3>
<p>Working in public can be nerve-wracking. Well, it <em>is</em> for me. You don't really know who is watching your work, and what they really think of it.</p>
<p>You're one step away from an intolerant expert judging your work as not relevant.</p>
<p>And maybe the creator of a library is looking at your tutorial on it, thinking you didn't get it right.</p>
<p>But looking at the opposite side of the spectrum, by learning in public you are forced to grow.</p>
<p>Step up the game.</p>
<p>You need to put a lot of effort to make your work great in the eyes of a lot of people.</p>
<h3 id="heading-burnout">Burnout</h3>
<p>It's easy to feel overwhelmed by all the things you are doing. Thinking about new content, writing the actual content, writing guest posts, trying to promote the content as much as you can – but without being spammy, and replying to comments and feedback.</p>
<p>This is not unique to blogging, of course. I have seen this even more in the YouTube space. There, it's even worse to me. You are putting your face and voice in front of a lot of people, instead of just your words and pictures like in a blog post.</p>
<p>My best advice to avoid burnout is to choose a minimalistic approach and to pick a topic that deeply interests you.</p>
<p>If you write about things you are passionate about, you will never have a shortage of things to write about. Your list will be 3 miles long.</p>
<p>Choosing a minimalistic approach means that you have to cut down anything that's not essential. I do not have comments on my blog. I need to care less about what people <em>think</em>, which has the drawback of creating less community, but also has the positive of causing me less stress.</p>
<p>Also, I do not generally promote the content I write on social media or other outlets, except if it is a special article that I really want to be seen, and I do not usually write guest posts on other blogs.</p>
<p>Such activities can be limited once the blog is up and running and you get a fair share of visits every day. So with the increase of views and stress given by many people looking at your work every day, you get the benefit of focus.</p>
<h3 id="heading-lower-your-expectations">Lower your expectations</h3>
<p>If you keep your expectations low, you will never be deluded. Don't expect your blog to be an overnight success. It will not happen. Just like it does not happen with a YouTube channel or a podcast. It's hard. Except for some lucky ones, maybe.</p>
<p>This is why blogging about things you are passionate about is beneficial. If you write about things you always wanted to write about, and will even write if no one is reading, then you are on the right track.</p>
<p>Then if success will ever come to you, you'll be more than ready for it.</p>
<h3 id="heading-trolls-and-negative-feedback">Trolls and negative feedback</h3>
<p>The Internet can be a wild place, and I am sure I don't have to explain this to you. When people write comments online, they can be mean. Sometimes. Most of the time they are not. </p>
<p>I do not have comments on my blog directly, but I do receive feedback via email and on Twitter. And on YouTube videos.</p>
<p>And the rare day I get one blog post featured on Reddit or Hacker News, two sites relevant for my content, I get very stressed about looking at comments.</p>
<p>It must be me, and most of the times comments are wildly positive, which is great. But I heard somewhere that our brain is much more receptive to negative feedback, and I can certainly confirm that I remember bad feedback more than positive feedback. It can take 10 positive comments to make up for a single negative one.</p>
<p>I might be over-sensitive but removing comments altogether from my blog removed the handbrake. I do not have to worry if some content does not resonate with people.</p>
<p>I wrote it, it's like that, I did my best to make sure it's "correct" to my best judgment, and I am off to the next one.</p>
<p>Your mileage might vary.</p>
<h3 id="heading-ignore-vanity-metrics">Ignore vanity metrics</h3>
<p>I have the incredible experience of having enough visitors to be surprised every day of the number of people visiting the blog. </p>
<p>I open Google Analytics at a random point in time during the day and I see the number of people. Then I get back to whatever I was doing. It's kind of addictive, but also useless.</p>
<p>Does that affect my day? No.</p>
<p>Does that change what I'm going to do next? No.</p>
<p>Same for email subscribers. Does it really matter how many people are on the list? No.</p>
<p>What matters the most is that people resonate with your ideas and learn from your work.</p>
<p>Even if it is just a handful of people.</p>
<p>The rest is useless.</p>
<h3 id="heading-blogging-is-lonely">Blogging is lonely</h3>
<p>Blogging is lonely, in the same way that writing a book is lonely. Also working in your secret laboratory is lonely. Being a YouTuber is lonely. Being a remote freelancer is lonely.</p>
<p>There's not much of a solution for this.</p>
<p>Other than accept it, and realize that some people might be more happy to be lonely. I am definitely an introvert and I thrive in a lonely environment, spending days in the silence.</p>
<p>That's probably why I like blogging.</p>
<h3 id="heading-it-takes-time">It takes time</h3>
<p>Let's say it out loud: it's going to take a lot of time. There is no way that your blog will be an overnight success. It will take many months and possibly years before you will see a rising tide of visitors to your blog. Maybe. If you did it alright.</p>
<p>This is a harsh truth, but it's one I think is necessary because I don't want you to believe that success is easy to achieve, and I want to set the right expectations. Time, persistence, showing up every day. This is what it takes, for any kind of success in any kind of activity.</p>
<p>It's a long game, but one that will eventually give you a lot of satisfaction.</p>
<h2 id="heading-making-money-with-a-blog">Making money with a blog</h2>
<p>A blog can be a great launch point for various projects that can make you money.</p>
<p>There’s absolutely no need for your blog to make money if you don’t want it to. But it’s good to know what your options are. In this last chapter, I’m going to explain at a high level the main options for “monetizing” a blog.</p>
<h3 id="heading-get-more-clients-for-your-business">Get more clients for your business</h3>
<p>The first and easiest way, I'd say, is to offer your services.</p>
<p>This especially works with non-location specific services. For example, if you are a plumber it might be harder. Not impossible, especially in large cities, but other channels could work better.</p>
<p>But if your business or activity is not linked to a specific location, a blog can be a great promotion for your business.</p>
<p>You can write articles that position you as an expert in the field you work in, and people will get in touch using the tools you give them: email, chat, or whatever you want.</p>
<p>I’ve seen this applied countless times, and it can lead to big opportunities in consulting. I have also experimented this first-hand when I started my career.</p>
<h3 id="heading-advertising-affiliates-and-sponsors">Advertising, affiliates, and sponsors</h3>
<p>When your blog starts to gain a consistent number of visitors, that’s when it can make you some money in what’s usually called “passive income”.</p>
<p>There are 3 ways, mostly: advertising, affiliates, and sponsors. This is the difference: advertising is banner or text ads that appear on your page. You typically add a code to the site and then forget about it.</p>
<p>There is a broker, like Google Ads or Mediavine or BuySellAds that will take care of everything for you. They'll find companies that want to show their ads, and their ads will be displayed on your blog. You get paid by ad views and/or ad clicks. It’s the simplest method you can find, although it usually requires a high number of page views to work.</p>
<p>Affiliates work in a different way: you get paid when people purchase a product coming from a link put on your website. </p>
<p>A common affiliate system is Amazon affiliate links. I’m sure you’ve seen them everywhere, under YouTube videos, under Instagram posts, and so on. </p>
<p>When Amazon makes a sale, you get a percentage of that. Same works for other smaller affiliate programs. </p>
<p>For affiliate links, you need to generate a specific link and depending on the frequency you have to do that, and the number of products or programs you promote, it will require more work on your part.</p>
<p>Sponsors work in a different way, and you typically need to get in touch with companies via email or phone. They will usually pay a flat fee for a month (or more) of sponsoring. You typically need to put a banner on the site or talk about their products in your posts.</p>
<h3 id="heading-selling-your-own-products">Selling your own products</h3>
<p>The system I like the most is using the blog to promote your own products.</p>
<p>It’s similar to promoting your services, but with products, it requires less work on your part and it can scale very easily.</p>
<p>Sure, you need a product beforehand. And you need a product that you know will be relevant and useful to people who read your posts.</p>
<p>But once you have it, you can promote it to your readers, without paying for ads, and without having to run an affiliate program yourself. Then, all your work – your blog and your products – are all aligned in the same direction: making useful things for the people you want to interact with.</p>
<h2 id="heading-final-words">Final words</h2>
<p>I hope this book was useful to you, and I really hope it might be the inspiration you need to create your own blog.</p>
<p><a target="_blank" href="https://flaviocopes.com/page/book-blog/">Download a PDF and ePub version of the <strong>How to Start a Blog</strong> book here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Python Handbook – Learn Python for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ The Python Handbook follows the 80/20 rule: learn 80% of the topic in 20% of the time. I find this approach gives a well-rounded overview.  This book does not try to cover everything under the sun related to Python. It focuses on the core of the lang... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-python-handbook/</link>
                <guid isPermaLink="false">66bb5ab8b6e566d0c2aea612</guid>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ learn to code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ python developer ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Flavio Copes ]]>
                </dc:creator>
                <pubDate>Wed, 10 Mar 2021 22:51:03 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/03/book.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The Python Handbook follows the 80/20 rule: learn 80% of the topic in 20% of the time.</p>
<p>I find this approach gives a well-rounded overview. </p>
<p>This book does not try to cover everything under the sun related to Python. It focuses on the core of the language, trying to simplify the more complex topics. </p>
<p>I hope the contents of this book will help you achieve what you want: <strong>learn the basics of Python</strong>.</p>
<blockquote>
<p>Note: You can <a target="_blank" href="https://flaviocopes.com/page/python-handbook/">get a PDF, ePub and Mobi version of this Python Handbook</a></p>
</blockquote>
<p>Enjoy!</p>
<h2 id="heading-summary">Summary</h2>
<ul>
<li><a class="post-section-overview" href="#heading-introduction-to-python">Introduction to Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-install-python">How to Install Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-run-python-programs">How to Run Python Programs</a></li>
<li><a class="post-section-overview" href="#heading-python-2-vs-python-3">Python 2 vs Python 3</a></li>
<li><a class="post-section-overview" href="#heading-python-basics">Python Basics</a></li>
<li><a class="post-section-overview" href="#heading-data-types-in-python">Data Types in Python</a></li>
<li><a class="post-section-overview" href="#operators">Operators in Python</a></li>
<li><a class="post-section-overview" href="#heading-the-ternary-operator-in-python">The Ternary Operator in Python</a></li>
<li><a class="post-section-overview" href="#heading-strings-in-python">Strings in Python</a></li>
<li><a class="post-section-overview" href="#heading-booleans-in-python">Booleans in Python</a></li>
<li><a class="post-section-overview" href="#heading-numbers-in-python">Numbers in Python</a></li>
<li><a class="post-section-overview" href="#heading-constants-in-python">Constants in Python</a></li>
<li><a class="post-section-overview" href="#heading-enums-in-python">Enums in Python</a></li>
<li><a class="post-section-overview" href="#heading-user-input-in-python">User Input in Python</a></li>
<li><a class="post-section-overview" href="#heading-control-statements-in-python">Control Statements in Python</a></li>
<li><a class="post-section-overview" href="#heading-lists-in-python">Lists in Python</a></li>
<li><a class="post-section-overview" href="#heading-tuples-in-python">Tuples in Python</a></li>
<li><a class="post-section-overview" href="#heading-dictionaries-in-python">Dictionaries in Python</a></li>
<li><a class="post-section-overview" href="#heading-sets-in-python">Sets in Python</a></li>
<li><a class="post-section-overview" href="#heading-functions-in-python">Functions in Python</a></li>
<li><a class="post-section-overview" href="#heading-objects-in-python">Objects in Python</a></li>
<li><a class="post-section-overview" href="#heading-loops-in-python">Loops in Python</a></li>
<li><a class="post-section-overview" href="#heading-classes-in-python">Classes in Python</a></li>
<li><a class="post-section-overview" href="#heading-modules-in-python">Modules in Python</a></li>
<li><a class="post-section-overview" href="#heading-the-python-standard-library">The Python Standard Library</a></li>
<li><a class="post-section-overview" href="#heading-the-pep8-python-style-guide">The PEP8 Python Style Guide</a></li>
<li><a class="post-section-overview" href="#heading-debugging-in-python">Debugging in Python</a></li>
<li><a class="post-section-overview" href="#heading-variable-scope-in-python">Variable Scope in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-accept-arguments-from-the-command-line-in-python">How to Accept Arguments from the Command Line in Python</a></li>
<li><a class="post-section-overview" href="#heading-lambda-functions-in-python">Lambda Functions in Python</a></li>
<li><a class="post-section-overview" href="#heading-recursion-in-python">Recursion in Python</a></li>
<li><a class="post-section-overview" href="#heading-nested-functions-in-python">Nested Functions in Python</a></li>
<li><a class="post-section-overview" href="#heading-closures-in-python">Closures in Python</a></li>
<li><a class="post-section-overview" href="#heading-decorators-in-python">Decorators in Python</a></li>
<li><a class="post-section-overview" href="#heading-docstrings-in-python">Docstrings in Python</a></li>
<li><a class="post-section-overview" href="#heading-introspection-in-python">Introspection in Python</a></li>
<li><a class="post-section-overview" href="#heading-annotations-in-python">Annotations in Python</a></li>
<li><a class="post-section-overview" href="#heading-exceptions-in-python">Exceptions in Python</a></li>
<li><a class="post-section-overview" href="#heading-the-with-statement-in-python">The with Statement in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-install-3rd-party-packages-in-python-using-pip">How to Install 3rd Party Packages in Python Using pip</a></li>
<li><a class="post-section-overview" href="#heading-list-comprehensions-in-python">List Comprehensions in Python</a></li>
<li><a class="post-section-overview" href="#heading-polymorphism-in-python">Polymorphism in Python</a></li>
<li><a class="post-section-overview" href="#heading-operator-overloading-in-python">Operator Overloading in Python</a></li>
<li><a class="post-section-overview" href="#heading-virtual-environments-in-python">Virtual Environments in Python</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-introduction-to-python">Introduction to Python</h2>
<p>Python is literally eating the programming world. It is growing in popularity and usage in ways that are pretty much unprecedented in the history of computers.</p>
<p>Python excels in a wide variety of scenarios – <strong>Shell scripting</strong>, <strong>task automation</strong>, and <strong>Web development</strong> are just some basic examples.</p>
<p>Python is the language of choice for <strong>data analysis</strong> and <strong>machine learning</strong>, but it can also adapt to create games and work with embedded devices.</p>
<p>Most importantly, it's the language of choice for introductory <strong>computer science courses</strong> in universities all around the world.</p>
<p>Many students learn Python as their first programming language. Many are learning it right now, and many more will learn it in the future. And for many of them, Python will be the only programming language they need.</p>
<p>Thanks to this unique position, Python is likely going to grow even more in the future.</p>
<p>The language is simple, expressive, and it's quite straightforward.</p>
<p>The ecosystem is huge. There seems to be a library for everything you can imagine.</p>
<p>Python is a high-level programming language suitable for beginners thanks to its intuitive syntax, its huge community, and its vibrant ecosystem.</p>
<p>It is also appreciated by professionals across many different fields.</p>
<p>Technically speaking Python is an interpreted language that does not have an intermediate compilation phase like a compiled language, for example C or Java.</p>
<p>And like many interpreted languages, it is dynamically typed. This means that you do not have to indicate the types of the variables you use, and variables are not tied to a specific type.</p>
<p>This has pros and cons. In particular, you write programs faster, but on the other hand you have less help from the tools to prevent possible bugs. This means that you will find out about certain issues only by executing the program at runtime.</p>
<p>Python supports a wide variety of different programming paradigms, including procedural programming, object oriented programming, and functional programming. It's flexible enough to adapt to a lot of different needs.</p>
<p>Created in 1991 by Guido van Rossum, it's been rising in popularity - especially in the past 5 years, as this Google Trends infographic shows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-09-at-19.22.38.png" alt="Screen-Shot-2020-11-09-at-19.22.38" width="600" height="400" loading="lazy"></p>
<p>Starting with Python is very easy. All you need is to install the official package from python.org, for Windows, macOS or Linux, and you're ready to go.</p>
<p>If you are new to programming, in the following posts I will guide you to go from zero to becoming a Python programmer.</p>
<p>And even if you are currently a programmer who specializes in another language, Python is a language worth knowing because I think it's only going to keep growing from here.</p>
<p>Lower level languages like C++ and Rust might be great for expert programmers, but they're daunting to begin with, and they take a long time to master. </p>
<p>Python, on the other hand, is a programming language for everyone – students, people doing their day jobs with Excel, scientists, and more.</p>
<p><strong>It's the language everyone interested in coding should learn first</strong>.</p>
<h2 id="heading-how-to-install-python">How to Install Python</h2>
<p>Go to <a target="_blank" href="https://www.python.org">https://www.python.org</a>, choose the Downloads menu, choose your operating system, and a panel with a link to download the official package will appear:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-09-at-13.57.36-1.png" alt="Screen-Shot-2020-11-09-at-13.57.36-1" width="600" height="400" loading="lazy"></p>
<p>Make sure you follow the specific instructions for your operating system. On macOS you can find a detailed guide on <a target="_blank" href="https://flaviocopes.com/python-installation-macos/">https://flaviocopes.com/python-installation-macos/</a>.</p>
<h2 id="heading-how-to-run-python-programs">How to Run Python Programs</h2>
<p>There are a few different ways to run Python programs.</p>
<p>In particular, there's a distinction between using interactive prompts, where you type Python code and it's immediately executed, and saving a Python program into a file and executing that.</p>
<p>Let's start with interactive prompts.</p>
<p>If you open your terminal and type <code>python</code>, you will see a screen like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-13.44.07.png" alt="Screen-Shot-2020-11-10-at-13.44.07" width="600" height="400" loading="lazy"></p>
<p>This is the Python REPL (Read-Evaluate-Print-Loop).</p>
<p>Notice the <code>&gt;&gt;&gt;</code> symbol, and the cursor after that. You can type any Python code here, and press the <code>enter</code> key to run it.</p>
<p>For example try defining a new variable using</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Flavio"</span>
</code></pre>
<p>and then print its value, using <code>print()</code>:</p>
<pre><code class="lang-python">print(name)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.11.57.png" alt="Screen-Shot-2020-11-10-at-14.11.57" width="600" height="400" loading="lazy"></p>
<blockquote>
<p>Note: in the REPL, you can also just type <code>name</code>, press the <code>enter</code> key and you'll get the value back. But in a program, you are not going to see any output if you do so - you need to use <code>print()</code> instead.</p>
</blockquote>
<p>Any line of Python you write here is going to be executed immediately.</p>
<p>Type <code>quit()</code> to exit this Python REPL.</p>
<p>You can access the same interactive prompt using the IDLE application that's installed by Python automatically:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.13.25.png" alt="Screen-Shot-2020-11-10-at-14.13.25" width="600" height="400" loading="lazy"></p>
<p>This might be more convenient for you because with the mouse you can move around and copy/paste more easily than with the terminal.</p>
<p>Those are the basics that come with Python by default. However I recommend that you install <a target="_blank" href="https://ipython.org/">IPython</a>, probably the best command line REPL application you can find.</p>
<p>Install it with</p>
<pre><code class="lang-sh">pip install ipython
</code></pre>
<p>Make sure the pip binaries are in your path, then run <code>ipython</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-11-at-09.36.29.png" alt="Screen-Shot-2020-11-11-at-09.36.29" width="600" height="400" loading="lazy"></p>
<p><code>ipython</code> is another interface that lets you work with a Python REPL, and provides some nice features like syntax highlighting, code completion, and much more.</p>
<p>The second way to run a Python program is to write your Python program code into a file, for example <code>program.py</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.01.24.png" alt="Screen-Shot-2020-11-10-at-14.01.24" width="600" height="400" loading="lazy"></p>
<p>and then run it with <code>python program.py</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.01.32.png" alt="Screen-Shot-2020-11-10-at-14.01.32" width="600" height="400" loading="lazy"></p>
<blockquote>
<p>Note that we save Python programs with the <code>.py</code> extension - that's a convention.</p>
</blockquote>
<p>In this case the program is executed as a whole, not one line at a time. And that's typically how we run programs.</p>
<p>We use the REPL for quick prototyping and for learning.</p>
<p>On Linux and macOS, a Python program can also be transformed into a shell script, by prepending all its content with a special line that indicates which executable to use to run it.</p>
<p>On my system the Python executable is located in <code>/usr/bin/python3</code>, so I type <code>#!/usr/bin/python3</code> in the first line:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.17.26.png" alt="Screen-Shot-2020-11-10-at-14.17.26" width="600" height="400" loading="lazy"></p>
<p>Then I can set execution permission on the file:</p>
<pre><code class="lang-sh">chmod u+x program.py
</code></pre>
<p>and I can run the program with</p>
<pre><code class="lang-sh">./program.py
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.18.42.png" alt="Screen-Shot-2020-11-10-at-14.18.42" width="600" height="400" loading="lazy"></p>
<p>This is especially useful when you write scripts that interact with the terminal.</p>
<p>We have many other ways to run Python programs.</p>
<p>One of them is using VS Code, and in particular the official Python extension from Microsoft:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.23.32.png" alt="Screen-Shot-2020-11-10-at-14.23.32" width="600" height="400" loading="lazy"></p>
<p>After installing this extension you will have Python code autocompletion and error checking, automatic formatting and code linting with <code>pylint</code>, and some special commands, including:</p>
<p><strong>Python: Start REPL</strong> to run the REPL in the integrated terminal:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.31.36.png" alt="Screen-Shot-2020-11-10-at-14.31.36" width="600" height="400" loading="lazy"></p>
<p><strong>Python: Run Python File in Terminal</strong> to run the current file in the terminal:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.31.06.png" alt="Screen-Shot-2020-11-10-at-14.31.06" width="600" height="400" loading="lazy"></p>
<p><strong>Python: Run Current File in Python Interactive Window</strong>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.30.02-1.png" alt="Screen-Shot-2020-11-10-at-14.30.02-1" width="600" height="400" loading="lazy"></p>
<p>and many more. Just open the command palette (View -&gt; Command Palette, or Cmd-Shift-P) and type <code>python</code> to see all the Python-related commands:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.30.02.png" alt="Screen-Shot-2020-11-10-at-14.30.02" width="600" height="400" loading="lazy"></p>
<p>Another way to easily run Python code is to use repl.it, a very nice website that provides a coding environment you can create and run your apps on, in any language, Python included:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.33.58.png" alt="Screen-Shot-2020-11-10-at-14.33.58" width="600" height="400" loading="lazy"></p>
<p>Signup (it's free), then under "create a repl" click Python:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.46.34.png" alt="Screen-Shot-2020-11-10-at-14.46.34" width="600" height="400" loading="lazy"></p>
<p>and you will be immediately shown an editor with a <code>main.py</code> file, ready to be filled with a lot of Python code:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.47.15.png" alt="Screen-Shot-2020-11-10-at-14.47.15" width="600" height="400" loading="lazy"></p>
<p>Once you have some code, click "Run" to run it on the right side of the window:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screen-Shot-2020-11-10-at-14.48.09.png" alt="Screen-Shot-2020-11-10-at-14.48.09" width="600" height="400" loading="lazy"></p>
<p>I think repl.it is handy because:</p>
<ul>
<li>you can easily share code just by sharing the link</li>
<li>multiple people can work on the same code</li>
<li>it can host long-running programs</li>
<li>you can install packages</li>
<li>it provides you a key-value database for more complex applications</li>
</ul>
<h2 id="heading-python-2-vs-python-3">Python 2 vs Python 3</h2>
<p>One key topic we should address, right from the start, is the Python 2 vs Python 3 discussion.</p>
<p>Python 3 was introduced in 2008, and it's been in development as the main Python version, while Python 2 continued being maintained with bug fixes and security patches until early 2020.</p>
<p>On that date, Python 2 support was discontinued.</p>
<p>Many programs are still written using Python 2, and organizations still actively work on those, because the migration to Python 3 is not trivial and it would require a lot of work to upgrade those programs. And large and important migrations always introduce new bugs.</p>
<p>But new code, unless you have to adhere to rules set by your organization that forces Python 2, should always be written in Python 3.</p>
<blockquote>
<p>This book focuses on Python 3. </p>
</blockquote>
<h2 id="heading-python-basics">Python Basics</h2>
<h3 id="heading-variables-in-python">Variables in Python</h3>
<p>We can create a new Python variable by assigning a value to a label, using the <code>=</code> assignment operator.</p>
<p>In this example we assign a string with the value "Roger" to the <code>name</code> label:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
</code></pre>
<p>Here's an example with a number:</p>
<pre><code class="lang-python">age = <span class="hljs-number">8</span>
</code></pre>
<p>A variable name can be composed of characters, numbers, and the <code>_</code> underscore character. It can't start with a number. These are all <strong>valid</strong> variable names:</p>
<pre><code class="lang-python">name1
AGE
aGE
a11111
my_name
_name
</code></pre>
<p>These are <strong>invalid</strong> variable names:</p>
<pre><code class="lang-python"><span class="hljs-number">123</span>
test!
name%
</code></pre>
<p>Other than that, anything is valid unless it's a Python <strong>keyword</strong>. There are some keywords like <code>for</code>, <code>if</code>, <code>while</code>, <code>import</code> and more.</p>
<p>There's no need to memorize them, as Python will alert you if you use one of those as a variable, and you will gradually recognize them as part of the Python programming language syntax.</p>
<h3 id="heading-expressions-and-statements-in-python">Expressions and statements in Python</h3>
<p>We can <em>expression</em> any sort of code that returns a value. For example</p>
<pre><code class="lang-python"><span class="hljs-number">1</span> + <span class="hljs-number">1</span>
<span class="hljs-string">"Roger"</span>
</code></pre>
<p>A statement, on the other hand, is an operation on a value. For example these are 2 statements:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
print(name)
</code></pre>
<p>A program is formed by a series of statements. Each statement is put on its own line, but you can use a semicolon to have more than one statement on a single line:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>; print(name)
</code></pre>
<h3 id="heading-comments">Comments</h3>
<p>In a Python program, everything after a hash mark is ignored, and considered a comment:</p>
<pre><code class="lang-python"><span class="hljs-comment">#this is a commented line</span>

name = <span class="hljs-string">"Roger"</span> <span class="hljs-comment"># this is an inline comment</span>
</code></pre>
<h3 id="heading-indentation-in-python">Indentation in Python</h3>
<p>Indentation in Python is meaningful.</p>
<p>You cannot indent randomly like this:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Flavio"</span>
    print(name)
</code></pre>
<p>Some other languages do not have meaningful whitespace, but in Python, indentation matters.</p>
<p>In this case, if you try to run this program you would get a <code>IndentationError: unexpected indent</code> error, because indenting has a special meaning.</p>
<p>Everything indented belongs to a block, like a control statement or conditional block, or a function or class body. We'll see more about those later on.</p>
<h2 id="heading-data-types-in-python">Data Types in Python</h2>
<p>Python has several built-in types.</p>
<p>If you create the <code>name</code> variable assigning it the value "Roger", automatically this variable now represents a <strong>String</strong> data type.</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
</code></pre>
<p>You can check the type of a variable by using the <code>type()</code> function, passing the variable as an argument, and then comparing the result to <code>str</code>:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
type(name) == str <span class="hljs-comment">#True</span>
</code></pre>
<p>Or using <code>isinstance()</code>:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
isinstance(name, str) <span class="hljs-comment">#True</span>
</code></pre>
<blockquote>
<p>Notice that to see the <code>True</code> value in Python, outside of a REPL, you need to wrap this code inside <code>print()</code>, but for clarity I avoid using it.</p>
</blockquote>
<p>We used the <code>str</code> class here, but the same works for other data types.</p>
<p>First, we have numbers. Integer numbers are represented using the <code>int</code> class. Floating point numbers (fractions) are of type <code>float</code>:</p>
<pre><code class="lang-python">age = <span class="hljs-number">1</span>
type(age) == int <span class="hljs-comment">#True</span>
</code></pre>
<pre><code class="lang-python">fraction = <span class="hljs-number">0.1</span>
type(fraction) == float <span class="hljs-comment">#True</span>
</code></pre>
<p>You saw how to create a type from a value literal, like this:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Flavio"</span>
age = <span class="hljs-number">20</span>
</code></pre>
<p>Python automatically detects the type from the value type.</p>
<p>You can also create a variable of a specific type by using the class constructor, passing a value literal or a variable name:</p>
<pre><code class="lang-python">name = str(<span class="hljs-string">"Flavio"</span>)
anotherName = str(name)
</code></pre>
<p>You can also convert from one type to another by using the class constructor. Python will try to determine the correct value, for example extracting a number from a string:</p>
<pre><code class="lang-python">age = int(<span class="hljs-string">"20"</span>)
print(age) <span class="hljs-comment">#20</span>

fraction = <span class="hljs-number">0.1</span>
intFraction = int(fraction)
print(intFraction) <span class="hljs-comment">#0</span>
</code></pre>
<p>This is called <strong>casting</strong>. Of course this conversion might not always work depending on the value passed. If you write <code>test</code> instead of <code>20</code> in the above string, you'll get a <code>ValueError: invalid literal for int() with base 10: 'test'</code> error.</p>
<p>Those are just the basics of types. We have a lot more types in Python:</p>
<ul>
<li><code>complex</code> for complex numbers</li>
<li><code>bool</code> for booleans</li>
<li><code>list</code> for lists</li>
<li><code>tuple</code> for tuples</li>
<li><code>range</code> for ranges</li>
<li><code>dict</code> for dictionaries</li>
<li><code>set</code> for sets</li>
</ul>
<p>and more!</p>
<p>We'll explore them all soon.</p>
<h2 id="heading-operators-in-python">Operators in Python</h2>
<p>Python operators are symbols that we use to run operations upon values and variables.</p>
<p>We can divide operators based on the kind of operation they perform:</p>
<ul>
<li>assignment operator</li>
<li>arithmetic operators</li>
<li>comparison operators</li>
<li>logical operators</li>
<li>bitwise operators</li>
</ul>
<p>plus some interesting ones like <code>is</code> and <code>in</code>.</p>
<h3 id="heading-assignment-operator-in-python">Assignment operator in Python</h3>
<p>The assignment operator is used to assign a value to a variable:</p>
<pre><code class="lang-python">age = <span class="hljs-number">8</span>
</code></pre>
<p>Or to assign a variable value to another variable:</p>
<pre><code class="lang-python">age = <span class="hljs-number">8</span>
anotherVariable = age
</code></pre>
<p>Since Python 3.8, the <code>:=</code> <em>walrus operator</em> is used to assign a value to a variable as part of another operation. For example inside an <code>if</code> or in the conditional part of a loop. More on that later.</p>
<h3 id="heading-arithmetic-operators-in-python">Arithmetic operators in Python</h3>
<p>Python has a number of arithmetic operators: <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code> (division), <code>%</code> (remainder), <code>**</code> (exponentiation) and <code>//</code> (floor division):</p>
<pre><code class="lang-python"><span class="hljs-number">1</span> + <span class="hljs-number">1</span> <span class="hljs-comment">#2</span>
<span class="hljs-number">2</span> - <span class="hljs-number">1</span> <span class="hljs-comment">#1</span>
<span class="hljs-number">2</span> * <span class="hljs-number">2</span> <span class="hljs-comment">#4</span>
<span class="hljs-number">4</span> / <span class="hljs-number">2</span> <span class="hljs-comment">#2</span>
<span class="hljs-number">4</span> % <span class="hljs-number">3</span> <span class="hljs-comment">#1</span>
<span class="hljs-number">4</span> ** <span class="hljs-number">2</span> <span class="hljs-comment">#16</span>
<span class="hljs-number">4</span> // <span class="hljs-number">2</span> <span class="hljs-comment">#2</span>
</code></pre>
<blockquote>
<p>Note that you don't need a space between the operands, but it's good for readability.</p>
</blockquote>
<p><code>-</code> also works as a unary minus operator:</p>
<pre><code class="lang-python">print(<span class="hljs-number">-4</span>) <span class="hljs-comment">#-4</span>
</code></pre>
<p><code>+</code> is also used to concatenate String values:</p>
<pre><code class="lang-python"><span class="hljs-string">"Roger"</span> + <span class="hljs-string">" is a good dog"</span>
<span class="hljs-comment">#Roger is a good dog</span>
</code></pre>
<p>We can combine the assignment operator with arithmetic operators:</p>
<ul>
<li><code>+=</code></li>
<li><code>-=</code></li>
<li><code>*=</code></li>
<li><code>/=</code></li>
<li><code>%=</code></li>
<li>..and so on</li>
</ul>
<p>Example:</p>
<pre><code class="lang-python">age = <span class="hljs-number">8</span>
age += <span class="hljs-number">1</span>
<span class="hljs-comment"># age is now 9</span>
</code></pre>
<h3 id="heading-comparison-operators-in-python">Comparison operators in Python</h3>
<p>Python defines a few comparison operators:</p>
<ul>
<li><code>==</code></li>
<li><code>!=</code></li>
<li><code>&gt;</code></li>
<li><code>&lt;</code></li>
<li><code>&gt;=</code></li>
<li><code>&lt;=</code></li>
</ul>
<p>You can use those operators to get a boolean value (<code>True</code> or <code>False</code>) depending on the result:</p>
<pre><code class="lang-python">a = <span class="hljs-number">1</span>
b = <span class="hljs-number">2</span>

a == b <span class="hljs-comment">#False</span>
a != b <span class="hljs-comment">#True</span>
a &gt; b <span class="hljs-comment">#False</span>
a &lt;= b <span class="hljs-comment">#True</span>
</code></pre>
<h3 id="heading-boolean-operators-in-python">Boolean operators in Python</h3>
<p>Python gives us the following boolean operators:</p>
<ul>
<li><code>not</code></li>
<li><code>and</code></li>
<li><code>or</code></li>
</ul>
<p>When working with <code>True</code> or <code>False</code> attributes, those work like logical AND, OR and NOT, and are often used in the <code>if</code> conditional expression evaluation:</p>
<pre><code class="lang-python">condition1 = <span class="hljs-literal">True</span>
condition2 = <span class="hljs-literal">False</span>

<span class="hljs-keyword">not</span> condition1 <span class="hljs-comment">#False</span>
condition1 <span class="hljs-keyword">and</span> condition2 <span class="hljs-comment">#False</span>
condition1 <span class="hljs-keyword">or</span> condition2 <span class="hljs-comment">#True</span>
</code></pre>
<p>Otherwise, pay attention to a possible source of confusion:</p>
<p><code>or</code> used in an expression returns the value of the first operand that is not a falsy value (<code>False</code>, <code>0</code>, <code>''</code>, <code>[]</code>..). Otherwise it returns the last operand.</p>
<pre><code class="lang-python">print(<span class="hljs-number">0</span> <span class="hljs-keyword">or</span> <span class="hljs-number">1</span>) <span class="hljs-comment">## 1</span>
print(<span class="hljs-literal">False</span> <span class="hljs-keyword">or</span> <span class="hljs-string">'hey'</span>) <span class="hljs-comment">## 'hey'</span>
print(<span class="hljs-string">'hi'</span> <span class="hljs-keyword">or</span> <span class="hljs-string">'hey'</span>) <span class="hljs-comment">## 'hi'</span>
print([] <span class="hljs-keyword">or</span> <span class="hljs-literal">False</span>) <span class="hljs-comment">## 'False'</span>
print(<span class="hljs-literal">False</span> <span class="hljs-keyword">or</span> []) <span class="hljs-comment">## '[]'</span>
</code></pre>
<p>The Python docs describe it as <code>if x is false, then y, else x</code>.</p>
<p><code>and</code> only evaluates the second argument if the first one is true. So if the first argument is falsy (<code>False</code>, <code>0</code>, <code>''</code>, <code>[]</code>..), it returns that argument. Otherwise it evaluates the second argument:</p>
<pre><code class="lang-python">print(<span class="hljs-number">0</span> <span class="hljs-keyword">and</span> <span class="hljs-number">1</span>) <span class="hljs-comment">## 0</span>
print(<span class="hljs-number">1</span> <span class="hljs-keyword">and</span> <span class="hljs-number">0</span>) <span class="hljs-comment">## 0</span>
print(<span class="hljs-literal">False</span> <span class="hljs-keyword">and</span> <span class="hljs-string">'hey'</span>) <span class="hljs-comment">## False</span>
print(<span class="hljs-string">'hi'</span> <span class="hljs-keyword">and</span> <span class="hljs-string">'hey'</span>) <span class="hljs-comment">## 'hey'</span>
print([] <span class="hljs-keyword">and</span> <span class="hljs-literal">False</span> ) <span class="hljs-comment">## []</span>
print(<span class="hljs-literal">False</span> <span class="hljs-keyword">and</span> [] ) <span class="hljs-comment">## False</span>
</code></pre>
<p>The Python docs describe it as <code>if x is false, then x, else y</code>.</p>
<h3 id="heading-bitwise-operators-in-python">Bitwise operators in Python</h3>
<p>Some operators are used to work on bits and binary numbers:</p>
<ul>
<li><code>&amp;</code> performs binary AND</li>
<li><code>|</code> performs binary OR</li>
<li><code>^</code> performs a binary XOR operation</li>
<li><code>~</code> performs a binary NOT operation</li>
<li><code>&lt;&lt;</code> shift left operation</li>
<li><code>&gt;&gt;</code> shift right operation</li>
</ul>
<p>Bitwise operators are rarely used, only in very specific situations, but they are worth mentioning.</p>
<h3 id="heading-is-and-in-in-python"><code>is</code> and <code>in</code> in Python</h3>
<p><code>is</code> is called the <strong>identity operator</strong>. It is used to compare two objects and returns true if both are the same object. More on objects later.</p>
<p><code>in</code> is called the <strong>membership operator</strong>. Is used to tell if a value is contained in a list, or another sequence. More on lists and other sequences later.</p>
<h2 id="heading-the-ternary-operator-in-python">The Ternary Operator in Python</h2>
<p>The ternary operator in Python allows you to quickly define a conditional.</p>
<p>Let's say you have a function that compares an <code>age</code> variable to the <code>18</code> value, and returns True or False depending on the result.</p>
<p>Instead of writing:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">is_adult</span>(<span class="hljs-params">age</span>):</span>
    <span class="hljs-keyword">if</span> age &gt; <span class="hljs-number">18</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>
</code></pre>
<p>You can implement it with the ternary operator in this way:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">is_adult</span>(<span class="hljs-params">age</span>):</span>
    <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span> <span class="hljs-keyword">if</span> age &gt; <span class="hljs-number">18</span> <span class="hljs-keyword">else</span> <span class="hljs-literal">False</span>
</code></pre>
<p>First you define the result if the condition is True, then you evaluate the condition, then you define the result if the condition is false:</p>
<pre><code class="lang-python">&lt;result_if_true&gt; <span class="hljs-keyword">if</span> &lt;condition&gt; <span class="hljs-keyword">else</span> &lt;result_if_false&gt;
</code></pre>
<h2 id="heading-strings-in-python">Strings in Python</h2>
<p>A string in Python is a series of characters enclosed in quotes or double quotes:</p>
<pre><code class="lang-python"><span class="hljs-string">"Roger"</span>
<span class="hljs-string">'Roger'</span>
</code></pre>
<p>You can assign a string value to a variable:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
</code></pre>
<p>You can concatenate two strings using the <code>+</code> operator:</p>
<pre><code class="lang-python">phrase = <span class="hljs-string">"Roger"</span> + <span class="hljs-string">" is a good dog"</span>
</code></pre>
<p>You can append to a string using <code>+=</code>:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
name += <span class="hljs-string">" is a good dog"</span>

print(name) <span class="hljs-comment">#Roger is a good dog</span>
</code></pre>
<p>You can convert a number to a string using the <code>str</code> class constructor:</p>
<pre><code class="lang-python">str(<span class="hljs-number">8</span>) <span class="hljs-comment">#"8"</span>
</code></pre>
<p>This is essential to concatenate a number to a string:</p>
<pre><code class="lang-python">print(<span class="hljs-string">"Roger is "</span> + str(<span class="hljs-number">8</span>) + <span class="hljs-string">" years old"</span>) <span class="hljs-comment">#Roger is 8 years old</span>
</code></pre>
<p>A string can be multi-line when defined with a special syntax, enclosing the string in a set of 3 quotes:</p>
<pre><code class="lang-python">print(<span class="hljs-string">"""Roger is

    8

years old
"""</span>)

<span class="hljs-comment">#double quotes, or single quotes</span>

print(<span class="hljs-string">'''
Roger is

    8

years old
'''</span>)
</code></pre>
<p>A string has a set of built-in methods, like:</p>
<ul>
<li><code>isalpha()</code> to check if a string contains only characters and is not empty</li>
<li><code>isalnum()</code> to check if a string contains characters or digits and is not empty</li>
<li><code>isdecimal()</code> to check if a string contains digits and is not empty</li>
<li><code>lower()</code> to get a lowercase version of a string</li>
<li><code>islower()</code> to check if a string is lowercase</li>
<li><code>upper()</code> to get an uppercase version of a string</li>
<li><code>isupper()</code> to check if a string is uppercase</li>
<li><code>title()</code> to get a capitalized version of a string</li>
<li><code>startsswith()</code> to check if the string starts with a specific substring</li>
<li><code>endswith()</code> to check if the string ends with a specific substring</li>
<li><code>replace()</code> to replace a part of a string</li>
<li><code>split()</code> to split a string on a specific character separator</li>
<li><code>strip()</code> to trim the whitespace from a string</li>
<li><code>join()</code> to append new letters to a string</li>
<li><code>find()</code> to find the position of a substring</li>
</ul>
<p>and many more.</p>
<p>None of those methods alter the original string. They return a new, modified string instead. For example:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
print(name.lower()) <span class="hljs-comment">#"roger"</span>
print(name) <span class="hljs-comment">#"Roger"</span>
</code></pre>
<p>You can use some global functions to work with strings, too.</p>
<p>In particular I think of <code>len()</code>, which gives you the length of a string:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
print(len(name)) <span class="hljs-comment">#5</span>
</code></pre>
<p>The <code>in</code> operator lets you check if a string contains a substring:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
print(<span class="hljs-string">"ger"</span> <span class="hljs-keyword">in</span> name) <span class="hljs-comment">#True</span>
</code></pre>
<p>Escaping is a way to add special characters into a string.</p>
<p>For example, how do you add a double quote into a string that's wrapped into double quotes?</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
</code></pre>
<p><code>"Ro"Ger"</code> will not work, as Python will think the string ends at <code>"Ro"</code>.</p>
<p>The way to go is to escape the double quote inside the string, with the <code>\</code> backslash character:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Ro\"ger"</span>
</code></pre>
<p>This applies to single quotes too <code>\'</code>, and for special formatting characters like <code>\t</code> for tab, <code>\n</code> for new line and <code>\\</code> for the backslash.</p>
<p>Given a string, you can get its characters using square brackets to get a specific item, given its index, starting from 0:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
name[<span class="hljs-number">0</span>] <span class="hljs-comment">#'R'</span>
name[<span class="hljs-number">1</span>] <span class="hljs-comment">#'o'</span>
name[<span class="hljs-number">2</span>] <span class="hljs-comment">#'g'</span>
</code></pre>
<p>Using a negative number will start counting from the end:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
name[<span class="hljs-number">-1</span>] <span class="hljs-comment">#"r"</span>
</code></pre>
<p>You can also use a range, using what we call <strong>slicing</strong>:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
name[<span class="hljs-number">0</span>:<span class="hljs-number">2</span>] <span class="hljs-comment">#"Ro"</span>
name[:<span class="hljs-number">2</span>] <span class="hljs-comment">#"Ro"</span>
name[<span class="hljs-number">2</span>:] <span class="hljs-comment">#"ger"</span>
</code></pre>
<h2 id="heading-booleans-in-python">Booleans in Python</h2>
<p>Python provides the <code>bool</code> type, which can have two values: <code>True</code> and <code>False</code> (capitalized).</p>
<pre><code class="lang-python">done = <span class="hljs-literal">False</span>
done = <span class="hljs-literal">True</span>
</code></pre>
<p>Booleans are especially useful with conditional control structures like <code>if</code> statements:</p>
<pre><code class="lang-python">done = <span class="hljs-literal">True</span>

<span class="hljs-keyword">if</span> done:
    <span class="hljs-comment"># run some code here</span>
<span class="hljs-keyword">else</span>:
    <span class="hljs-comment"># run some other code</span>
</code></pre>
<p>When evaluating a value for <code>True</code> or <code>False</code>, if the value is not a <code>bool</code> we have some rules depending on the type we're checking:</p>
<ul>
<li>numbers are always <code>True</code> except for the number <code>0</code></li>
<li>strings are <code>False</code> only when empty</li>
<li>lists, tuples, sets, and dictionaries are <code>False</code> only when empty</li>
</ul>
<p>You can check if a value is a boolean in this way:</p>
<pre><code class="lang-python">done = <span class="hljs-literal">True</span>
type(done) == bool <span class="hljs-comment">#True</span>
</code></pre>
<p>Or using <code>isinstance()</code>, passing 2 arguments: the variable, and the <code>bool</code> class:</p>
<pre><code class="lang-python">done = <span class="hljs-literal">True</span>
isinstance(done, bool) <span class="hljs-comment">#True</span>
</code></pre>
<p>The global <code>any()</code> function is also very useful when working with booleans, as it returns <code>True</code> if any of the values of the iterable (list, for example) passed as argument are <code>True</code>:</p>
<pre><code class="lang-python">book_1_read = <span class="hljs-literal">True</span>
book_2_read = <span class="hljs-literal">False</span>

read_any_book = any([book_1_read, book_2_read])
</code></pre>
<p>The global <code>all()</code> function is same, but returns <code>True</code> if all of the values passed to it are <code>True</code>:</p>
<pre><code class="lang-python">ingredients_purchased = <span class="hljs-literal">True</span>
meal_cooked = <span class="hljs-literal">False</span>

ready_to_serve = all([ingredients_purchased, meal_cooked])
</code></pre>
<h2 id="heading-numbers-in-python">Numbers in Python</h2>
<p>Numbers in Python can be of 3 types: <code>int</code>, <code>float</code> and <code>complex</code>.</p>
<h3 id="heading-integer-numbers-in-python">Integer numbers in Python</h3>
<p>Integer numbers are represented using the <code>int</code> class. You can define an integer using a value literal:</p>
<pre><code class="lang-python">age = <span class="hljs-number">8</span>
</code></pre>
<p>You can also define an integer number using the <code>int()</code> constructor:</p>
<pre><code class="lang-python">age = int(<span class="hljs-number">8</span>)
</code></pre>
<p>To check if a variable is of type <code>int</code>, you can use the <code>type()</code> global function:</p>
<pre><code class="lang-python">type(age) == int <span class="hljs-comment">#True</span>
</code></pre>
<h3 id="heading-floating-point-numbers-in-python">Floating point numbers in Python</h3>
<p>Floating point numbers (fractions) are of type <code>float</code>. You can define an integer using a value literal:</p>
<pre><code class="lang-python">fraction = <span class="hljs-number">0.1</span>
</code></pre>
<p>Or using the <code>float()</code> constructor:</p>
<pre><code class="lang-python">fraction = float(<span class="hljs-number">0.1</span>)
</code></pre>
<p>To check if a variable is of type <code>float</code>, you can use the <code>type()</code> global function:</p>
<pre><code class="lang-python">type(fraction) == float <span class="hljs-comment">#True</span>
</code></pre>
<h3 id="heading-complex-numbers-in-python">Complex numbers in Python</h3>
<p>Complex numbers are of type <code>complex</code>.</p>
<p>You can define them using a value literal:</p>
<pre><code class="lang-python">complexNumber = <span class="hljs-number">2</span>+<span class="hljs-number">3j</span>
</code></pre>
<p>or using the <code>complex()</code> constructor:</p>
<pre><code class="lang-python">complexNumber = complex(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
</code></pre>
<p>Once you have a complex number, you can get its real and imaginary part:</p>
<pre><code class="lang-python">complexNumber.real <span class="hljs-comment">#2.0</span>
complexNumber.imag <span class="hljs-comment">#3.0</span>
</code></pre>
<p>Again, to check if a variable is of type <code>complex</code>, you can use the <code>type()</code> global function:</p>
<pre><code class="lang-python">type(complexNumber) == complex <span class="hljs-comment">#True</span>
</code></pre>
<h3 id="heading-arithmetic-operations-on-numbers-in-python">Arithmetic operations on numbers in Python</h3>
<p>You can perform arithmetic operations on numbers, using the arithmetic operators: <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code> (division), <code>%</code> (remainder), <code>**</code> (exponentiation) and <code>//</code> (floor division):</p>
<pre><code class="lang-python"><span class="hljs-number">1</span> + <span class="hljs-number">1</span> <span class="hljs-comment">#2</span>
<span class="hljs-number">2</span> - <span class="hljs-number">1</span> <span class="hljs-comment">#1</span>
<span class="hljs-number">2</span> * <span class="hljs-number">2</span> <span class="hljs-comment">#4</span>
<span class="hljs-number">4</span> / <span class="hljs-number">2</span> <span class="hljs-comment">#2</span>
<span class="hljs-number">4</span> % <span class="hljs-number">3</span> <span class="hljs-comment">#1</span>
<span class="hljs-number">4</span> ** <span class="hljs-number">2</span> <span class="hljs-comment">#16</span>
<span class="hljs-number">4</span> // <span class="hljs-number">2</span> <span class="hljs-comment">#2</span>
</code></pre>
<p>and you can use the compound assignment operators</p>
<ul>
<li><code>+=</code></li>
<li><code>-=</code></li>
<li><code>*=</code></li>
<li><code>/=</code></li>
<li><code>%=</code></li>
<li>..and so on</li>
</ul>
<p>to quickly perform operations on variables, too:</p>
<pre><code class="lang-python">age = <span class="hljs-number">8</span>
age += <span class="hljs-number">1</span>
</code></pre>
<h3 id="heading-built-in-functions-in-python">Built-in Functions in Python</h3>
<p>There are 2 built-in functions that help with numbers:</p>
<p><code>abs()</code> returns the absolute value of a number.</p>
<p><code>round()</code> given a number, returns its value rounded to the nearest integer:</p>
<pre><code class="lang-python">round(<span class="hljs-number">0.12</span>) <span class="hljs-comment">#0</span>
</code></pre>
<p>You can specify a second parameter to set the decimal point's precision:</p>
<pre><code class="lang-python">round(<span class="hljs-number">0.12</span>, <span class="hljs-number">1</span>) <span class="hljs-comment">#0.1</span>
</code></pre>
<p>Several other math utility functions and constants are provided by the Python standard library:</p>
<ul>
<li>the <code>math</code> package provides general math functions and constants</li>
<li>the <code>cmath</code> package provides utilities to work with complex numbers.</li>
<li>the <code>decimal</code> package provides utilities to work with decimals and floating point numbers.</li>
<li>the <code>fractions</code> package provides utilities to work with rational numbers.</li>
</ul>
<p>We'll explore some of those separately later on.</p>
<h2 id="heading-constants-in-python">Constants in Python</h2>
<p>Python has no way to enforce that a variable should be a constant.</p>
<p>The nearest you can get is to use an enum:</p>
<pre><code class="lang-Python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Constants</span>(<span class="hljs-params">Enum</span>):</span>
    WIDTH = <span class="hljs-number">1024</span>
    HEIGHT = <span class="hljs-number">256</span>
</code></pre>
<p>And get to each value using, for example, <code>Constants.WIDTH.value</code>.</p>
<p>No one can reassign that value.</p>
<p>Otherwise if you want to rely on naming conventions, you can adhere to this one: declare variables that should never change uppercase:</p>
<pre><code class="lang-python">WIDTH = <span class="hljs-number">1024</span>
</code></pre>
<p>No one will prevent you from overwriting this value, and Python will not stop it.</p>
<p>That's what most Python code does that you will see.</p>
<h2 id="heading-enums-in-python">Enums in Python</h2>
<p>Enums are readable names that are bound to a constant value.</p>
<p>To use enums, import <code>Enum</code> from the <code>enum</code> standard library module:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> enum <span class="hljs-keyword">import</span> Enum
</code></pre>
<p>Then you can initialize a new enum in this way:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">State</span>(<span class="hljs-params">Enum</span>):</span>
    INACTIVE = <span class="hljs-number">0</span>
    ACTIVE = <span class="hljs-number">1</span>
</code></pre>
<p>Once you do so, you can reference <code>State.INACTIVE</code> and <code>State.ACTIVE</code>, and they serve as constants.</p>
<p>Now if you try to print <code>State.ACTIVE</code> for example:</p>
<pre><code class="lang-python">print(State.ACTIVE)
</code></pre>
<p>it will not return <code>1</code>, but <code>State.ACTIVE</code>.</p>
<p>The same value can be reached by the number assigned in the enum: <code>print(State(1))</code> will return <code>State.ACTIVE</code>. Same for using the square brackets notation <code>State['ACTIVE']</code>.</p>
<p>You can, however, get the value using <code>State.ACTIVE.value</code>.</p>
<p>You can list all the possible values of an enum:</p>
<pre><code class="lang-python">list(State) <span class="hljs-comment"># [&lt;State.INACTIVE: 0&gt;, &lt;State.ACTIVE: 1&gt;]</span>
</code></pre>
<p>You can count them:</p>
<pre><code class="lang-python">len(State) <span class="hljs-comment"># 2</span>
</code></pre>
<h2 id="heading-user-input-in-python">User Input in Python</h2>
<p>In a Python command line application you can display information to the user using the <code>print()</code> function:</p>
<pre><code class="lang-python">name = <span class="hljs-string">"Roger"</span>
print(name)
</code></pre>
<p>We can also accept input from the user, using <code>input()</code>:</p>
<pre><code class="lang-python">print(<span class="hljs-string">'What is your age?'</span>)
age = input()
print(<span class="hljs-string">'Your age is '</span> + age)
</code></pre>
<p>This approach gets input at runtime, meaning the program will stop execution and will wait until the user types something and presses the <code>enter</code> key.</p>
<p>You can also do more complex input processing and accept input at program invocation time, and we'll see how to do that later on.</p>
<p>This works for command line applications. Other kinds of applications will need a different way of accepting input.</p>
<h2 id="heading-control-statements-in-python">Control Statements in Python</h2>
<p>When you're dealing with booleans, and expressions that return a boolean in particular, we can make decisions and take different roads depending on their <code>True</code> or <code>False</code> values.</p>
<p>In Python we do so using the <code>if</code> statement:</p>
<pre><code class="lang-python">condition = <span class="hljs-literal">True</span>

<span class="hljs-keyword">if</span> condition == <span class="hljs-literal">True</span>:
    <span class="hljs-comment"># do something</span>
</code></pre>
<p>When the condition test resolves to <code>True</code>, like in the above case, its block gets executed.</p>
<p>What is a block? A block is that part that is indented one level (4 spaces usually) on the right:</p>
<pre><code class="lang-python">condition = <span class="hljs-literal">True</span>

<span class="hljs-keyword">if</span> condition == <span class="hljs-literal">True</span>:
    print(<span class="hljs-string">"The condition"</span>)
    print(<span class="hljs-string">"was true"</span>)
</code></pre>
<p>The block can be formed by a single line, or multiple lines as well, and it ends when you move back to the previous indentation level:</p>
<pre><code class="lang-python">condition = <span class="hljs-literal">True</span>

<span class="hljs-keyword">if</span> condition == <span class="hljs-literal">True</span>:
    print(<span class="hljs-string">"The condition"</span>)
    print(<span class="hljs-string">"was true"</span>)

print(<span class="hljs-string">"Outside of the if"</span>)
</code></pre>
<p>In combination with <code>if</code> you can have an <code>else</code> block that's executed if the condition test of <code>if</code> results to <code>False</code>:</p>
<pre><code class="lang-python">condition = <span class="hljs-literal">True</span>

<span class="hljs-keyword">if</span> condition == <span class="hljs-literal">True</span>:
    print(<span class="hljs-string">"The condition"</span>)
    print(<span class="hljs-string">"was True"</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"The condition"</span>)
    print(<span class="hljs-string">"was False"</span>)
</code></pre>
<p>And you can have different linked <code>if</code> checks with <code>elif</code> that's executed if the previous check was <code>False</code>:</p>
<pre><code class="lang-python">condition = <span class="hljs-literal">True</span>
name = <span class="hljs-string">"Roger"</span>

<span class="hljs-keyword">if</span> condition == <span class="hljs-literal">True</span>:
    print(<span class="hljs-string">"The condition"</span>)
    print(<span class="hljs-string">"was True"</span>)
<span class="hljs-keyword">elif</span> name == <span class="hljs-string">"Roger"</span>:
    print(<span class="hljs-string">"Hello Roger"</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"The condition"</span>)
    print(<span class="hljs-string">"was False"</span>)
</code></pre>
<p>The second block in this case is executed if <code>condition</code> is <code>False</code>, and the <code>name</code> variable value is "Roger".</p>
<p>In a <code>if</code> statement you can have just one <code>if</code> and <code>else</code> check, but multiple series of <code>elif</code> checks:</p>
<pre><code class="lang-python">condition = <span class="hljs-literal">True</span>
name = <span class="hljs-string">"Roger"</span>

<span class="hljs-keyword">if</span> condition == <span class="hljs-literal">True</span>:
    print(<span class="hljs-string">"The condition"</span>)
    print(<span class="hljs-string">"was True"</span>)
<span class="hljs-keyword">elif</span> name == <span class="hljs-string">"Roger"</span>:
    print(<span class="hljs-string">"Hello Roger"</span>)
<span class="hljs-keyword">elif</span> name == <span class="hljs-string">"Syd"</span>:
    print(<span class="hljs-string">"Hello Syd"</span>)
<span class="hljs-keyword">elif</span> name == <span class="hljs-string">"Flavio"</span>:
    print(<span class="hljs-string">"Hello Flavio"</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"The condition"</span>)
    print(<span class="hljs-string">"was False"</span>)
</code></pre>
<p><code>if</code> and <code>else</code> can also be used in an inline format, which lets us return one value or another based on a condition.</p>
<p>Example:</p>
<pre><code class="lang-python">a = <span class="hljs-number">2</span>
result = <span class="hljs-number">2</span> <span class="hljs-keyword">if</span> a == <span class="hljs-number">0</span> <span class="hljs-keyword">else</span> <span class="hljs-number">3</span>
print(result) <span class="hljs-comment"># 3</span>
</code></pre>
<h2 id="heading-lists-in-python">Lists in Python</h2>
<p>Lists are an essential Python data structure.</p>
<p>The allow you to group together multiple values and reference them all with a common name.</p>
<p>For example:</p>
<pre><code class="lang-python">dogs = [<span class="hljs-string">"Roger"</span>, <span class="hljs-string">"Syd"</span>]
</code></pre>
<p>A list can hold values of different types:</p>
<pre><code class="lang-python">items = [<span class="hljs-string">"Roger"</span>, <span class="hljs-number">1</span>, <span class="hljs-string">"Syd"</span>, <span class="hljs-literal">True</span>]
</code></pre>
<p>You can check if an item is contained in a list with the <code>in</code> operator:</p>
<pre><code class="lang-python">print(<span class="hljs-string">"Roger"</span> <span class="hljs-keyword">in</span> items) <span class="hljs-comment"># True</span>
</code></pre>
<p>A list can also be defined as empty:</p>
<pre><code class="lang-python">items = []
</code></pre>
<p>You can reference the items in a list by their index, starting from zero:</p>
<pre><code class="lang-python">items[<span class="hljs-number">0</span>] <span class="hljs-comment"># "Roger"</span>
items[<span class="hljs-number">1</span>] <span class="hljs-comment"># 1</span>
items[<span class="hljs-number">3</span>] <span class="hljs-comment"># True</span>
</code></pre>
<p>Using the same notation you can change the value stored at a specific index:</p>
<pre><code class="lang-python">items[<span class="hljs-number">0</span>] = <span class="hljs-string">"Roger"</span>
</code></pre>
<p>You can also use the <code>index()</code> method:</p>
<pre><code class="lang-python">items.index(<span class="hljs-number">0</span>) <span class="hljs-comment"># "Roger"</span>
items.index(<span class="hljs-number">1</span>) <span class="hljs-comment"># 1</span>
</code></pre>
<p>As with strings, using a negative index will start searching from the end:</p>
<pre><code class="lang-python">items[<span class="hljs-number">-1</span>] <span class="hljs-comment"># True</span>
</code></pre>
<p>You can also extract a part of a list, using slices:</p>
<pre><code class="lang-python">items[<span class="hljs-number">0</span>:<span class="hljs-number">2</span>] <span class="hljs-comment"># ["Roger", 1]</span>
items[<span class="hljs-number">2</span>:] <span class="hljs-comment"># ["Syd", True]</span>
</code></pre>
<p>Get the number of items contained in a list using the <code>len()</code> global function, the same we used to get the length of a string:</p>
<pre><code class="lang-python">len(items) <span class="hljs-comment">#4</span>
</code></pre>
<p>You can add items to the list by using a list <code>append()</code> method:</p>
<pre><code class="lang-python">items.append(<span class="hljs-string">"Test"</span>)
</code></pre>
<p>or the extend() method:</p>
<pre><code class="lang-python">items.extend([<span class="hljs-string">"Test"</span>])
</code></pre>
<p>You can also use the <code>+=</code> operator:</p>
<pre><code class="lang-python">items += [<span class="hljs-string">"Test"</span>]

<span class="hljs-comment"># items is ['Roger', 1, 'Syd', True, 'Test']</span>
</code></pre>
<blockquote>
<p>Tip: with <code>extend()</code> or <code>+=</code> don't forget the square brackets. Don't do <code>items += "Test"</code> or <code>items.extend("Test")</code> or Python will add 4 individual characters to the list, resulting in <code>['Roger', 1, 'Syd', True, 'T', 'e', 's', 't']</code></p>
</blockquote>
<p>Remove an item using the <code>remove()</code> method:</p>
<pre><code class="lang-python">items.remove(<span class="hljs-string">"Test"</span>)
</code></pre>
<p>You can add multiple elements using</p>
<pre><code class="lang-python">items += [<span class="hljs-string">"Test1"</span>, <span class="hljs-string">"Test2"</span>]

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

items.extend([<span class="hljs-string">"Test1"</span>, <span class="hljs-string">"Test2"</span>])
</code></pre>
<p>These append the item to the end of the list.</p>
<p>To add an item in the middle of a list, at a specific index, use the <code>insert()</code> method:</p>
<pre><code class="lang-python">items.insert(<span class="hljs-string">"Test"</span>, <span class="hljs-number">1</span>) <span class="hljs-comment"># add "Test" at index 1</span>
</code></pre>
<p>To add multiple items at a specific index, you need to use slices:</p>
<pre><code class="lang-python">items[<span class="hljs-number">1</span>:<span class="hljs-number">1</span>] = [<span class="hljs-string">"Test1"</span>, <span class="hljs-string">"Test2"</span>]
</code></pre>
<p>Sort a list using the <code>sort()</code> method:</p>
<pre><code class="lang-python">items.sort()
</code></pre>
<blockquote>
<p>Tip: sort() will only work if the list holds values that can be compared. Strings and integers for example can't be compared, and you'll get an error like <code>TypeError: '&lt;' not supported between instances of 'int' and 'str'</code> if you try.</p>
</blockquote>
<p>The <code>sort()</code> methods orders uppercase letters first, then lowercase letters. To fix this, use:</p>
<pre><code class="lang-python">items.sort(key=str.lower)
</code></pre>
<p>instead.</p>
<p>Sorting modifies the original list content. To avoid that, you can copy the list content using</p>
<pre><code class="lang-python">itemscopy = items[:]
</code></pre>
<p>or use the <code>sorted()</code> global function:</p>
<pre><code class="lang-python">print(sorted(items, key=str.lower))
</code></pre>
<p>that will return a new list, sorted, instead of modifying the original list.</p>
<h2 id="heading-tuples-in-python">Tuples in Python</h2>
<p>Tuples are another fundamental Python data structure.</p>
<p>They allow you to create immutable groups of objects. This means that once a tuple is created, it can't be modified. You can't add or remove items.</p>
<p>They are created in a way similar to lists, but using parentheses instead of square brackets:</p>
<pre><code class="lang-python">names = (<span class="hljs-string">"Roger"</span>, <span class="hljs-string">"Syd"</span>)
</code></pre>
<p>A tuple is ordered, like a list, so you can get its values by referencing an index value:</p>
<pre><code class="lang-python">names[<span class="hljs-number">0</span>] <span class="hljs-comment"># "Roger"</span>
names[<span class="hljs-number">1</span>] <span class="hljs-comment"># "Syd"</span>
</code></pre>
<p>You can also use the <code>index()</code> method:</p>
<pre><code class="lang-python">names.index(<span class="hljs-string">'Roger'</span>) <span class="hljs-comment"># 0</span>
names.index(<span class="hljs-string">'Syd'</span>)   <span class="hljs-comment"># 1</span>
</code></pre>
<p>As with strings and lists, using a negative index will start searching from the end:</p>
<pre><code class="lang-python">names[<span class="hljs-number">-1</span>] <span class="hljs-comment"># True</span>
</code></pre>
<p>You can count the items in a tuple with the <code>len()</code> function:</p>
<pre><code class="lang-python">len(names) <span class="hljs-comment"># 2</span>
</code></pre>
<p>You can check if an item is contained in a tuple with the <code>in</code> operator:</p>
<pre><code class="lang-python">print(<span class="hljs-string">"Roger"</span> <span class="hljs-keyword">in</span> names) <span class="hljs-comment"># True</span>
</code></pre>
<p>You can also extract a part of a tuple, using slices:</p>
<pre><code class="lang-python">names[<span class="hljs-number">0</span>:<span class="hljs-number">2</span>] <span class="hljs-comment"># ('Roger', 'Syd')</span>
names[<span class="hljs-number">1</span>:] <span class="hljs-comment"># ('Syd',)</span>
</code></pre>
<p>Get the number of items in a tuple using the <code>len()</code> global function, the same we used to get the length of a string:</p>
<pre><code class="lang-python">len(names) <span class="hljs-comment">#2</span>
</code></pre>
<p>You can create a sorted version of a tuple using the <code>sorted()</code> global function:</p>
<pre><code class="lang-python">sorted(names)
</code></pre>
<p>You can create a new tuple from existing tuples using the <code>+</code> operator:</p>
<pre><code class="lang-python">newTuple = names + (<span class="hljs-string">"Vanille"</span>, <span class="hljs-string">"Tina"</span>)
</code></pre>
<h2 id="heading-dictionaries-in-python">Dictionaries in Python</h2>
<p>Dictionaries are a very important Python data structure.</p>
<p>While lists allow you to create collections of values, dictionaries allow you to create collections of <strong>key / value pairs</strong>.</p>
<p>Here is a dictionary example with one key/value pair:</p>
<pre><code class="lang-python">dog = { <span class="hljs-string">'name'</span>: <span class="hljs-string">'Roger'</span> }
</code></pre>
<p>The key can be any immutable value like a string, a number or a tuple. The value can be anything you want.</p>
<p>A dictionary can contain multiple key/value pairs:</p>
<pre><code class="lang-python">dog = { <span class="hljs-string">'name'</span>: <span class="hljs-string">'Roger'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-number">8</span> }
</code></pre>
<p>You can access individual key values using this notation:</p>
<pre><code class="lang-python">dog[<span class="hljs-string">'name'</span>] <span class="hljs-comment"># 'Roger'</span>
dog[<span class="hljs-string">'age'</span>]  <span class="hljs-comment"># 8</span>
</code></pre>
<p>Using the same notation you can change the value stored at a specific index:</p>
<pre><code class="lang-python">dog[<span class="hljs-string">'name'</span>] = <span class="hljs-string">'Syd'</span>
</code></pre>
<p>And another way is using the <code>get()</code> method, which has an option to add a default value:</p>
<pre><code class="lang-python">dog.get(<span class="hljs-string">'name'</span>) <span class="hljs-comment"># 'Roger'</span>
dog.get(<span class="hljs-string">'test'</span>, <span class="hljs-string">'default'</span>) <span class="hljs-comment"># 'default'</span>
</code></pre>
<p>The <code>pop()</code> method retrieves the value of a key, and subsequently deletes the item from the dictionary:</p>
<pre><code class="lang-python">dog.pop(<span class="hljs-string">'name'</span>) <span class="hljs-comment"># 'Roger'</span>
</code></pre>
<p>The <code>popitem()</code> method retrieves and removes the last key/value pair inserted into the dictionary:</p>
<pre><code class="lang-python">dog.popitem()
</code></pre>
<p>You can check if a key is contained into a dictionary with the <code>in</code> operator:</p>
<pre><code class="lang-python"><span class="hljs-string">'name'</span> <span class="hljs-keyword">in</span> dog <span class="hljs-comment"># True</span>
</code></pre>
<p>Get a list with the keys in a dictionary using the <code>keys()</code> method, passing its result to the <code>list()</code> constructor:</p>
<pre><code class="lang-python">list(dog.keys()) <span class="hljs-comment"># ['name', 'age']</span>
</code></pre>
<p>Get the values using the <code>values()</code> method, and the key/value pairs tuples using the <code>items()</code> method:</p>
<pre><code class="lang-python">print(list(dog.values()))
<span class="hljs-comment"># ['Roger', 8]</span>

print(list(dog.items()))
<span class="hljs-comment"># [('name', 'Roger'), ('age', 8)]</span>
</code></pre>
<p>Get a dictionary length using the <code>len()</code> global function, the same we used to get the length of a string or the items in a list:</p>
<pre><code class="lang-python">len(dog) <span class="hljs-comment">#2</span>
</code></pre>
<p>You can add a new key/value pair to the dictionary in this way:</p>
<pre><code class="lang-python">dog[<span class="hljs-string">'favorite food'</span>] = <span class="hljs-string">'Meat'</span>
</code></pre>
<p>You can remove a key/value pair from a dictionary using the <code>del</code> statement:</p>
<pre><code class="lang-python"><span class="hljs-keyword">del</span> dog[<span class="hljs-string">'favorite food'</span>]
</code></pre>
<p>To copy a dictionary, use the copy() method:</p>
<pre><code class="lang-python">dogCopy = dog.copy()
</code></pre>
<h2 id="heading-sets-in-python">Sets in Python</h2>
<p>Sets are another important Python data structure.</p>
<p>We can say they work like tuples, but they are not ordered, and they are <strong>mutable</strong>.</p>
<p>Or we can say they work like dictionaries, but they don't have keys.</p>
<p>They also have an immutable version, called <code>frozenset</code>.</p>
<p>You can create a set using this syntax:</p>
<pre><code class="lang-python">names = {<span class="hljs-string">"Roger"</span>, <span class="hljs-string">"Syd"</span>}
</code></pre>
<p>Sets work well when you think about them as mathematical sets.</p>
<p>You can intersect two sets:</p>
<pre><code class="lang-python">set1 = {<span class="hljs-string">"Roger"</span>, <span class="hljs-string">"Syd"</span>}
set2 = {<span class="hljs-string">"Roger"</span>}

intersect = set1 &amp; set2 <span class="hljs-comment">#{'Roger'}</span>
</code></pre>
<p>You can create a union of two sets:</p>
<pre><code class="lang-python">set1 = {<span class="hljs-string">"Roger"</span>, <span class="hljs-string">"Syd"</span>}
set2 = {<span class="hljs-string">"Luna"</span>}

union = set1 | set2
<span class="hljs-comment">#{'Syd', 'Luna', 'Roger'}</span>
</code></pre>
<p>You can get the difference between two sets:</p>
<pre><code class="lang-python">set1 = {<span class="hljs-string">"Roger"</span>, <span class="hljs-string">"Syd"</span>}
set2 = {<span class="hljs-string">"Roger"</span>}

difference = set1 - set2 <span class="hljs-comment">#{'Syd'}</span>
</code></pre>
<p>You can check if a set is a superset of another (and of course if a set is a subset of another):</p>
<pre><code class="lang-python">set1 = {<span class="hljs-string">"Roger"</span>, <span class="hljs-string">"Syd"</span>}
set2 = {<span class="hljs-string">"Roger"</span>}

isSuperset = set1 &gt; set2 <span class="hljs-comment"># True</span>
</code></pre>
<p>You can count the items in a set with the <code>len()</code> global function:</p>
<pre><code class="lang-python">names = {<span class="hljs-string">"Roger"</span>, <span class="hljs-string">"Syd"</span>}
len(names) <span class="hljs-comment"># 2</span>
</code></pre>
<p>You can get a list from the items in a set by passing the set to the <code>list()</code> constructor:</p>
<pre><code class="lang-python">names = {<span class="hljs-string">"Roger"</span>, <span class="hljs-string">"Syd"</span>}
list(names) <span class="hljs-comment">#['Syd', 'Roger']</span>
</code></pre>
<p>You can check if an item is contained in a set with the <code>in</code> operator:</p>
<pre><code class="lang-python">print(<span class="hljs-string">"Roger"</span> <span class="hljs-keyword">in</span> names) <span class="hljs-comment"># True</span>
</code></pre>
<h2 id="heading-functions-in-python">Functions in Python</h2>
<p>A function lets us create a set of instructions that we can run when needed.</p>
<p>Functions are essential in Python and in many other programming languages. They help us create meaningful programs, because they allow us to decompose a program into manageable parts, and they promote readability and code reuse.</p>
<p>Here is an example function called <code>hello</code> that prints "Hello!":</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hello</span>():</span>
    print(<span class="hljs-string">'Hello!'</span>)
</code></pre>
<p>This is the function <strong>definition</strong>. Thereis a name (<code>hello</code>) and a body, the set of instructions, which is the part that follows the colon. It's indented one level on the right.</p>
<p>To run this function, we must call it. This is the syntax to call the function:</p>
<pre><code class="lang-python">hello()
</code></pre>
<p>We can execute this function once, or multiple times.</p>
<p>The name of the function, <code>hello</code>, is very important. It should be descriptive, so anyone calling it can imagine what the function does.</p>
<p>A function can accept one or more parameters:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hello</span>(<span class="hljs-params">name</span>):</span>
    print(<span class="hljs-string">'Hello '</span> + name + <span class="hljs-string">'!'</span>)
</code></pre>
<p>In this case we call the function by passing the argument</p>
<pre><code class="lang-python">hello(<span class="hljs-string">'Roger'</span>)
</code></pre>
<blockquote>
<p>We call <em>parameters</em> the values accepted by the function inside the function definition, and <em>arguments</em> the values we pass to the function when we call it. It's common to get confused about this distinction.</p>
</blockquote>
<p>An argument can have a default value that's applied if the argument is not specified:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hello</span>(<span class="hljs-params">name=<span class="hljs-string">'my friend'</span></span>):</span>
    print(<span class="hljs-string">'Hello '</span> + name + <span class="hljs-string">'!'</span>)

hello()
<span class="hljs-comment">#Hello my friend!</span>
</code></pre>
<p>Here's how we can accept multiple parameters:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hello</span>(<span class="hljs-params">name, age</span>):</span>
    print(<span class="hljs-string">'Hello '</span> + name + <span class="hljs-string">', you are '</span> + str(age) + <span class="hljs-string">' years old!'</span>)
</code></pre>
<p>In this case we call the function passing a set of arguments:</p>
<pre><code class="lang-python">hello(<span class="hljs-string">'Roger'</span>, <span class="hljs-number">8</span>)
</code></pre>
<p>Parameters are passed by reference. All types in Python are objects, but some of them are immutable, including integers, booleans, floats, strings, and tuples. This means that if you pass them as parameters and you modify their value inside the function, the new value is not reflected outside of the function:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">change</span>(<span class="hljs-params">value</span>):</span>
    value = <span class="hljs-number">2</span>

val = <span class="hljs-number">1</span>
change(val)

print(val) <span class="hljs-comment">#1</span>
</code></pre>
<p>If you pass an object that's not immutable, and you change one of its properties, the change will be reflected outside.</p>
<p>A function can return a value, using the <code>return</code> statement. For example in this case we return the <code>name</code> parameter name:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hello</span>(<span class="hljs-params">name</span>):</span>
    print(<span class="hljs-string">'Hello '</span> + name + <span class="hljs-string">'!'</span>)
    <span class="hljs-keyword">return</span> name
</code></pre>
<p>When the function meets the <code>return</code> statement, the function ends.</p>
<p>We can omit the value:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hello</span>(<span class="hljs-params">name</span>):</span>
    print(<span class="hljs-string">'Hello '</span> + name + <span class="hljs-string">'!'</span>)
    <span class="hljs-keyword">return</span>
</code></pre>
<p>We can have the return statement inside a conditional, which is a common way to end a function if a starting condition is not met:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hello</span>(<span class="hljs-params">name</span>):</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> name:
        <span class="hljs-keyword">return</span>
    print(<span class="hljs-string">'Hello '</span> + name + <span class="hljs-string">'!'</span>)
</code></pre>
<p>If we call the function passing a value that evaluates to <code>False</code>, like an empty string, the function is terminated before reaching the <code>print()</code> statement.</p>
<p>You can return multiple values by using comma separated values:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hello</span>(<span class="hljs-params">name</span>):</span>
    print(<span class="hljs-string">'Hello '</span> + name + <span class="hljs-string">'!'</span>)
    <span class="hljs-keyword">return</span> name, <span class="hljs-string">'Roger'</span>, <span class="hljs-number">8</span>
</code></pre>
<p>In this case calling <code>hello('Syd')</code> the return value is a tuple containing those 3 values: <code>('Syd', 'Roger', 8)</code>.</p>
<h2 id="heading-objects-in-python">Objects in Python</h2>
<p>Everything in Python is an object.</p>
<p>Even values of basic primitive types (integer, string, float..) are objects. Lists are objects, as are tuples, dictionaries, everything.</p>
<p>Objects have <strong>attributes</strong> and <strong>methods</strong> that can be accessed using the dot syntax.</p>
<p>For example, try defining a new variable of type <code>int</code>:</p>
<pre><code class="lang-python">age = <span class="hljs-number">8</span>
</code></pre>
<p><code>age</code> now has access to the properties and methods defined for all <code>int</code> objects.</p>
<p>This includes, for example, access to the real and imaginary part of that number:</p>
<pre><code class="lang-python">print(age.real) <span class="hljs-comment"># 8</span>
print(age.imag) <span class="hljs-comment"># 0</span>

print(age.bit_length()) <span class="hljs-comment">#4</span>

<span class="hljs-comment"># the bit_length() method returns the number of bits necessary to represent this number in binary notation</span>
</code></pre>
<p>A variable holding a list value has access to a different set of methods:</p>
<pre><code class="lang-python">items = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
items.append(<span class="hljs-number">3</span>)
items.pop()
</code></pre>
<p>The methods depend on the type of value.</p>
<p>The <code>id()</code> global function provided by Python lets you inspect the location in memory for a particular object.</p>
<pre><code class="lang-python">id(age) <span class="hljs-comment"># 140170065725376</span>
</code></pre>
<blockquote>
<p>Your memory value will change - I am only showing it as an example.</p>
</blockquote>
<p>If you assign a different value to the variable, its address will change, because the content of the variable has been replaced with another value stored in another location in memory:</p>
<pre><code class="lang-python">age = <span class="hljs-number">8</span>

print(id(age)) <span class="hljs-comment"># 140535918671808</span>

age = <span class="hljs-number">9</span>

print(id(age)) <span class="hljs-comment"># 140535918671840</span>
</code></pre>
<p>But if you modify the object using its methods, the address stays the same:</p>
<pre><code class="lang-python">items = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>]

print(id(items)) <span class="hljs-comment"># 140093713593920</span>

items.append(<span class="hljs-number">3</span>)

print(items) <span class="hljs-comment"># [1, 2, 3]</span>
print(id(items)) <span class="hljs-comment"># 140093713593920</span>
</code></pre>
<p>The address only changes if you reassign a variable to another value.</p>
<p>Some objects are <em>mutable</em>, while others are <em>immutable</em>. This depends on the object itself. </p>
<p>If the object provides methods to change its content, then it's mutable. Otherwise it's immutable. </p>
<p>Most types defined by Python are immutable. For example an <code>int</code> is immutable. There are no methods to change its value. If you increment the value using</p>
<pre><code class="lang-python">age = <span class="hljs-number">8</span>
age = age + <span class="hljs-number">1</span>

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

age += <span class="hljs-number">1</span>
</code></pre>
<p>and you check with <code>id(age)</code>, you will find that <code>age</code> points to a different memory location. The original value has not mutated, we just switched to another value.</p>
<h2 id="heading-loops-in-python">Loops in Python</h2>
<p>Loops are one essential part of programming.</p>
<p>In Python we have 2 kinds of loops: <strong>while loops</strong> and <strong>for loops</strong>.</p>
<h3 id="heading-while-loops-in-python"><code>while</code> loops in Python</h3>
<p><code>while</code> loops are defined using the <code>while</code> keyword, and they repeat their block until the condition is evaluated as <code>False</code>:</p>
<pre><code class="lang-python">condition = <span class="hljs-literal">True</span>
<span class="hljs-keyword">while</span> condition == <span class="hljs-literal">True</span>:
    print(<span class="hljs-string">"The condition is True"</span>)
</code></pre>
<p>This is an <strong>infinite loop</strong>. It never ends.</p>
<p>Let's halt the loop right after the first iteration:</p>
<pre><code class="lang-python">condition = <span class="hljs-literal">True</span>
<span class="hljs-keyword">while</span> condition == <span class="hljs-literal">True</span>:
    print(<span class="hljs-string">"The condition is True"</span>)
    condition = <span class="hljs-literal">False</span>

print(<span class="hljs-string">"After the loop"</span>)
</code></pre>
<p>In this case, the first iteration is run, as the condition test is evaluated to <code>True</code>. At the second iteration, the condition test evaluates to <code>False</code>, so the control goes to the next instruction after the loop.</p>
<p>It's common to have a counter to stop the iteration after some number of cycles:</p>
<pre><code class="lang-python">count = <span class="hljs-number">0</span>
<span class="hljs-keyword">while</span> count &lt; <span class="hljs-number">10</span>:
    print(<span class="hljs-string">"The condition is True"</span>)
    count = count + <span class="hljs-number">1</span>

print(<span class="hljs-string">"After the loop"</span>)
</code></pre>
<h3 id="heading-for-loops-in-python"><code>for</code> loops in Python</h3>
<p>Using <code>for</code> loops we can tell Python to execute a block for a pre-determined amount of times, up front, and without the need of a separate variable and conditional to check its value.</p>
<p>For example we can iterate the items in a list:</p>
<pre><code class="lang-python">items = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
<span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> items:
    print(item)
</code></pre>
<p>Or, you can iterate a specific amount of times using the <code>range()</code> function:</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> range(<span class="hljs-number">04</span>):
    print(item)
</code></pre>
<p><code>range(4)</code> creates a sequence that starts from 0 and contains 4 items: <code>[0, 1, 2, 3]</code>.</p>
<p>To get the index, you should wrap the sequence into the <code>enumerate()</code> function:</p>
<pre><code class="lang-python">items = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
<span class="hljs-keyword">for</span> index, item <span class="hljs-keyword">in</span> enumerate(items):
    print(index, item)
</code></pre>
<h3 id="heading-break-and-continue-in-python">Break and continue in Python</h3>
<p>Both <code>while</code> and <code>for</code> loops can be interrupted inside the block, using two special keywords: <code>break</code> and <code>continue</code>.</p>
<p><code>continue</code> stops the current iteration and tells Python to execute the next one.</p>
<p><code>break</code> stops the loop altogether, and goes on with the next instruction after the loop ends.</p>
<p>The first example here prints <code>1, 3, 4</code>. The second example prints <code>1</code>:</p>
<pre><code class="lang-python">items = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
<span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> items:
    <span class="hljs-keyword">if</span> item == <span class="hljs-number">2</span>:
        <span class="hljs-keyword">continue</span>
    print(item)
</code></pre>
<pre><code class="lang-python">items = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
<span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> items:
    <span class="hljs-keyword">if</span> item == <span class="hljs-number">2</span>:
        <span class="hljs-keyword">break</span>
    print(item)
</code></pre>
<h2 id="heading-classes-in-python">Classes in Python</h2>
<p>In addition to using the Python-provided types, we can declare our own classes, and from classes we can instantiate objects.</p>
<p>An object is an instance of a class. A class is the type of an object.</p>
<p>We can define a class in this way:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> &lt;<span class="hljs-title">class_name</span>&gt;:</span>
    <span class="hljs-comment"># my class</span>
</code></pre>
<p>For example let's define a Dog class</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>:</span>
    <span class="hljs-comment"># the Dog class</span>
</code></pre>
<p>A class can define methods:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>:</span>
    <span class="hljs-comment"># the Dog class</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">bark</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">'WOF!'</span>)
</code></pre>
<blockquote>
<p><code>self</code> as the argument of the method points to the current object instance, and must be specified when defining a method.</p>
</blockquote>
<p>We create an instance of a class, an <strong>object</strong>, using this syntax:</p>
<pre><code class="lang-python">roger = Dog()
</code></pre>
<p>Now <code>roger</code> is a new object of type Dog.</p>
<p>If you run</p>
<pre><code class="lang-python">print(type(roger))
</code></pre>
<p>You will get <code>&lt;class '__main__.Dog'&gt;</code></p>
<p>A special type of method, <code>__init__()</code> is called constructor, and we can use it to initialize one or more properties when we create a new object from that class:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>:</span>
    <span class="hljs-comment"># the Dog class</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, name, age</span>):</span>
        self.name = name
        self.age = age

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">bark</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">'WOF!'</span>)
</code></pre>
<p>We use it in this way:</p>
<pre><code class="lang-python">roger = Dog(<span class="hljs-string">'Roger'</span>, <span class="hljs-number">8</span>)
print(roger.name) <span class="hljs-comment"># 'Roger'</span>
print(roger.age)  <span class="hljs-comment"># 8</span>

roger.bark() <span class="hljs-comment"># 'WOF!'</span>
</code></pre>
<p>One important feature of classes is inheritance.</p>
<p>We can create an Animal class with a method <code>walk()</code>:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">walk</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">'Walking..'</span>)
</code></pre>
<p>and the Dog class can inherit from Animal:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>(<span class="hljs-params">Animal</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">bark</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">'WOF!'</span>)
</code></pre>
<p>Now creating a new object of class <code>Dog</code> will have the <code>walk()</code> method as that's inherited from <code>Animal</code>:</p>
<pre><code class="lang-python">roger = Dog()
roger.walk() <span class="hljs-comment"># 'Walking..'</span>
roger.bark() <span class="hljs-comment"># 'WOF!'</span>
</code></pre>
<h2 id="heading-modules-in-python">Modules in Python</h2>
<p>Every Python file is a module.</p>
<p>You can import a module from other files, and that's the base of any program of moderate complexity, as it promotes a sensible organization and code reuse.</p>
<p>In the typical Python program, one file acts as the entry point. The other files are modules and expose functions that we can call from other files.</p>
<p>The file <code>dog.py</code> contains this code:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">bark</span>():</span>
    print(<span class="hljs-string">'WOF!'</span>)
</code></pre>
<p>We can import this function from another file using <code>import</code>. And once we do, we can reference the function using the dot notation, <code>dog.bark()</code>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> dog

dog.bark()
</code></pre>
<p>Or, we can use the <code>from .. import</code> syntax and call the function directly:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> dog <span class="hljs-keyword">import</span> bark

bark()
</code></pre>
<p>The first strategy allows us to load everything defined in a file.</p>
<p>The second strategy lets us pick the things we need.</p>
<p>Those modules are specific to your program, and importing depends on the location of the file in the filesystem.</p>
<p>Suppose you put <code>dog.py</code> in a <code>lib</code> subfolder.</p>
<p>In that folder, you need to create an empty file named <code>__init__.py</code>. This tells Python the folder contains modules.</p>
<p>Now you can choose - you can import <code>dog</code> from <code>lib</code>:</p>
<pre><code class="lang-py"><span class="hljs-keyword">from</span> lib <span class="hljs-keyword">import</span> dog

dog.bark()
</code></pre>
<p>or you can reference the <code>dog</code> module specific function importing from <code>lib.dog</code>:</p>
<pre><code class="lang-py"><span class="hljs-keyword">from</span> lib.dog <span class="hljs-keyword">import</span> bark

bark()
</code></pre>
<h2 id="heading-the-python-standard-library">The Python Standard Library</h2>
<p>Python exposes a lot of built-in functionality through its <strong>standard library</strong>.</p>
<p>The standard library is a huge collection of all sort of utilities, ranging from math utilities to debugging to creating graphical user interfaces.</p>
<p>You can find the full list of standard library modules here: https://docs.python.org/3/library/index.html</p>
<p>Some of the important modules are:</p>
<ul>
<li><code>math</code> for math utilities</li>
<li><code>re</code> for regular expressions</li>
<li><code>json</code> to work with JSON</li>
<li><code>datetime</code> to work with dates</li>
<li><code>sqlite3</code> to use SQLite</li>
<li><code>os</code> for Operating System utilities</li>
<li><code>random</code> for random number generation</li>
<li><code>statistics</code> for statistics utilities</li>
<li><code>requests</code> to perform HTTP network requests</li>
<li><code>http</code> to create HTTP servers</li>
<li><code>urllib</code> to manage URLs</li>
</ul>
<p>Let's introduce how to <em>use</em> a module of the standard library. You already know how to use modules you create, importing from other files in the program folder.</p>
<p>Well that's the same with modules provided by the standard library:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> math

math.sqrt(<span class="hljs-number">4</span>) <span class="hljs-comment"># 2.0</span>
</code></pre>
<p>or</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> sqrt

sqrt(<span class="hljs-number">4</span>) <span class="hljs-comment"># 2.0</span>
</code></pre>
<p>We'll soon explore the most important modules individually to understand what we can do with them.</p>
<h2 id="heading-the-pep8-python-style-guide">The PEP8 Python Style Guide</h2>
<p>When you write code, you should adhere to the conventions of the programming language you use.</p>
<p>If you learn the right naming and formatting conventions right from the start, it will be easier to read code written by other people, and people will find your code easier to read.</p>
<p>Python defines its conventions in the PEP8 style guide. PEP stands for <em>Python Enhancement Proposals</em> and it's the place where all Python language enhancements and discussions happen. </p>
<p>There are a lot of PEP proposals, all available at https://www.python.org/dev/peps/.</p>
<p>PEP8 is one of the first ones, and one of the most important, too. It defines the formatting and also some rules on how to write Python in a "pythonic" way.</p>
<p>You can read its full content here: https://www.python.org/dev/peps/pep-0008/ but here's a quick summary of the important points you can start with:</p>
<ul>
<li>Indent using spaces, not tabs</li>
<li>Indent using 4 spaces.</li>
<li>Python files are encoded in UTF-8</li>
<li>Use maximum 80 columns for your code</li>
<li>Write each statement on its own line</li>
<li>Functions, variable names and file names are lowercase, with underscores between words (snake_case)</li>
<li>Class names are capitalized, separate words are written with the capital letter too, (CamelCase)</li>
<li>Package names are lowercase and do not have underscores between words</li>
<li>Variables that should not change (constants) are written in uppercase</li>
<li>Variable names should be meaningful</li>
<li>Add useful comments, but avoid obvious comments</li>
<li>Add spaces around operators</li>
<li>Do not use unnecessary whitespace</li>
<li>Add a blank line before a function</li>
<li>Add a blank line between methods in a class</li>
<li>Inside functions/methods, blank lines can be used to separate related blocks of code to help readability</li>
</ul>
<h2 id="heading-debugging-in-python">Debugging in Python</h2>
<p>Debugging is one of the best skills you can learn, as it will help you in many difficult situations.</p>
<p>Every language has its debugger. Python has <code>pdb</code>, available through the standard library.</p>
<p>You debug by adding one breakpoint into your code:</p>
<pre><code class="lang-python">breakpoint()
</code></pre>
<blockquote>
<p>You can add more breakpoints if needed.</p>
</blockquote>
<p>When the Python interpreter hits a breakpoint in your code, it will stop, and it will tell you what is the next instruction it will run.</p>
<p>Then and you can do a few things.</p>
<p>You can type the name of any variable to inspect its value.</p>
<p>You can press <code>n</code> to step to the next line in the current function. If the code calls functions, the debugger does not get into them, and considers them "black boxes".</p>
<p>You can press <code>s</code> to step to the next line in the current function. If the next line is a function, the debugger goes into that, and you can then run one instruction of that function at a time.</p>
<p>You can press <code>c</code> to continue the execution of the program normally, without the need to do it step-by-step.</p>
<p>You can press <code>q</code> to stop the execution of the program.</p>
<p>Debugging is useful to evaluate the result of an instruction, and it's especially good to know how to use it when you have complex iterations or algorithms that you want to fix.</p>
<h2 id="heading-variable-scope-in-python">Variable Scope in Python</h2>
<p>When you declare a variable, that variable is visible in parts of your program, depending on where you declare it.</p>
<p>If you declare it outside of any function, the variable is visible to any code running after the declaration, including functions:</p>
<pre><code class="lang-python">age = <span class="hljs-number">8</span>

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

print(age) <span class="hljs-comment"># 8</span>
test() <span class="hljs-comment"># 8</span>
</code></pre>
<p>We call it a <strong>global variable</strong>.</p>
<p>If you define a variable inside a function, that variable is a <strong>local variable</strong>, and it is only visible inside that function. Outside the function, it is not reachable:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test</span>():</span>
    age = <span class="hljs-number">8</span>
    print(age)

test() <span class="hljs-comment"># 8</span>

print(age)
<span class="hljs-comment"># NameError: name 'age' is not defined</span>
</code></pre>
<h2 id="heading-how-to-accept-arguments-from-the-command-line-in-python">How to Accept Arguments from the Command Line in Python</h2>
<p>Python offers several ways to handle arguments passed when we invoke the program from the command line.</p>
<p>So far you've run programs either from a REPL, or using</p>
<pre><code class="lang-sh">python &lt;filename&gt;.py
</code></pre>
<p>You can pass additional arguments and options when you do so, like this:</p>
<pre><code class="lang-sh">python &lt;filename&gt;.py &lt;argument1&gt;
python &lt;filename&gt;.py &lt;argument1&gt; &lt;argument2&gt;
</code></pre>
<p>A basic way to handle those arguments is to use the <code>sys</code> module from the standard library.</p>
<p>You can get the arguments passed in the <code>sys.argv</code> list:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sys
print(len(sys.argv))
print(sys.argv)
</code></pre>
<p>The <code>sys.argv</code> list contains as the first item the name of the file that was run, for example <code>['main.py']</code>.</p>
<p>This is a simple way, but you have to do a lot of work. You need to validate arguments, make sure their type is correct, and you need to print feedback to the user if they are not using the program correctly.</p>
<p>Python provides another package in the standard library to help you: <code>argparse</code>.</p>
<p>First you import <code>argparse</code> and you call <code>argparse.ArgumentParser()</code>, passing the description of your program:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> argparse

parser = argparse.ArgumentParser(
    description=<span class="hljs-string">'This program prints the name of my dogs'</span>
)
</code></pre>
<p>Then you proceed to add arguments you want to accept.
For example in this program we accept a <code>-c</code> option to pass a color, like this: <code>python program.py -c red</code></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> argparse

parser = argparse.ArgumentParser(
    description=<span class="hljs-string">'This program prints a color HEX value'</span>
)

parser.add_argument(<span class="hljs-string">'-c'</span>, <span class="hljs-string">'--color'</span>, metavar=<span class="hljs-string">'color'</span>, required=<span class="hljs-literal">True</span>, help=<span class="hljs-string">'the color to search for'</span>)

args = parser.parse_args()

print(args.color) <span class="hljs-comment"># 'red'</span>
</code></pre>
<p>If the argument is not specified, the program raises an error:</p>
<pre><code>➜  python python program.py
<span class="hljs-attr">usage</span>: program.py [-h] -c color
program.py: error: the following <span class="hljs-built_in">arguments</span> are required: -c
</code></pre><p>You can set an option to have a specific set of values, using <code>choices</code>:</p>
<pre><code class="lang-python">parser.add_argument(<span class="hljs-string">'-c'</span>, <span class="hljs-string">'--color'</span>, metavar=<span class="hljs-string">'color'</span>, required=<span class="hljs-literal">True</span>, choices={<span class="hljs-string">'red'</span>,<span class="hljs-string">'yellow'</span>}, help=<span class="hljs-string">'the color to search for'</span>)
</code></pre>
<pre><code>➜  python python program.py -c blue
<span class="hljs-attr">usage</span>: program.py [-h] -c color
program.py: error: argument -c/--color: invalid choice: <span class="hljs-string">'blue'</span> (choose <span class="hljs-keyword">from</span> <span class="hljs-string">'yellow'</span>, <span class="hljs-string">'red'</span>)
</code></pre><p>There are more options, but those are the basics.</p>
<p>And there are community packages that provide this functionality, too, like <a target="_blank" href="https://click.palletsprojects.com/en/7.x/">Click</a> and <a target="_blank" href="https://python-prompt-toolkit.readthedocs.io/en/master/index.html">Python Prompt Toolkit</a>.</p>
<h2 id="heading-lambda-functions-in-python">Lambda Functions in Python</h2>
<p>Lambda functions (also called anonymous functions) are tiny functions that have no name and only have one expression as their body.</p>
<p>In Python they are defined using the <code>lambda</code> keyword:</p>
<pre><code class="lang-python"><span class="hljs-keyword">lambda</span> &lt;arguments&gt; : &lt;expression&gt;
</code></pre>
<p>The body must be a single expression - an expression, not a statement.</p>
<blockquote>
<p>This difference is important. An expression returns a value, a statement does not.</p>
</blockquote>
<p>The simplest example of a lambda function is a function that doubles the value of a number:</p>
<pre><code class="lang-python"><span class="hljs-keyword">lambda</span> num : num * <span class="hljs-number">2</span>
</code></pre>
<p>Lambda functions can accept more arguments:</p>
<pre><code class="lang-python"><span class="hljs-keyword">lambda</span> a, b : a * b
</code></pre>
<p>Lambda functions cannot be invoked directly, but you can assign them to variables:</p>
<pre><code class="lang-python">multiply = <span class="hljs-keyword">lambda</span> a, b : a * b

print(multiply(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>)) <span class="hljs-comment"># 4</span>
</code></pre>
<p>The utility of lambda functions comes when combined with other Python functionality, for example in combination with <code>map()</code>, <code>filter()</code> and <code>reduce()</code>.</p>
<h2 id="heading-recursion-in-python">Recursion in Python</h2>
<p>A function in Python can call itself. That's what recursion is. And it can be pretty useful in many scenarios.</p>
<p>The common way to explain recursion is by using the factorial calculation.</p>
<p>The factorial of a number is the number <code>n</code> mutiplied by <code>n-1</code>, multiplied by <code>n-2</code>... and so on, until reaching the number <code>1</code>:</p>
<pre><code><span class="hljs-number">3</span>! = <span class="hljs-number">3</span> * <span class="hljs-number">2</span> * <span class="hljs-number">1</span> = <span class="hljs-number">6</span>
<span class="hljs-number">4</span>! = <span class="hljs-number">4</span> * <span class="hljs-number">3</span> * <span class="hljs-number">2</span> * <span class="hljs-number">1</span> = <span class="hljs-number">24</span>
<span class="hljs-number">5</span>! = <span class="hljs-number">5</span> * <span class="hljs-number">4</span> * <span class="hljs-number">3</span> * <span class="hljs-number">2</span> * <span class="hljs-number">1</span> = <span class="hljs-number">120</span>
</code></pre><p>Using recursion we can write a function that calculates the factorial of any number:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">factorial</span>(<span class="hljs-params">n</span>):</span>
    <span class="hljs-keyword">if</span> n == <span class="hljs-number">1</span>: <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>
    <span class="hljs-keyword">return</span> n * factorial(n<span class="hljs-number">-1</span>)

print(factorial(<span class="hljs-number">3</span>)) <span class="hljs-comment">#   6</span>
print(factorial(<span class="hljs-number">4</span>)) <span class="hljs-comment">#  24</span>
print(factorial(<span class="hljs-number">5</span>)) <span class="hljs-comment"># 120</span>
</code></pre>
<p>If inside the <code>factorial()</code> function you call <code>factorial(n)</code> instead of <code>factorial(n-1)</code>, you are going to cause an infinite recursion. Python by default will halt recursions at 1000 calls, and when this limit is reached, you will get a <code>RecursionError</code> error.</p>
<p>Recursion is helpful in many places, and it helps us simplify our code when there's no other optimal way to do it, so it's good to know this technique.</p>
<h2 id="heading-nested-functions-in-python">Nested Functions in Python</h2>
<p>Functions in Python can be nested inside other functions.</p>
<p>A function defined inside a function is visible only inside that function.</p>
<p>This is useful to create utilities that are useful to a function, but not useful outside of it.</p>
<p>You might ask: why should I be "hiding" this function, if it does no harm?</p>
<p>One, because it's always best to hide functionality that's local to a function, and is not useful elsewhere.</p>
<p>Also, because we can make use of closures (more on this later).</p>
<p>Here is an example:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">talk</span>(<span class="hljs-params">phrase</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">say</span>(<span class="hljs-params">word</span>):</span>
        print(word)

    words = phrase.split(<span class="hljs-string">' '</span>)
    <span class="hljs-keyword">for</span> word <span class="hljs-keyword">in</span> words:
        say(word)

talk(<span class="hljs-string">'I am going to buy the milk'</span>)
</code></pre>
<p>If you want to access a variable defined in the outer function from the inner function, you first need to declare it as <code>nonlocal</code>:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">count</span>():</span>
    count = <span class="hljs-number">0</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">increment</span>():</span>
        <span class="hljs-keyword">nonlocal</span> count
        count = count + <span class="hljs-number">1</span>
        print(count)

    increment()

count()
</code></pre>
<p>This is useful especially with closures, as we'll see next.</p>
<h2 id="heading-closures-in-python">Closures in Python</h2>
<p>If you return a nested function from a function, that nested function has access to the variables defined in that function, even if that function is not active any more.</p>
<p>Here is a simple counter example.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">counter</span>():</span>
    count = <span class="hljs-number">0</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">increment</span>():</span>
        <span class="hljs-keyword">nonlocal</span> count
        count = count + <span class="hljs-number">1</span>
        <span class="hljs-keyword">return</span> count

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

increment = counter()

print(increment()) <span class="hljs-comment"># 1</span>
print(increment()) <span class="hljs-comment"># 2</span>
print(increment()) <span class="hljs-comment"># 3</span>
</code></pre>
<p>We return the <code>increment()</code> inner function, and that still has access to the state of the <code>count</code> variable even though the <code>counter()</code> function has ended.</p>
<h2 id="heading-decorators-in-python">Decorators in Python</h2>
<p>Decorators are a way to change, enhance, or alter in any way how a function works.</p>
<p>Decorators are defined with the <code>@</code> symbol followed by the decorator name, just before the function definition.</p>
<p>Example:</p>
<pre><code class="lang-python"><span class="hljs-meta">@logtime</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hello</span>():</span>
    print(<span class="hljs-string">'hello!'</span>)
</code></pre>
<p>This <code>hello</code> function has the <code>logtime</code> decorator assigned.</p>
<p>Whenever we call <code>hello()</code>, the decorator is going to be called.</p>
<p>A decorator is a function that takes a function as a parameter, wraps the function in an inner function that performs the job it has to do, and returns that inner function. In other words:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">logtime</span>(<span class="hljs-params">func</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapper</span>():</span>
        <span class="hljs-comment"># do something before</span>
        val = func()
        <span class="hljs-comment"># do something after</span>
        <span class="hljs-keyword">return</span> val
    <span class="hljs-keyword">return</span> wrapper
</code></pre>
<h2 id="heading-docstrings-in-python">Docstrings in Python</h2>
<p>Documentation is hugely important, not just to communicate to other people what the goal of a function/class/method/module is, but it also communicates it to yourself.</p>
<p>When you come back to your code 6 or 12 months from now, you might not remember all the knowledge you are holding in your head. At that point, reading your code and understanding what it is supposed to do will be much more difficult.</p>
<p>Comments are one way to help yourself (and others) out:</p>
<pre><code class="lang-python"><span class="hljs-comment"># this is a comment</span>

num = <span class="hljs-number">1</span> <span class="hljs-comment">#this is another comment</span>
</code></pre>
<p>Another way is to use <strong>docstrings</strong>.</p>
<p>The utility of docstrings is that they follow conventions. As such they can be processed automatically.</p>
<p>This is how you define a docstring for a function:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">increment</span>(<span class="hljs-params">n</span>):</span>
    <span class="hljs-string">"""Increment a number"""</span>
    <span class="hljs-keyword">return</span> n + <span class="hljs-number">1</span>
</code></pre>
<p>This is how you define a docstring for a class and a method:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>:</span>
    <span class="hljs-string">"""A class representing a dog"""</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, name, age</span>):</span>
        <span class="hljs-string">"""Initialize a new dog"""</span>
        self.name = name
        self.age = age

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">bark</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-string">"""Let the dog bark"""</span>
        print(<span class="hljs-string">'WOF!'</span>)
</code></pre>
<p>Document a module by placing a docstring at the top of the file, for example supposing this is <code>dog.py</code>:</p>
<pre><code class="lang-python"><span class="hljs-string">"""Dog module

This module does ... bla bla bla and provides the following classes:

- Dog
...
"""</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>:</span>
    <span class="hljs-string">"""A class representing a dog"""</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, name, age</span>):</span>
        <span class="hljs-string">"""Initialize a new dog"""</span>
        self.name = name
        self.age = age

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">bark</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-string">"""Let the dog bark"""</span>
        print(<span class="hljs-string">'WOF!'</span>)
</code></pre>
<p>Docstrings can span multiple lines:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">increment</span>(<span class="hljs-params">n</span>):</span>
    <span class="hljs-string">"""Increment
    a number
    """</span>
    <span class="hljs-keyword">return</span> n + <span class="hljs-number">1</span>
</code></pre>
<p>Python will process those and you can use the <code>help()</code> global function to get the documentation for a class/method/function/module.</p>
<p>For example calling <code>help(increment)</code> will give you this:</p>
<pre><code>Help on <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">increment</span> <span class="hljs-title">in</span> <span class="hljs-title">module</span>
<span class="hljs-title">__main__</span>:

<span class="hljs-title">increment</span>(<span class="hljs-params">n</span>)
    <span class="hljs-title">Increment</span>
    <span class="hljs-title">a</span> <span class="hljs-title">number</span></span>
</code></pre><p>There are many different standards to format docstrings, and you can choose to adhere to your favorite one.</p>
<p>I like Google's standard: https://github.com/google/styleguide/blob/gh-pages/pyguide.md#38-comments-and-docstrings</p>
<p>Standards allow to have tools to extract docstrings and automatically generate documentation for your code.</p>
<h2 id="heading-introspection-in-python">Introspection in Python</h2>
<p>Functions, variables, and objects can be analyzed using <strong>introspection</strong>.</p>
<p>First, using the <code>help()</code> global function we can get the documentation if provided in form of docstrings.</p>
<p>Then, you can use print() to get information about a function:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">increment</span>(<span class="hljs-params">n</span>):</span>
    <span class="hljs-keyword">return</span> n + <span class="hljs-number">1</span>

print(increment)

<span class="hljs-comment"># &lt;function increment at 0x7f420e2973a0&gt;</span>
</code></pre>
<p>or an object:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>():</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">bark</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">'WOF!'</span>)

roger = Dog()

print(roger)

<span class="hljs-comment"># &lt;__main__.Dog object at 0x7f42099d3340&gt;</span>
</code></pre>
<p>The <code>type()</code> function gives us the type of an object:</p>
<pre><code class="lang-python">print(type(increment))
<span class="hljs-comment"># &lt;class 'function'&gt;</span>

print(type(roger))
<span class="hljs-comment"># &lt;class '__main__.Dog'&gt;</span>

print(type(<span class="hljs-number">1</span>))
<span class="hljs-comment"># &lt;class 'int'&gt;</span>

print(type(<span class="hljs-string">'test'</span>))
<span class="hljs-comment"># &lt;class 'str'&gt;</span>
</code></pre>
<p>The <code>dir()</code> global function lets us find out all the methods and attributes of an object:</p>
<pre><code class="lang-python">print(dir(roger))

<span class="hljs-comment"># ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'bark']</span>
</code></pre>
<p>The <code>id()</code> global function shows us the location in memory of any object:</p>
<pre><code class="lang-python">print(id(roger)) <span class="hljs-comment"># 140227518093024</span>
print(id(<span class="hljs-number">1</span>))     <span class="hljs-comment"># 140227521172384</span>
</code></pre>
<p>It can be useful to check if two variables point to the same object.</p>
<p>The <code>inspect</code> standard library module gives us more tools to get information about objects, and you can check it out here: https://docs.python.org/3/library/inspect.html</p>
<h2 id="heading-annotations-in-python">Annotations in Python</h2>
<p>Python is dynamically typed. We do not have to specify the type of a variable or function parameter, or a function return value.</p>
<p>Annotations allow us to (optionally) do that.</p>
<p>This is a function without annotations:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">increment</span>(<span class="hljs-params">n</span>):</span>
    <span class="hljs-keyword">return</span> n + <span class="hljs-number">1</span>
</code></pre>
<p>This is the same function with annotations:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">increment</span>(<span class="hljs-params">n: int</span>) -&gt; int:</span>
    <span class="hljs-keyword">return</span> n + <span class="hljs-number">1</span>
</code></pre>
<p>You can also annotate variables:</p>
<pre><code class="lang-python">count: int = <span class="hljs-number">0</span>
</code></pre>
<p>Python will ignore those annotations. A separate tool called <a target="_blank" href="http://mypy-lang.org/"><code>mypy</code></a> can be run standalone, or integrated by IDE like VS Code or PyCharm to automatically check for type errors statically, while you are coding. It will also help you catch type mismatch bugs before even running the code.</p>
<p>A great help especially when your software becomes large and you need to refactor your code.</p>
<h2 id="heading-exceptions-in-python">Exceptions in Python</h2>
<p>It's important to have a way to handle errors, and Python gives us exception handling to do so.</p>
<p>If you wrap lines of code into a <code>try:</code> block:</p>
<pre><code class="lang-python"><span class="hljs-keyword">try</span>:
    <span class="hljs-comment"># some lines of code</span>
</code></pre>
<p>If an error occurs, Python will alert you and you can determine which kind of error occurred using a <code>except</code> blocks:</p>
<pre><code class="lang-python"><span class="hljs-keyword">try</span>:
    <span class="hljs-comment"># some lines of code</span>
<span class="hljs-keyword">except</span> &lt;ERROR1&gt;:
    <span class="hljs-comment"># handler &lt;ERROR1&gt;</span>
<span class="hljs-keyword">except</span> &lt;ERROR2&gt;:
    <span class="hljs-comment"># handler &lt;ERROR2&gt;</span>
</code></pre>
<p>To catch all exceptions you can use <code>except</code> without any error type:</p>
<pre><code class="lang-python"><span class="hljs-keyword">try</span>:
    <span class="hljs-comment"># some lines of code</span>
<span class="hljs-keyword">except</span> &lt;ERROR1&gt;:
    <span class="hljs-comment"># handler &lt;ERROR1&gt;</span>
<span class="hljs-keyword">except</span>:
    <span class="hljs-comment"># catch all other exceptions</span>
</code></pre>
<p>The <code>else</code> block is run if no exceptions were found:</p>
<pre><code class="lang-python"><span class="hljs-keyword">try</span>:
    <span class="hljs-comment"># some lines of code</span>
<span class="hljs-keyword">except</span> &lt;ERROR1&gt;:
    <span class="hljs-comment"># handler &lt;ERROR1&gt;</span>
<span class="hljs-keyword">except</span> &lt;ERROR2&gt;:
    <span class="hljs-comment"># handler &lt;ERROR2&gt;</span>
<span class="hljs-keyword">else</span>:
    <span class="hljs-comment"># no exceptions were raised, the code ran successfully</span>
</code></pre>
<p>A <code>finally</code> block lets you perform some operation in any case, regardless of whether an error occurred or not:</p>
<pre><code class="lang-python"><span class="hljs-keyword">try</span>:
    <span class="hljs-comment"># some lines of code</span>
<span class="hljs-keyword">except</span> &lt;ERROR1&gt;:
    <span class="hljs-comment"># handler &lt;ERROR1&gt;</span>
<span class="hljs-keyword">except</span> &lt;ERROR2&gt;:
    <span class="hljs-comment"># handler &lt;ERROR2&gt;</span>
<span class="hljs-keyword">else</span>:
    <span class="hljs-comment"># no exceptions were raised, the code ran successfully</span>
<span class="hljs-keyword">finally</span>:
    <span class="hljs-comment"># do something in any case</span>
</code></pre>
<p>The specific error that's going to occur depends on the operation you're performing.</p>
<p>For example if you are reading a file, you might get an <code>EOFError</code>. If you divide a number by zero you will get a <code>ZeroDivisionError</code>. If you have a type conversion issue you might get a <code>TypeError</code>.</p>
<p>Try this code:</p>
<pre><code class="lang-python">result = <span class="hljs-number">2</span> / <span class="hljs-number">0</span>
print(result)
</code></pre>
<p>The program will terminate with an error:</p>
<pre><code>Traceback (most recent call last):
  File <span class="hljs-string">"main.py"</span>, line <span class="hljs-number">1</span>, <span class="hljs-keyword">in</span> &lt;<span class="hljs-built_in">module</span>&gt;
    result = <span class="hljs-number">2</span> / <span class="hljs-number">0</span>
<span class="hljs-attr">ZeroDivisionError</span>: division by zero
</code></pre><p>and the lines of code after the error will not be executed.</p>
<p>Adding that operation in a <code>try:</code> block lets us recover gracefully and move on with the program:</p>
<pre><code class="lang-python"><span class="hljs-keyword">try</span>:
    result = <span class="hljs-number">2</span> / <span class="hljs-number">0</span>
<span class="hljs-keyword">except</span> ZeroDivisionError:
    print(<span class="hljs-string">'Cannot divide by zero!'</span>)
<span class="hljs-keyword">finally</span>:
    result = <span class="hljs-number">1</span>

print(result) <span class="hljs-comment"># 1</span>
</code></pre>
<p>You can raise exceptions in your own code, too, using the <code>raise</code> statement:</p>
<pre><code class="lang-python"><span class="hljs-keyword">raise</span> Exception(<span class="hljs-string">'An error occurred!'</span>)
</code></pre>
<p>This raises a general exception, and you can intercept it using:</p>
<pre><code class="lang-python"><span class="hljs-keyword">try</span>:
    <span class="hljs-keyword">raise</span> Exception(<span class="hljs-string">'An error occurred!'</span>)
<span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> error:
    print(error)
</code></pre>
<p>You can also define your own exception class, extending from Exception:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DogNotFoundException</span>(<span class="hljs-params">Exception</span>):</span>
    <span class="hljs-keyword">pass</span>
</code></pre>
<blockquote>
<p><code>pass</code> here means "nothing" and we must use it when we define a class without methods, or a function without code, too.</p>
</blockquote>
<pre><code class="lang-python"><span class="hljs-keyword">try</span>:
    <span class="hljs-keyword">raise</span> DogNotFoundException()
<span class="hljs-keyword">except</span> DogNotFoundException:
    print(<span class="hljs-string">'Dog not found!'</span>)
</code></pre>
<h2 id="heading-the-with-statement-in-python">The <code>with</code> Statement in Python</h2>
<p>The <code>with</code> statement is very helpful to simplify working with exception handling.</p>
<p>For example when working with files, each time we open a file, we must remember to close it.</p>
<p><code>with</code> makes this process transparent.</p>
<p>Instead of writing:</p>
<pre><code class="lang-python">filename = <span class="hljs-string">'/Users/flavio/test.txt'</span>

<span class="hljs-keyword">try</span>:
    file = open(filename, <span class="hljs-string">'r'</span>)
    content = file.read()
    print(content)
<span class="hljs-keyword">finally</span>:
    file.close()
</code></pre>
<p>You can write:</p>
<pre><code class="lang-python">filename = <span class="hljs-string">'/Users/flavio/test.txt'</span>

<span class="hljs-keyword">with</span> open(filename, <span class="hljs-string">'r'</span>) <span class="hljs-keyword">as</span> file:
    content = file.read()
    print(content)
</code></pre>
<p>In other words we have built-in implicit exception handling, as <code>close()</code> will be called automatically for us.</p>
<p><code>with</code> is not just helpful to work with files. The above example is just meant to introduce its capabilities.</p>
<h2 id="heading-how-to-install-3rd-party-packages-in-python-using-pip">How to Install 3rd Party Packages in Python Using <code>pip</code></h2>
<p>The Python standard library contains a huge number of utilities that simplify our Python development needs, but nothing can satisfy <em>everything</em>.</p>
<p>That's why individuals and companies create packages, and make them available as open source software for the entire community.</p>
<p>Those modules are all collected in a single place, the <strong>Python Package Index</strong> available at https://pypi.org, and they can be installed on your system using <code>pip</code>.</p>
<p>There are more than 270,000 packages freely available at the time of writing.</p>
<blockquote>
<p>You should have <code>pip</code> already installed if you followed the Python installation instructions.</p>
</blockquote>
<p>Install any package using the command <code>pip install</code>:</p>
<pre><code>pip install &lt;package&gt;
</code></pre><p>or, if you do have troubles, you can also run it through <code>python -m</code>:</p>
<pre><code>python -m pip install &lt;package&gt;
</code></pre><p>For example you can install the <a target="_blank" href="https://pypi.org/project/requests/"><code>requests</code></a> package, a popular HTTP library:</p>
<pre><code>pip install requests
</code></pre><p>and once you do, it will be available for all your Python scripts, because packages are installed globally.</p>
<p>The exact location depends on your operating system.</p>
<p>On macOS, running Python 3.9, the location is <code>/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages</code>.</p>
<p>Upgrade a package to its latest version using:</p>
<pre><code>pip install –U &lt;package&gt;
</code></pre><p>Install a specific version of a package using:</p>
<pre><code>pip install &lt;package&gt;==<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span></span>
</code></pre><p>Uninstall a package using:</p>
<pre><code>pip uninstall &lt;package&gt;
</code></pre><p>Show an installed package details, including version, documentation website and author information using:</p>
<pre><code>pip show &lt;package&gt;
</code></pre><h2 id="heading-list-comprehensions-in-python">List Comprehensions in Python</h2>
<p>List comprehensions are a way to create lists in a very concise way.</p>
<p>Suppose you have a list:</p>
<pre><code class="lang-python">numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]
</code></pre>
<p>You can create a new list using a list comprehension, composed by the <code>numbers</code> list elements, power 2:</p>
<pre><code class="lang-python">numbers_power_2 = [n**<span class="hljs-number">2</span> <span class="hljs-keyword">for</span> n <span class="hljs-keyword">in</span> numbers]
<span class="hljs-comment"># [1, 4, 9, 16, 25]</span>
</code></pre>
<p>List comprehensions are a syntax that's sometimes preferred over loops, as it's more readable when the operation can be written on a single line:</p>
<pre><code class="lang-python">numbers_power_2 = []
<span class="hljs-keyword">for</span> n <span class="hljs-keyword">in</span> numbers:
    numbers_power_2.append(n**<span class="hljs-number">2</span>)
</code></pre>
<p>and over <code>map()</code>:</p>
<pre><code class="lang-python">numbers_power_2 = list(map(<span class="hljs-keyword">lambda</span> n : n**<span class="hljs-number">2</span>, numbers))
</code></pre>
<h2 id="heading-polymorphism-in-python">Polymorphism in Python</h2>
<p>Polymorphism generalizes a functionality so it can work on different types. It's an important concept in object-oriented programming.</p>
<p>We can define the same method on different classes:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">eat</span>():</span>
        print(<span class="hljs-string">'Eating dog food'</span>)

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">eat</span>():</span>
        print(<span class="hljs-string">'Eating cat food'</span>)
</code></pre>
<p>Then we can generate objects and we can call the <code>eat()</code> method regardless of the class the object belongs to, and we'll get different results:</p>
<pre><code class="lang-python">animal1 = Dog()
animal2 = Cat()

animal1.eat()
animal2.eat()
</code></pre>
<p>We built a generalized interface and we now do not need to know that an animal is a Cat or a Dog.</p>
<h2 id="heading-operator-overloading-in-python">Operator Overloading in Python</h2>
<p>Operator overloading is an advanced technique we can use to make classes comparable and to make them work with Python operators.</p>
<p>Let's take a class Dog:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>:</span>
    <span class="hljs-comment"># the Dog class</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, name, age</span>):</span>
        self.name = name
        self.age = age
</code></pre>
<p>Let's create 2 Dog objects:</p>
<pre><code class="lang-python">roger = Dog(<span class="hljs-string">'Roger'</span>, <span class="hljs-number">8</span>)
syd = Dog(<span class="hljs-string">'Syd'</span>, <span class="hljs-number">7</span>)
</code></pre>
<p>We can use operator overloading to add a way to compare those 2 objects, based on the <code>age</code> property:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>:</span>
    <span class="hljs-comment"># the Dog class</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, name, age</span>):</span>
        self.name = name
        self.age = age
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__gt__</span>(<span class="hljs-params">self, other</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span> <span class="hljs-keyword">if</span> self.age &gt; other.age <span class="hljs-keyword">else</span> <span class="hljs-literal">False</span>
</code></pre>
<p>Now if you try running <code>print(roger &gt; syd)</code> you will get the result <code>True</code>.</p>
<p>In the same way we defined <code>__gt__()</code> (which means greater than), we can define the following methods:</p>
<ul>
<li><code>__eq__()</code> to check for equality</li>
<li><code>__lt__()</code> to check if an object should be considered lower than another with the <code>&lt;</code> operator</li>
<li><code>__le__()</code> for lower or equal (<code>&lt;=</code>)</li>
<li><code>__ge__()</code> for greater or equal (<code>&gt;=</code>)</li>
<li><code>__ne__()</code> for not equal (<code>!=</code>)</li>
</ul>
<p>Then you have methods to interoperate with arithmetic operations:</p>
<ul>
<li><code>__add__()</code> respond to the <code>+</code> operator</li>
<li><code>__sub__()</code> respond to the <code>–</code> operator</li>
<li><code>__mul__()</code> respond to the <code>*</code> operator</li>
<li><code>__truediv__()</code> respond to the <code>/</code> operator</li>
<li><code>__floordiv__()</code> respond to the <code>//</code> operator</li>
<li><code>__mod__()</code> respond to the <code>%</code> operator</li>
<li><code>__pow__()</code> respond to the <code>**</code> operator</li>
<li><code>__rshift__()</code> respond to the <code>&gt;&gt;</code> operator</li>
<li><code>__lshift__()</code> respond to the <code>&lt;&lt;</code> operator</li>
<li><code>__and__()</code> respond to the <code>&amp;</code> operator</li>
<li><code>__or__()</code> respond to the <code>|</code> operator</li>
<li><code>__xor__()</code> respond to the <code>^</code> operator</li>
</ul>
<p>There are a few more methods to work with other operators, but you get the idea.</p>
<h2 id="heading-virtual-environments-in-python">Virtual Environments in Python</h2>
<p>It's common to have multiple Python applications running on your system.</p>
<p>When applications require the same module, at some point you will reach a tricky situation where an app needs a version of a module, and another app a different version of that same module.</p>
<p>To solve this, you use <strong>virtual environments</strong>.</p>
<p>We'll use <code>venv</code>. Other tools work similarly, like <code>pipenv</code>.</p>
<p>Create a virtual environment using</p>
<pre><code class="lang-sh">python -m venv .venv
</code></pre>
<p>in the folder where you want to start the project, or where you already have an existing project.</p>
<p>Then run</p>
<pre><code class="lang-sh"><span class="hljs-built_in">source</span> .venv/bin/activate
</code></pre>
<blockquote>
<p>Use <code>source .venv/bin/activate.fish</code> on the Fish shell</p>
</blockquote>
<p>Executing the program will activate the Python virtual environment. Depending on your configuration you might also see your terminal prompt change.</p>
<p>Mine changed from</p>
<p><code>➜ folder</code></p>
<p>to</p>
<p><code>(.venv) ➜ folder</code></p>
<p>Now running <code>pip</code> will use this virtual environment instead of the global environment.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Thanks a lot for reading this book.</p>
<p>I hope it will inspire you to learn more about Python.</p>
<p>For more on Python and programming tutorials in general, check out my blog <a target="_blank" href="https://flaviocopes.com">flaviocopes.com</a>.</p>
<p>Send any feedback, errata, or opinions at <a target="_blank" href="mailto:flavio@flaviocopes.com">flavio@flaviocopes.com</a>, and you can reach me on Twitter <a target="_blank" href="https://twitter.com/flaviocopes">@flaviocopes</a>.</p>
<blockquote>
<p>Note: You can <a target="_blank" href="https://flaviocopes.com/page/python-handbook/">get a PDF, ePub and Mobi version of this Python Handbook</a></p>
</blockquote>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ React for Beginners – A React.js Handbook for Front End Developers ]]>
                </title>
                <description>
                    <![CDATA[ React is one of the most popular JavaScript frameworks ever created, and I believe that it's one of the best tools out there. The goal of this handbook is to provide a starter guide to learning React. At the end of the book, you'll have a basic under... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-beginner-handbook/</link>
                <guid isPermaLink="false">66bb5a89965d5c9ed5487bac</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Flavio Copes ]]>
                </dc:creator>
                <pubDate>Fri, 13 Nov 2020 17:02:22 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/11/book-2.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>React is one of the most popular JavaScript frameworks ever created, and I believe that it's one of the best tools out there.</p>
<p>The goal of this handbook is to provide a starter guide to learning React.</p>
<p>At the end of the book, you'll have a basic understanding of:</p>
<ul>
<li>What React is and why it's so popular</li>
<li>How to install React</li>
<li>React Components</li>
<li>React State</li>
<li>React Props</li>
<li>Handling user events in React</li>
<li>Lifecycle events in a React component</li>
</ul>
<p>These topics will be the base upon which you will build in other more advanced React tutorials.</p>
<p>This book is especially written for JavaScript programmers who are new to React. So let's get started.</p>
<h2 id="heading-what-is-react">What is React?</h2>
<p>React is a JavaScript library that aims to simplify the development of visual interfaces.</p>
<p>Developed at Facebook and released to the world in 2013, it drives some of the most widely used apps, powering Facebook and Instagram among countless other applications.</p>
<p>Its primary goal is to make it easy to reason about an interface and its state at any point in time. It does this by dividing the UI into a collection of components.</p>
<p>You might experience some initial difficulties when learning React. But once it "clicks", I guarantee it's going to be one of the best experiences you ever have. React makes many things easier, and its ecosystem is filled with great libraries and tools.</p>
<p>React in itself has a very small API, and you basically need to understand 4 concepts to get started:</p>
<ul>
<li>Components</li>
<li>JSX</li>
<li>State</li>
<li>Props</li>
</ul>
<p>We'll explore all of these in this book, and we'll leave the more advanced concepts to other tutorials. I will give you some pointers in the last section about how to move forward.</p>
<p>And you can <a target="_blank" href="https://flaviocopes.com/page/react-handbook/">download this handbook in PDF / ePub / Mobi format for free</a>.</p>
<h2 id="heading-summary-of-the-handbook">Summary of the handbook</h2>
<ul>
<li><a class="post-section-overview" href="#heading-how-much-javascript-you-need-to-know-to-use-react">How much JavaScript you need to know to use React</a></li>
<li><a class="post-section-overview" href="#heading-why-should-you-learn-react">Why should you learn React?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-install-react">How to install React</a></li>
<li><a class="post-section-overview" href="#heading-react-components">React Components</a></li>
<li><a class="post-section-overview" href="#heading-introduction-to-jsx">Introduction to JSX</a></li>
<li><a class="post-section-overview" href="#heading-using-jsx-to-compose-a-ui">Using JSX to compose a UI</a></li>
<li><a class="post-section-overview" href="#heading-the-difference-between-jsx-and-html">The difference between JSX and HTML</a></li>
<li><a class="post-section-overview" href="#heading-embedding-javascript-in-jsx">Embedding JavaScript in JSX</a></li>
<li><a class="post-section-overview" href="#heading-managing-state-in-react">Managing state in React</a></li>
<li><a class="post-section-overview" href="#heading-component-props-in-react">Component Props in React</a></li>
<li><a class="post-section-overview" href="#heading-data-flow-in-a-react-application">Data flow in a React application</a></li>
<li><a class="post-section-overview" href="#heading-handling-user-events-in-react">Handling user events in React</a></li>
<li><a class="post-section-overview" href="#heading-lifecycle-events-in-a-react-component">Lifecycle events in a React component</a></li>
<li><a class="post-section-overview" href="#heading-where-to-go-from-here">Where to go from here</a></li>
</ul>
<h2 id="heading-how-much-javascript-you-need-to-know-to-use-react">How much JavaScript you need to know to use React</h2>
<p>Before jumping straight into React, you should have a good understanding of some core JavaScript concepts.</p>
<p>You don't have to be a JavaScript expert, but I think you need a good overview of:</p>
<ul>
<li><a target="_blank" href="https://flaviocopes.com/javascript-variables/">Variables</a></li>
<li><a target="_blank" href="https://flaviocopes.com/javascript-arrow-functions/">Arrow functions</a></li>
<li><a target="_blank" href="https://flaviocopes.com/javascript-rest-spread/">Work with objects and arrays using Rest and Spread</a></li>
<li><a target="_blank" href="https://flaviocopes.com/javascript-destructuring/">Object and array destructuring</a></li>
<li><a target="_blank" href="https://flaviocopes.com/javascript-template-literals/">Template literals</a></li>
<li><a target="_blank" href="https://flaviocopes.com/javascript-callbacks/">Callbacks</a></li>
<li><a target="_blank" href="https://flaviocopes.com/es-modules/">ES Modules</a></li>
</ul>
<p>If those concepts sound unfamiliar, I've provided you with some links to find out more about those subjects.</p>
<h2 id="heading-why-should-you-learn-react">Why should you learn React?</h2>
<p>I highly recommend that any Web developer has at least a basic understanding of React.</p>
<p>That's because of a few reasons.</p>
<ol>
<li>React is very popular. As a developer, it's quite likely that you're going to work on a React project in the future. Perhaps an existing project, or maybe your team will want you to work on a brand new app based on React.</li>
<li>A lot of tooling today is built using React at the core. Popular frameworks and tools like Next.js, Gatsby, and many others use React under the hood.</li>
<li>As a frontend engineer, React is probably going to come up in a job interview.</li>
</ol>
<p>Those are all good reasons, but one of the main reasons I want you to learn React is that it's great.</p>
<p>It promotes several good development practices, including code reusability and component-driven development. It is fast, it is lightweight, and the way it makes you think about the data flow in your application perfectly suits a lot of common scenarios.</p>
<h2 id="heading-how-to-install-react">How to install React</h2>
<p>There are a few different ways to install React.</p>
<p>To start with, I highly recommend one approach, and that's using the officially recommended tool called <code>create-react-app</code>.</p>
<p><code>create-react-app</code> is a command line application, aimed at getting you up to speed with React in no time.</p>
<p>You start by using <code>npx</code>, which is an easy way to download and execute Node.js commands without installing them.</p>
<blockquote>
<p>See my npx guide here: <a target="_blank" href="https://flaviocopes.com/npx/">https://flaviocopes.com/npx/</a></p>
</blockquote>
<p><code>npx</code> comes with <code>npm</code> (since version 5.2). If you don't have npm installed already, do it now from <a target="_blank" href="https://nodejs.org">https://nodejs.org</a> (npm is installed with Node).</p>
<p>If you are unsure which version of npm you have, run <code>npm -v</code> to check if you need to update.</p>
<blockquote>
<p>Tip: check out my OSX terminal tutorial at <a target="_blank" href="https://flaviocopes.com/macos-terminal/">https://flaviocopes.com/macos-terminal/</a> if you're unfamiliar with using the terminal. It applies to Mac and Linux.</p>
</blockquote>
<p>When you run <code>npx create-react-app &lt;app-name&gt;</code>, <code>npx</code> is going to <em>download</em> the most recent <code>create-react-app</code> release, run it, and then remove it from your system. </p>
<p>This is great because you will never have an outdated version on your system, and every time you run it, you're getting the latest and greatest code available.</p>
<p>Let's start then:</p>
<pre><code class="lang-sh">npx create-react-app todolist
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/cra-start.png" alt="cra-start" width="600" height="400" loading="lazy"></p>
<p>This is when it finished running:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/create-react-app-finished.png" alt="create-react-app-finished" width="600" height="400" loading="lazy"></p>
<p><code>create-react-app</code> created a file structure in the folder you told it to (<code>todolist</code> in this case), and initialized a <a target="_blank" href="https://flaviocopes.com/git/">Git</a> repository.</p>
<p>It also added a few commands in the <code>package.json</code> file:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/cra-packagejson.png" alt="cra-packagejson" width="600" height="400" loading="lazy"></p>
<p>So you can immediately start the app by going into the newly created application folder and running <code>npm start</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/cra-running.png" alt="cra-running" width="600" height="400" loading="lazy"></p>
<p>By default this command launches the app on your local port 3000, and it opens your browser showing you the welcome screen:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/cra-browser.png" alt="cra-browser" width="600" height="400" loading="lazy"></p>
<p>Now you're ready to work on this application!</p>
<h2 id="heading-react-components">React Components</h2>
<p>In the last section you saw how to create your first React application.</p>
<p>This application comes with a series of files that do various things, mostly related to configuration, but there's one file that stands out: <code>App.js</code>.</p>
<p><code>App.js</code> is the <strong>first React Component</strong> you meet.</p>
<p>Its code is this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> logo <span class="hljs-keyword">from</span> <span class="hljs-string">'./logo.svg'</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./App.css'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">header</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App-header"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">{logo}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App-logo"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"logo"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
          Edit <span class="hljs-tag">&lt;<span class="hljs-name">code</span>&gt;</span>src/App.js<span class="hljs-tag">&lt;/<span class="hljs-name">code</span>&gt;</span> and save to reload.
        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">a</span>
          <span class="hljs-attr">className</span>=<span class="hljs-string">"App-link"</span>
          <span class="hljs-attr">href</span>=<span class="hljs-string">"https://reactjs.org"</span>
          <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>
          <span class="hljs-attr">rel</span>=<span class="hljs-string">"noopener noreferrer"</span>
        &gt;</span>
          Learn React
        <span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>An application built using React, or one of the other popular frontend frameworks like Vue and Svelte for example, is built using dozens of components.</p>
<p>But let's start by analyzing this first component. I'm going to simplify this component code like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> logo <span class="hljs-keyword">from</span> <span class="hljs-string">'./logo.svg'</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./App.css'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-comment">/* something */</span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>You can see a few things here. We <em>import</em> some things, and we <em>export</em> a function called <code>App</code>.</p>
<p>The things we import in this case are a JavaScript library (the <code>react</code> npm package), an SVG image, and a CSS file.</p>
<blockquote>
<p><code>create-react-app</code> is set up in a way that allows us to import images and CSS to use in our JavaScript, but this is not something you need to care about now. What you need to care about is the concept of a <strong>component</strong></p>
</blockquote>
<p><code>App</code> is a function that, in the original example, returns something that at first sight looks quite strange.</p>
<p>It looks like <strong>HTML</strong> but it has some JavaScript embedded into it.</p>
<p>That is <strong>JSX</strong>, a special language we use to build a component's output. We'll talk more about JSX in the next section.</p>
<p>In addition to defining some JSX to return, a component has several other characteristics.</p>
<p>A component can have its own <strong>state</strong>, which means it encapsulates some variables that other components can't access unless this component exposes this state to the rest of the application.</p>
<p>A component can also receive data from other components. In this case we're talking about <strong>props</strong>.</p>
<p>Don't worry, we're going to look in detail at all those terms (JSX, State and Props) soon.</p>
<h2 id="heading-introduction-to-jsx">Introduction to JSX</h2>
<p>We can't talk about React without first explaining JSX.</p>
<p>In the last section you met your first React component, the <code>App</code> component defined in the default application built by <code>create-react-app</code>.</p>
<p>Its code was this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> logo <span class="hljs-keyword">from</span> <span class="hljs-string">'./logo.svg'</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./App.css'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">header</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App-header"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">{logo}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App-logo"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"logo"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
          Edit <span class="hljs-tag">&lt;<span class="hljs-name">code</span>&gt;</span>src/App.js<span class="hljs-tag">&lt;/<span class="hljs-name">code</span>&gt;</span> and save to reload.
        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">a</span>
          <span class="hljs-attr">className</span>=<span class="hljs-string">"App-link"</span>
          <span class="hljs-attr">href</span>=<span class="hljs-string">"https://reactjs.org"</span>
          <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>
          <span class="hljs-attr">rel</span>=<span class="hljs-string">"noopener noreferrer"</span>
        &gt;</span>
          Learn React
        <span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>We previously ignored everything that was inside the <code>return</code> statement, but in this section we're going to talk about it.</p>
<p>We call JSX everything wrapped inside the parentheses returned by the component:</p>
<pre><code class="lang-jsx">&lt;div className=<span class="hljs-string">"App"</span>&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">header</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App-header"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">{logo}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App-logo"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"logo"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
      Edit <span class="hljs-tag">&lt;<span class="hljs-name">code</span>&gt;</span>src/App.js<span class="hljs-tag">&lt;/<span class="hljs-name">code</span>&gt;</span> and save to reload.
    <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">a</span>
      <span class="hljs-attr">className</span>=<span class="hljs-string">"App-link"</span>
      <span class="hljs-attr">href</span>=<span class="hljs-string">"https://reactjs.org"</span>
      <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>
      <span class="hljs-attr">rel</span>=<span class="hljs-string">"noopener noreferrer"</span>
    &gt;</span>
      Learn React
    <span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span></span>
&lt;/div&gt;
</code></pre>
<p>This <em>looks</em> like HTML, but it's not really HTML. It's a little different.</p>
<p>And it's a bit strange to have this code inside a JavaScript file. This does not look like JavaScript at all!</p>
<p>Under the hood, React will process the JSX and it will transform it into JavaScript that the browser will be able to interpret.</p>
<p>So we're writing JSX, but in the end there's a translation step that makes it digestible to a JavaScript interpreter.</p>
<p>React gives us this interface for one reason: <strong>it's easier to build UI interfaces using JSX</strong>.</p>
<p>Once you get more familiar with it, of course.</p>
<p>In the next section we'll talk about how JSX lets you easily compose a UI, then we'll look at the differences with "normal HTML" that you need to know.</p>
<h2 id="heading-using-jsx-to-compose-a-ui">Using JSX to compose a UI</h2>
<p>As introduced in the last section, one of the main benefits of JSX is that it makes it very easy to build a UI.</p>
<p>In particular, in a React component you can import other React components, and you can embed them and display them.</p>
<p>A React component is usually created in its own file, because that's how we can easily reuse it (by importing it) in other components.</p>
<p>But a React component can also be created in the same file of another component, if you plan to only use it in that component. There's no "rule" here, you can do what feels best to you.</p>
<p>I generally use separate files when the number of lines in a file grows too much.</p>
<p>To keep things simple let's create a component in the same <code>App.js</code> file.</p>
<p>We're going to create a <code>WelcomeMessage</code> component:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">WelcomeMessage</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Welcome!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
}
</code></pre>
<p>See? It's a simple function that returns a line of JSX that represents a <code>p</code> HTML element.</p>
<p>We're going to add it to the <code>App.js</code> file.</p>
<p>Now inside the <code>App</code> component JSX we can add <code>&lt;WelcomeMessage /&gt;</code> to show this component in the user interface:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> logo <span class="hljs-keyword">from</span> <span class="hljs-string">'./logo.svg'</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./App.css'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">WelcomeMessage</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Welcome!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">header</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App-header"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">{logo}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App-logo"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"logo"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
          Edit <span class="hljs-tag">&lt;<span class="hljs-name">code</span>&gt;</span>src/App.js<span class="hljs-tag">&lt;/<span class="hljs-name">code</span>&gt;</span> and save to reload.
        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">WelcomeMessage</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">a</span>
          <span class="hljs-attr">className</span>=<span class="hljs-string">"App-link"</span>
          <span class="hljs-attr">href</span>=<span class="hljs-string">"https://reactjs.org"</span>
          <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>
          <span class="hljs-attr">rel</span>=<span class="hljs-string">"noopener noreferrer"</span>
        &gt;</span>
          Learn React
        <span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>And here's the result. Can you see the "Welcome!" message in the screen?</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/new-component.png" alt="new-component" width="600" height="400" loading="lazy"></p>
<p>We say that <code>WelcomeMessage</code> is a <strong>child component</strong> of App, and <code>App</code> is its parent componnet.</p>
<p>We're adding the <code>&lt;WelcomeMessage /&gt;</code> component as if it was part of the HTML language.</p>
<p>That's the beauty of React components and JSX: we can compose an application interface and use it like we're writing HTML.</p>
<p>With some differences, as we'll see in the next section.</p>
<h2 id="heading-the-difference-between-jsx-and-html">The difference between JSX and HTML</h2>
<p>JSX kind of looks like HTML, but it's not.</p>
<p>In this section I want to introduce you to some of the most important things you need to keep in mind when using JSX.</p>
<p>One of the differences might be quite obvious if you looked at the <code>App</code> component JSX: there's a strange attribute called <code>className</code>.</p>
<p>In HTML we use the <code>class</code> attribute. It's probably the most widely used attribute, for various reasons. One of those reasons is CSS. The <code>class</code> attribute allows us to style HTML elements easily, and CSS frameworks like Tailwind put this attribute to the center of the CSS user interface design process.</p>
<p>But there's a problem. We are writing this UI code in a JavaScript file, and <code>class</code> in the JavaScript programming language is a reserved word. This means we can't use this reserved word as we want. It serves a specific purpose (defining JavaScript classes) and the React creators had to choose a different name for it.</p>
<p>That's how we ended up with <code>className</code> instead of <code>class</code>.</p>
<p>You need to remember this especially when you're copy/pasting some existing HTML.</p>
<p>React will try its best to make sure things don't break, but it will raise a lot of warnings in the Developer Tools:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/className.png" alt="className" width="600" height="400" loading="lazy"></p>
<p>This is not the only HTML feature that suffers from this problem, but it's the most common one.</p>
<p>Another big difference between JSX and HTML is that HTML is very <em>relaxed</em>, we can say. Even if you have an error in the syntax, or you close the wrong tag, or you have a mismatch, the browser will try its best to interpret the HTML without breaking.</p>
<p>It's one of the core features of the Web. It is very forgiving.</p>
<p>JSX is not forgiving. If you forget to close a tag, you will have a clear error message:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/jsx-error.png" alt="jsx-error" width="600" height="400" loading="lazy"></p>
<blockquote>
<p>React usually gives very good and informative error messages that point you in the right direction to fix the problem.</p>
</blockquote>
<p>Another big difference between JSX and HTML is that in JSX we can embed JavaScript.</p>
<p>Let's talk about this in the next section.</p>
<h2 id="heading-embedding-javascript-in-jsx">Embedding JavaScript in JSX</h2>
<p>One of the best features of React is that we can easily embed JavaScript into JSX.</p>
<p>Other frontend frameworks, for example Angular and Vue, have their own specific ways to print JavaScript values in the template, or perform things like loops.</p>
<p>React doesn't add new things. Instead, it lets us use JavaScript in the JSX, by using curly brackets.</p>
<p>The first example of this that I will show you comes directly from the <code>App</code> component we've studied so far.</p>
<p>We import the <code>logo</code> SVG file using</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> logo <span class="hljs-keyword">from</span> <span class="hljs-string">'./logo.svg'</span>
</code></pre>
<p>and then in the JSX we assign this SVG file to the <code>src</code> attribute of an <code>img</code> tag:</p>
<pre><code class="lang-js">&lt;img src={logo} className=<span class="hljs-string">"App-logo"</span> alt=<span class="hljs-string">"logo"</span> /&gt;
</code></pre>
<p>Let's do another example. Suppose the <code>App</code> component has a variable called <code>message</code>:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> message = <span class="hljs-string">'Hello!'</span>
  <span class="hljs-comment">//...</span>
}
</code></pre>
<p>We can print this value in the JSX by adding <code>{message}</code> anywhere in the JSX.</p>
<p>Inside the curly brackets <code>{ }</code> we can add any JavaScript statement, but <em>just one</em> statement for every curly bracket block.</p>
<p>And the statement must return something.</p>
<p>For example this is a common statement you will find in JSX. We have a ternary operator where we define a condition (<code>message === 'Hello!'</code>), and we print one value if the condition is true, or another value (the content of <code>message</code> in this case) if the condition is false:</p>
<pre><code class="lang-js">{
  message === <span class="hljs-string">'Hello!'</span> ? <span class="hljs-string">'The message was "Hello!"'</span> : message
}
</code></pre>
<h2 id="heading-managing-state-in-react">Managing state in React</h2>
<p>Every React component can have its own <strong>state</strong>.</p>
<p>What do we mean by <em>state</em>? The state is the <strong>set of data that is managed by the component</strong>.</p>
<p>Think about a form, for example. Each individual input element of the form is responsible for managing its state: what is written inside it.</p>
<p>A button is responsible for knowing if it's being clicked, or not. If it's on focus.</p>
<p>A link is responsible for knowing if the mouse is hovering over it.</p>
<p>In React, or in any other components-based framework/library, all our applications are based on and make heavy use of components' state.</p>
<p>We manage state using the <code>useState</code> utility provided by React. It's technically a <strong>hook</strong> (you don't need to know the details of hooks right now, but that's what it is).</p>
<p>You import <code>useState</code> from React in this way:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
</code></pre>
<p>Calling <code>useState()</code>, you will get back a new state variable, and a function that we can call to alter its value.</p>
<p><code>useState()</code> accepts the initial value of the state item and returns an array containing the state variable, and the function you call to alter the state.</p>
<p>Example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>)
</code></pre>
<p>This is important. We can't just alter the value of a state variable directly. We must call its modifier function. Otherwise the React component will not update its UI to reflect the changes of the data. </p>
<p>Calling the modifier is the way we can tell React that the component state has changed.</p>
<p>The syntax is a bit weird, right? Since <code>useState()</code> returns an array we use array destructuring to access each individual item, like this: <code>const [count, setCount] = useState(0)</code></p>
<p>Here's a practical example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>

<span class="hljs-keyword">const</span> Counter = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>)

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>You clicked {count} times<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setCount(count + 1)}&gt;Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}

ReactDOM.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Counter</span> /&gt;</span></span>, <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'app'</span>))
</code></pre>
<p>You can add as many <code>useState()</code> calls as you want, to create as many state variables as you want:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>)
<span class="hljs-keyword">const</span> [anotherCounter, setAnotherCounter] = useState(<span class="hljs-number">0</span>)
</code></pre>
<h2 id="heading-component-props-in-react">Component Props in React</h2>
<p>We call <code>props</code> the initial values passed to a component.</p>
<p>We previously created a <code>WelcomeMessage</code> component</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">WelcomeMessage</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Welcome!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
}
</code></pre>
<p>and we used it like this:</p>
<pre><code class="lang-js">&lt;WelcomeMessage /&gt;
</code></pre>
<p>This component does not have any initial value. It does not have props.</p>
<p>Props can be passed as attributes to the component in the JSX:</p>
<pre><code class="lang-js">&lt;WelcomeMessage myprop={<span class="hljs-string">'somevalue'</span>} /&gt;
</code></pre>
<p>and inside the component we receive the props as arguments:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">WelcomeMessage</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Welcome!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
}
</code></pre>
<p>It's common to use object destructuring to get the props by name:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">WelcomeMessage</span>(<span class="hljs-params">{ myprop }</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Welcome!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
}
</code></pre>
<p>Now that we have the prop, we can use it inside the component. For example we can print its value in the JSX:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">WelcomeMessage</span>(<span class="hljs-params">{ myprop }</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{myprop}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
}
</code></pre>
<p>Curly brackets here have various meanings. In the case of the function argument, curly brackets are used as part of the object destructuring syntax.</p>
<p>Then we use them to define the function code block, and finally in the JSX to print the JavaScript value.</p>
<p>Passing props to components is a great way to pass values around in your application.</p>
<p>A component either holds data (has state) or receives data through its props.</p>
<p>We can also send functions as props, so a child component can call a function in the parent component.</p>
<p>A special prop is called <code>children</code>. That contains the value of anything that is passed between the opening and closing tags of the component, for example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">WelcomeMessage</span>&gt;</span> Here is some message <span class="hljs-tag">&lt;/<span class="hljs-name">WelcomeMessage</span>&gt;</span>
</code></pre>
<p>In this case, inside <code>WelcomeMessage</code> we could access the value <code>Here is some message</code> by using the <code>children</code> prop:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">WelcomeMessage</span>(<span class="hljs-params">{ children }</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{children}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
}
</code></pre>
<h2 id="heading-data-flow-in-a-react-application">Data flow in a React application</h2>
<p>In a React application, data typically flows from a parent component to a child component, using props as we saw in the previous section:</p>
<pre><code class="lang-js">&lt;WelcomeMessage myprop={<span class="hljs-string">'somevalue'</span>} /&gt;
</code></pre>
<p>If you pass a function to the child component, you can however change the state of the parent component from a child component:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>)

&lt;Counter setCount={setCount} /&gt;
</code></pre>
<p>Inside the Counter component we can now grab the <code>setCount</code> prop and call it to update the <code>count</code> state in the parent component, when something happens:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Counter</span>(<span class="hljs-params">{ setCount }</span>) </span>{
  <span class="hljs-comment">//...</span>

  setCount(<span class="hljs-number">1</span>)

  <span class="hljs-comment">//...</span>
}
</code></pre>
<p>You need to know that there are more advanced ways to manage data, which include the Context API and libraries like Redux. But those introduce more complexity, and 90% of the times using those 2 ways I just explained are the perfect solution.</p>
<h2 id="heading-handling-user-events-in-react">Handling user events in React</h2>
<p>React provides an easy way to manage events fired from DOM events like clicks, form events, and more.</p>
<p>Let's talk about click events, which are pretty simple to digest.</p>
<p>You can use the <code>onClick</code> attribute on any JSX element:</p>
<pre><code class="lang-js">&lt;button
  onClick={<span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    <span class="hljs-comment">/* handle the event */</span>
  }}
&gt;
  Click here
&lt;/button&gt;
</code></pre>
<p>When the element is clicked, the function passed to the <code>onClick</code> attribute is fired.</p>
<p>You can define this function outside of the JSX:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> handleClickEvent = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
  <span class="hljs-comment">/* handle the event */</span>
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleClickEvent}</span>&gt;</span>Click here<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
}
</code></pre>
<p>When the <code>click</code> event is fired on the button, React calls the event handler function.</p>
<p>React supports a vast amount of types of events, like <code>onKeyUp</code>, <code>onFocus</code>,<code>onChange</code>, <code>onMouseDown</code>, <code>onSubmit</code> and many more.</p>
<h2 id="heading-lifecycle-events-in-a-react-component">Lifecycle events in a React component</h2>
<p>So far we've seen how to manage state with the <code>useState</code> hook.</p>
<p>There's another hook I want to introduce in this book: <code>useEffect</code>.</p>
<p>The <code>useEffect</code> hook allows components to have access to the lifecycle events of a component.</p>
<p>When you call the hook, you pass it a function. The function will be run by React when the component is first rendered, and on every subsequent re-render/update.</p>
<p>React first updates the DOM, then calls any function passed to <code>useEffect()</code>.</p>
<p>All without blocking the UI rendering, even on blocking code.</p>
<p>Here is an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> { useEffect, useState } = React

<span class="hljs-keyword">const</span> CounterWithNameAndSideEffect = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>)

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`You clicked <span class="hljs-subst">${count}</span> times`</span>)
  })

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>You clicked {count} times<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setCount(count + 1)}&gt;Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}
</code></pre>
<p>Since the useEffect() function is run on every subsequent re-render/update of the component, we can tell React to skip it, for performance purposes. We do this by adding a second parameter which is an array that contains a list of state variables to watch for. </p>
<p>React will only re-run the side effect if one of the items in this array changes.</p>
<pre><code class="lang-js">useEffect(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hi <span class="hljs-subst">${name}</span> you clicked <span class="hljs-subst">${count}</span> times`</span>)
}, [name, count])
</code></pre>
<p>Similarly, you can tell React to only execute the side effect once (at mount time), by passing an empty array:</p>
<pre><code class="lang-js">useEffect(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Component mounted`</span>)
}, [])
</code></pre>
<p>You migth find yourself using this option a lot.</p>
<p>useEffect() is great for adding logs, accessing 3rd party APIs, and much more.</p>
<h2 id="heading-where-to-go-from-here">Where to go from here</h2>
<p>Mastering the topics explained in this article is a great step towards your goal of learning React.</p>
<p>I want to give you some pointers now, because it's easy to get lost in the sea of tutorials and courses about React.</p>
<p>What should you learn next?</p>
<p>Learn more theory about the <a target="_blank" href="https://flaviocopes.com/react-virtual-dom/">Virtual DOM</a>, <a target="_blank" href="https://flaviocopes.com/react-declarative/">writing declarative code</a>, <a target="_blank" href="https://flaviocopes.com/react-unidirectional-data-flow/">unidirectional data flow</a>, <a target="_blank" href="https://flaviocopes.com/react-immutability/">immutability</a>, <a target="_blank" href="https://flaviocopes.com/react-composition/">composition</a>.</p>
<p>Start building some simple React applications. For example <a target="_blank" href="https://flaviocopes.com/react-example-counter/">build a simple counter</a> or a <a target="_blank" href="https://flaviocopes.com/react-example-githubusers/">interact with a public API</a>.</p>
<p>Learn how to perform <a target="_blank" href="https://flaviocopes.com/react-conditional-rendering/">conditional rendering</a>, how to perform <a target="_blank" href="https://flaviocopes.com/react-how-to-loop/">loops in JSX</a>, how to use the <a target="_blank" href="https://flaviocopes.com/react-developer-tools/">React Developer Tools</a>.</p>
<p>Learn how to apply CSS in a React application, with <a target="_blank" href="https://flaviocopes.com/react-css/">plain CSS</a> or <a target="_blank" href="https://flaviocopes.com/styled-components/">Styled Components</a>.</p>
<p>Learn how to manage state using the <a target="_blank" href="https://flaviocopes.com/react-context-api/">Context API</a>, useContext and <a target="_blank" href="https://flaviocopes.com/redux/">Redux</a>.</p>
<p>Learn how to interact with <a target="_blank" href="https://flaviocopes.com/react-forms/">forms</a>.</p>
<p>Learn how to use <a target="_blank" href="https://flaviocopes.com/react-router/">React Router</a>.</p>
<p>Learn <a target="_blank" href="https://flaviocopes.com/react-testing-components/">how to test React applications</a>.</p>
<p>Learn an application framework built on top of React, like <a target="_blank" href="https://flaviocopes.com/gatsby/">Gatsby</a> or <a target="_blank" href="https://flaviocopes.com/nextjs/">Next.js</a>.</p>
<p>Most of all, make sure you practice by building sample applications to apply everything you've learned.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Thanks a lot for reading this handbook.</p>
<p>I hope it will inspire you to learn more about React and everything you can do with it!</p>
<p>Remember that you can <a target="_blank" href="https://flaviocopes.com/page/react-handbook/">download this handbook in PDF / ePub / Mobi format for free</a> if you want.</p>
<p>I publish programming tutorials every day on my website <a target="_blank" href="https://flaviocopes.com">flaviocopes.com</a> if you want to check out more great content like this.</p>
<p>You can reach me on Twitter <a target="_blank" href="https://twitter.com/flaviocopes">@flaviocopes</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Linux Command Handbook – Learn Linux Commands for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ This Linux Command Handbook will cover 60 core Bash commands you will need as a developer. Each command includes example code and tips for when to use it. This Linux Command Handbook follows the 80/20 rule: you'll learn 80% of a topic in around 20% o... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-linux-commands-handbook/</link>
                <guid isPermaLink="false">66bb5aadb6e566d0c2aea60f</guid>
                
                    <category>
                        <![CDATA[ Linux ]]>
                    </category>
                
                    <category>
                        <![CDATA[ unix ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Flavio Copes ]]>
                </dc:creator>
                <pubDate>Tue, 03 Nov 2020 21:24:38 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/10/cover-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>This Linux Command Handbook will cover 60 core Bash commands you will need as a developer. Each command includes example code and tips for when to use it.</p>
<p>This Linux Command Handbook follows the 80/20 rule: you'll learn 80% of a topic in around 20% of the time you spend studying it.</p>
<p>I find that this approach gives you a well-rounded overview. </p>
<p>This handbook does not try to cover everything under the sun related to Linux and its commands. It focuses on the small core commands that you will use the 80% or 90% of the time, and tries to simplify the usage of the more complex ones.</p>
<p>All these commands work on Linux, macOS, WSL, and anywhere you have a UNIX environment.</p>
<p>I hope the contents of this handbook will help you achieve what you want: <strong>getting comfortable with Linux</strong>.</p>
<p>You can bookmark this page in your browser so you can reference this handbook in the future.</p>
<p>And you can <a target="_blank" href="https://flaviocopes.com/page/linux-commands-handbook/">download this handbook in PDF / ePUB / Mobi format for free</a>.</p>
<p>Enjoy!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-introduction-to-linux-and-shells">Introduction to Linux and shells</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-man-command">The Linux <code>man</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-ls-command">The Linux <code>ls</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-cd-command">The Linux <code>cd</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-pwd-command">The Linux <code>pwd</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-mkdir-command">The Linux <code>mkdir</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-rmdir-command">The Linux <code>rmdir</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-mv-command">The Linux <code>mv</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-cp-command">The Linux <code>cp</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-open-command">The Linux <code>open</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-touch-command">The Linux <code>touch</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-find-command">The Linux <code>find</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-ln-command">The Linux <code>ln</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-gzip-command">The Linux <code>gzip</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-gunzip-command">The Linux <code>gunzip</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-tar-command">The Linux <code>tar</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-alias-command">The Linux <code>alias</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-cat-command">The Linux <code>cat</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-less-command">The Linux <code>less</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-tail-command">The Linux <code>tail</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-wc-command">The Linux <code>wc</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-grep-command">The Linux <code>grep</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-sort-command">The Linux <code>sort</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-uniq-command">The Linux <code>uniq</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-diff-command">The Linux <code>diff</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-echo-command">The Linux <code>echo</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-chown-command">The Linux <code>chown</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-chmod-command">The Linux <code>chmod</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-umask-command">The Linux <code>umask</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-du-command">The Linux <code>du</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-df-command">The Linux <code>df</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-basename-command">The Linux <code>basename</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-dirname-command">The Linux <code>dirname</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-ps-command">The Linux <code>ps</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-top-command">The Linux <code>top</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-kill-command">The Linux <code>kill</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-killall-command">The Linux <code>killall</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-jobs-command">The Linux <code>jobs</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-bg-command">The Linux <code>bg</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-fg-command">The Linux <code>fg</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-type-command">The Linux <code>type</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-which-command">The Linux <code>which</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-nohup-command">The Linux <code>nohup</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-xargs-command">The Linux <code>xargs</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-vim-editor-command">The Linux <code>vim</code> editor command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-emacs-editor-command">The Linux <code>emacs</code> editor command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-nano-editor-command">The Linux <code>nano</code> editor command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-whoami-command">The Linux <code>whoami</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-who-command">The Linux <code>who</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-su-command">The Linux <code>su</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-sudo-command">The Linux <code>sudo</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-passwd-command">The Linux <code>passwd</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-ping-command">The Linux <code>ping</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-traceroute-command">The Linux <code>traceroute</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-clear-command">The Linux <code>clear</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-history-command">The Linux <code>history</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-export-command">The Linux <code>export</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-crontab-command">The Linux <code>crontab</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-uname-command">The Linux <code>uname</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-env-command">The Linux <code>env</code> command</a></li>
<li><a class="post-section-overview" href="#heading-the-linux-printenv-command">The Linux <code>printenv</code> command</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-introduction-to-linux-and-shells">Introduction to Linux and shells</h2>
<h3 id="heading-what-is-linux">What is Linux?</h3>
<p>Linux is an operating system, like macOS or Windows.</p>
<p>It is also the most popular Open Source operating system, and it gives you a lot of freedom.</p>
<p>It powers the vast majority of the servers that compose the Internet. It's the base upon which everything is built. But not just that. Android is based on (a modified version of) Linux.</p>
<p>The Linux "core" (called a <em>kernel</em>) was born in 1991 in Finland, and it has come a really long way from its humble beginnings. It went on to be the kernel of the GNU Operating System, creating the duo GNU/Linux.</p>
<p>There's one thing about Linux that corporations like Microsoft, Apple, and Google will never be able to offer: the freedom to do whatever you want with your computer.</p>
<p>They're actually going in the opposite direction, building walled gardens, especially on the mobile side.</p>
<p>Linux is the ultimate freedom. </p>
<p>It is developed by volunteers, some paid by companies that rely on it, some independently. But there's no single commercial company that can dictate what goes into Linux, or the project's priorities.</p>
<p>You can also use Linux as your day to day computer. I use macOS because I really enjoy the applications and design (and I also used to be an iOS and Mac apps developer). But before using macOS I used Linux as my main computer Operating System.</p>
<p>No one can dictate which apps you can run, or "call home" with apps that track you, your position, and more.</p>
<p>Linux is also special because there's not just "one Linux", like is the case with Windows or macOS. Instead, we have <strong>distributions</strong>.</p>
<p>A "distro" is made by a company or organization and packages the Linux core with additional programs and tooling. </p>
<p>For example you have Debian, Red Hat, and Ubuntu, probably the most popular distributions. </p>
<p>But many, many more exist. You can create your own distribution, too. But most likely you'll use a popular one that has lots of users and a community of people around it. This lets you do what you need to do without losing too much time reinventing the wheel and figuring out answers to common problems.</p>
<p>Some desktop computers and laptops ship with Linux preinstalled. Or you can install it on your Windows-based computer, or on a Mac.</p>
<p>But you don't need to disrupt your existing computer just to get an idea of how Linux works. </p>
<p>I don't have a Linux computer.</p>
<p>If you use a Mac, you just need to know that under the hood macOS is a UNIX Operating System. It shares a lot of the same ideas and software that a GNU/Linux system uses, because GNU/Linux is a free alternative to UNIX.</p>
<blockquote>
<p><a target="_blank" href="https://en.wikipedia.org/wiki/Unix">UNIX</a> is an umbrella term that groups many operating systems used in big corporations and institutions, starting from the 70's</p>
</blockquote>
<p>The macOS terminal gives you access to the same exact commands I'll describe in the rest of this handbook.</p>
<p>Microsoft has an official <a target="_blank" href="https://docs.microsoft.com/en-us/windows/wsl/install-win10">Windows Subsystem for Linux</a> which you can (and should!) install on Windows. This will give you the ability to run Linux in a very easy way on your PC.</p>
<p>But the vast majority of the time you will run a Linux computer in the cloud via a VPS (Virtual Private Server) like DigitalOcean.</p>
<h3 id="heading-what-is-a-linux-shell">What is a Linux shell?</h3>
<p>A shell is a command interpreter that exposes an interface to the user to work with the underlying operating system.</p>
<p>It allows you to execute operations using text and commands, and it provides users advanced features like being able to create scripts.</p>
<p>This is important: shells let you perform things in a more optimized way than a GUI (Graphical User Interface) could ever possibly let you do. Command line tools can offer many different configuration options without being too complex to use.</p>
<p>There are many different kind of shells. This post focuses on Unix shells, the ones that you will find commonly on Linux and macOS computers.</p>
<p>Many different kind of shells were created for those systems over time, and a few of them dominate the space: Bash, Csh, Zsh, Fish and many more!</p>
<p>All shells originate from the Bourne Shell, called <code>sh</code>. "Bourne" because its creator was Steve Bourne.</p>
<p>Bash means <em>Bourne-again shell</em>. <code>sh</code> was proprietary and not open source, and Bash was created in 1989 to create a free alternative for the GNU project and the Free Software Foundation. Since projects had to pay to use the Bourne shell, Bash became very popular.</p>
<p>If you use a Mac, try opening your Mac terminal. By default it runs ZSH (or, pre-Catalina, Bash).</p>
<p>You can set up your system to run any kind of shell – for example I use the Fish shell.</p>
<p>Each single shell has its own unique features and advanced usage, but they all share a common functionality: they can let you execute programs, and they can be programmed.</p>
<p>In the rest of this handbook we'll see in detail the most common commands you will use.</p>
<h2 id="heading-the-linux-man-command">The Linux <code>man</code> command</h2>
<p>The first command I'll introduce will help you understand all the other commands.</p>
<p>Every time I don't know how to use a command, I type <code>man &lt;command&gt;</code> to get the manual:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-07-04-at-18.42.40.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This is a man (from <strong>manual</strong>) page. Man pages are an essential tool to learn as a developer. They contain so much information that sometimes it's almost too much.<br>The above screenshot is just 1 of 14 screens of explanation for the <code>ls</code> command.</p>
<p>Most of the time when I need to learn a command quickly I use this site called <strong>tldr pages</strong>: <a target="_blank" href="https://tldr.sh/">https://tldr.sh</a>. It's a command you can install, which you then run like this: <code>tldr &lt;command&gt;</code>. It gives you a very quick overview of a command, with some handy examples of common usage scenarios:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-07-at-07.35.41.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This is not a substitute for <code>man</code>, but a handy tool to avoid losing yourself in the huge amount of information present in a <code>man</code> page. Then you can use the <code>man</code> page to explore all the different options and parameters you can use on a command.</p>
<h2 id="heading-the-linux-ls-command">The Linux <code>ls</code> command</h2>
<p>Inside a folder you can list all the files that the folder contains using the <code>ls</code> command:</p>
<pre><code class="lang-bash">ls
</code></pre>
<p>If you add a folder name or path, it will print that folder's contents:</p>
<pre><code class="lang-bash">ls /bin
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screenshot-2019-02-09-at-18.50.14.png" alt="Screenshot-2019-02-09-at-18.50.14" width="600" height="400" loading="lazy"></p>
<p><code>ls</code> accepts a lot of options. One of my favorite combinations is <code>-al</code>. Try it:</p>
<pre><code class="lang-bash">ls -al /bin
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screenshot-2019-02-09-at-18.49.52.png" alt="Screenshot-2019-02-09-at-18.49.52" width="600" height="400" loading="lazy"></p>
<p>Compared to the plain <code>ls</code> command, this returns much more information.</p>
<p>You have, from left to right:</p>
<ul>
<li>the file permissions (and if your system supports ACLs, you get an ACL flag as well)</li>
<li>the number of links to that file</li>
<li>the owner of the file</li>
<li>the group of the file</li>
<li>the file size in bytes</li>
<li>the file's last modified datetime</li>
<li>the file name</li>
</ul>
<p>This set of data is generated by the <code>l</code> option. The <code>a</code> option instead also shows the hidden files.</p>
<p>Hidden files are files that start with a dot (<code>.</code>).</p>
<h2 id="heading-the-linux-cd-command">The Linux <code>cd</code> command</h2>
<p>Once you have a folder, you can move into it using the <code>cd</code> command. <code>cd</code> means <strong>c</strong>hange <strong>d</strong>irectory. You invoke it specifying a folder to move into. You can specify a folder name, or an entire path.</p>
<p>Example:</p>
<pre><code class="lang-bash">mkdir fruits
<span class="hljs-built_in">cd</span> fruits
</code></pre>
<p>Now you are in the <code>fruits</code> folder.</p>
<p>You can use the <code>..</code> special path to indicate the parent folder:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> .. <span class="hljs-comment">#back to the home folder</span>
</code></pre>
<p>The # character indicates the start of the comment, which lasts for the entire line after it's found.</p>
<p>You can use it to form a path:</p>
<pre><code class="lang-bash">mkdir fruits
mkdir cars
<span class="hljs-built_in">cd</span> fruits
<span class="hljs-built_in">cd</span> ../cars
</code></pre>
<p>There is another special path indicator which is <code>.</code>, and indicates the <strong>current</strong> folder.</p>
<p>You can also use absolute paths, which start from the root folder <code>/</code>:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> /etc
</code></pre>
<h2 id="heading-the-linux-pwd-command">The Linux <code>pwd</code> command</h2>
<p>Whenever you feel lost in the filesystem, call the <code>pwd</code> command to know where you are:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">pwd</span>
</code></pre>
<p>It will print the current folder path.</p>
<h2 id="heading-the-linux-mkdir-command">The Linux <code>mkdir</code> command</h2>
<p>You create folders using the <code>mkdir</code> command:</p>
<pre><code class="lang-bash">mkdir fruits
</code></pre>
<p>You can create multiple folders with one command:</p>
<pre><code class="lang-bash">mkdir dogs cars
</code></pre>
<p>You can also create multiple nested folders by adding the <code>-p</code> option:</p>
<pre><code class="lang-bash">mkdir -p fruits/apples
</code></pre>
<p>Options in UNIX commands commonly take this form. You add them right after the command name, and they change how the command behaves. You can often combine multiple options, too.</p>
<p>You can find which options a command supports by typing <code>man &lt;commandname&gt;</code>. Try now with <code>man mkdir</code> for example (press the <code>q</code> key to esc the man page). Man pages are the amazing built-in help for UNIX.</p>
<h2 id="heading-the-linux-rmdir-command">The Linux <code>rmdir</code> command</h2>
<p>Just as you can create a folder using <code>mkdir</code>, you can delete a folder using <code>rmdir</code>:</p>
<pre><code class="lang-bash">mkdir fruits
rmdir fruits
</code></pre>
<p>You can also delete multiple folders at once:</p>
<pre><code class="lang-bash">mkdir fruits cars
rmdir fruits cars
</code></pre>
<p>The folder you delete must be empty.</p>
<p>To delete folders with files in them, we'll use the more generic <code>rm</code> command which deletes files and folders, using the <code>-rf</code> option:</p>
<pre><code class="lang-bash">rm -rf fruits cars
</code></pre>
<p>Be careful as this command does not ask for confirmation and it will immediately remove anything you ask it to remove.</p>
<p>There is no <strong>bin</strong> when removing files from the command line, and recovering lost files can be hard.</p>
<h2 id="heading-the-linux-mv-command">The Linux <code>mv</code> command</h2>
<p>Once you have a file, you can move it around using the <code>mv</code> command. You specify the file current path, and its new path:</p>
<pre><code class="lang-bash">touch <span class="hljs-built_in">test</span>
mv pear new_pear
</code></pre>
<p>The <code>pear</code> file is now moved to <code>new_pear</code>. This is how you <strong>rename</strong> files and folders.</p>
<p>If the last parameter is a folder, the file located at the first parameter path is going to be moved into that folder. In this case, you can specify a list of files and they will all be moved in the folder path identified by the last parameter:</p>
<pre><code class="lang-bash">touch pear
touch apple
mkdir fruits
mv pear apple fruits <span class="hljs-comment">#pear and apple moved to the fruits folder</span>
</code></pre>
<h2 id="heading-the-linux-cp-command">The Linux <code>cp</code> command</h2>
<p>You can copy a file using the <code>cp</code> command:</p>
<pre><code class="lang-bash">touch <span class="hljs-built_in">test</span>
cp apple another_apple
</code></pre>
<p>To copy folders you need to add the <code>-r</code> option to recursively copy the whole folder contents:</p>
<pre><code class="lang-bash">mkdir fruits
cp -r fruits cars
</code></pre>
<h2 id="heading-the-linux-open-command">The Linux <code>open</code> command</h2>
<p>The <code>open</code> command lets you open a file using this syntax:</p>
<pre><code class="lang-bash">open &lt;filename&gt;
</code></pre>
<p>You can also open a directory, which on macOS opens the Finder app with the current directory open:</p>
<pre><code class="lang-bash">open &lt;directory name&gt;
</code></pre>
<p>I use it all the time to open the current directory:</p>
<pre><code class="lang-bash">open .
</code></pre>
<blockquote>
<p>The special <code>.</code> symbol points to the current directory, as <code>..</code> points to the parent directory</p>
</blockquote>
<p>The same command can also be be used to run an application:</p>
<pre><code class="lang-bash">open &lt;application name&gt;
</code></pre>
<h2 id="heading-the-linux-touch-command">The Linux <code>touch</code> command</h2>
<p>You can create an empty file using the <code>touch</code> command:</p>
<pre><code class="lang-bash">touch apple
</code></pre>
<p>If the file already exists, it opens the file in write mode, and the timestamp of the file is updated.</p>
<h2 id="heading-the-linux-find-command">The Linux <code>find</code> command</h2>
<p>The <code>find</code> command can be used to find files or folders matching a particular search pattern. It searches recursively.</p>
<p>Let's learn how to use it by example.</p>
<p>Find all the files under the current tree that have the <code>.js</code> extension and print the relative path of each file that matches:</p>
<pre><code class="lang-bash">find . -name <span class="hljs-string">'*.js'</span>
</code></pre>
<p>It's important to use quotes around special characters like <code>*</code> to avoid the shell interpreting them.</p>
<p>Find directories under the current tree matching the name "src":</p>
<pre><code class="lang-bash">find . -<span class="hljs-built_in">type</span> d -name src
</code></pre>
<p>Use <code>-type f</code> to search only files, or <code>-type l</code> to only search symbolic links.</p>
<p><code>-name</code> is case sensitive. use <code>-iname</code> to perform a case-insensitive search.</p>
<p>You can search under multiple root trees:</p>
<pre><code class="lang-bash">find folder1 folder2 -name filename.txt
</code></pre>
<p>Find directories under the current tree matching the name "node_modules" or 'public':</p>
<pre><code class="lang-bash">find . -<span class="hljs-built_in">type</span> d -name node_modules -or -name public
</code></pre>
<p>You can also exclude a path using <code>-not -path</code>:</p>
<pre><code class="lang-bash">find . -<span class="hljs-built_in">type</span> d -name <span class="hljs-string">'*.md'</span> -not -path <span class="hljs-string">'node_modules/*'</span>
</code></pre>
<p>You can search files that have more than 100 characters (bytes) in them:</p>
<pre><code class="lang-bash">find . -<span class="hljs-built_in">type</span> f -size +100c
</code></pre>
<p>Search files bigger than 100KB but smaller than 1MB:</p>
<pre><code class="lang-bash">find . -<span class="hljs-built_in">type</span> f -size +100k -size -1M
</code></pre>
<p>Search files edited more than 3 days ago:</p>
<pre><code class="lang-bash">find . -<span class="hljs-built_in">type</span> f -mtime +3
</code></pre>
<p>Search files edited in the last 24 hours:</p>
<pre><code class="lang-bash">find . -<span class="hljs-built_in">type</span> f -mtime -1
</code></pre>
<p>You can delete all the files matching a search by adding the <code>-delete</code> option. This deletes all the files edited in the last 24 hours:</p>
<pre><code class="lang-bash">find . -<span class="hljs-built_in">type</span> f -mtime -1 -delete
</code></pre>
<p>You can execute a command on each result of the search. In this example we run <code>cat</code> to print the file content:</p>
<pre><code class="lang-bash">find . -<span class="hljs-built_in">type</span> f -<span class="hljs-built_in">exec</span> cat {} \;
</code></pre>
<p>Notice the terminating <code>\;</code>. <code>{}</code> is filled with the file name at execution time.</p>
<h2 id="heading-the-linux-ln-command">The Linux <code>ln</code> command</h2>
<p>The <code>ln</code> command is part of the Linux file system commands.</p>
<p>It's used to create links. What is a link? It's like a pointer to another file, or a file that points to another file. You might be familiar with Windows shortcuts. They're similar.</p>
<p>We have 2 types of links: <strong>hard links</strong> and <strong>soft links</strong>.</p>
<h4 id="heading-hard-links">Hard links</h4>
<p>Hard links are rarely used. They have a few limitations: you can't link to directories, and you can't link to external filesystems (disks).</p>
<p>A hard link is created using the following syntax:</p>
<pre><code class="lang-bash">ln &lt;original&gt; &lt;link&gt;
</code></pre>
<p>For example, say you have a file called recipes.txt. You can create a hard link to it using:</p>
<pre><code class="lang-bash">ln recipes.txt newrecipes.txt
</code></pre>
<p>The new hard link you created is indistinguishable from a regular file:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-02-at-11.26.21.png" alt="Screen-Shot-2020-09-02-at-11.26.21" width="600" height="400" loading="lazy"></p>
<p>Now any time you edit any of those files, the content will be updated for both.</p>
<p>If you delete the original file, the link will still contain the original file content, as that's not removed until there is one hard link pointing to it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-02-at-11.26.07.png" alt="Screen-Shot-2020-09-02-at-11.26.07" width="600" height="400" loading="lazy"></p>
<h4 id="heading-soft-links">Soft links</h4>
<p>Soft links are different. They are more powerful as you can link to other filesystems and to directories. But keep in mind that when the original is removed, the link will be broken.</p>
<p>You create soft links using the <code>-s</code> option of <code>ln</code>:</p>
<pre><code class="lang-bash">ln -s &lt;original&gt; &lt;link&gt;
</code></pre>
<p>For example, say you have a file called recipes.txt. You can create a soft link to it using:</p>
<pre><code class="lang-bash">ln -s recipes.txt newrecipes.txt
</code></pre>
<p>In this case you can see there's a special <code>l</code> flag when you list the file using <code>ls -al</code>. The file name has a <code>@</code> at the end, and it's also colored differently if you have colors enabled:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-02-at-11.27.18.png" alt="Screen-Shot-2020-09-02-at-11.27.18" width="600" height="400" loading="lazy">
Now if you delete the original file, the links will be broken, and the shell will tell you "No such file or directory" if you try to access it:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-02-at-11.27.03.png" alt="Screen-Shot-2020-09-02-at-11.27.03" width="600" height="400" loading="lazy"></p>
<h2 id="heading-the-linux-gzip-command">The Linux <code>gzip</code> command</h2>
<p>You can compress a file using the gzip compression protocol named <a target="_blank" href="https://en.wikipedia.org/wiki/LZ77_and_LZ78">LZ77</a> using the <code>gzip</code> command.</p>
<p>Here's the simplest usage:</p>
<pre><code class="lang-bash">gzip filename
</code></pre>
<p>This will compress the file, and append a <code>.gz</code> extension to it. The original file is deleted. </p>
<p>To prevent this, you can use the <code>-c</code> option and use output redirection to write the output to the <code>filename.gz</code> file:</p>
<pre><code class="lang-bash">gzip -c filename &gt; filename.gz
</code></pre>
<blockquote>
<p>The <code>-c</code> option specifies that the output will go to the standard output stream, leaving the original file intact.</p>
</blockquote>
<p>Or you can use the <code>-k</code> option:</p>
<pre><code class="lang-bash">gzip -k filename
</code></pre>
<p>There are various levels of compression. The more the compression, the longer it will take to compress (and decompress). Levels range from 1 (fastest, worst compression) to 9 (slowest, better compression), and the default is 6.</p>
<p>You can choose a specific level with the <code>-&lt;NUMBER&gt;</code> option:</p>
<pre><code class="lang-bash">gzip -1 filename
</code></pre>
<p>You can compress multiple files by listing them:</p>
<pre><code class="lang-bash">gzip filename1 filename2
</code></pre>
<p>You can compress all the files in a directory, recursively, using the <code>-r</code> option:</p>
<pre><code class="lang-bash">gzip -r a_folder
</code></pre>
<p>The <code>-v</code> option prints the compression percentage information. Here's an example of it being used along with the <code>-k</code> (keep) option:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-09-at-15.55.42.png" alt="Screen-Shot-2020-09-09-at-15.55.42" width="600" height="400" loading="lazy">
<code>gzip</code> can also be used to decompress a file, using the <code>-d</code> option:</p>
<pre><code class="lang-bash">gzip -d filename.gz
</code></pre>
<h2 id="heading-the-linux-gunzip-command">The Linux <code>gunzip</code> command</h2>
<p>The <code>gunzip</code> command is basically equivalent to the <code>gzip</code> command, except the <code>-d</code> option is always enabled by default.</p>
<p>The command can be invoked in this way:</p>
<pre><code class="lang-bash">gunzip filename.gz
</code></pre>
<p>This will gunzip and will remove the <code>.gz</code> extension, putting the result in the <code>filename</code> file. If that file exists, it will overwrite that.</p>
<p>You can extract to a different filename using output redirection using the <code>-c</code> option:</p>
<pre><code class="lang-bash">gunzip -c filename.gz &gt; anotherfilename
</code></pre>
<h2 id="heading-the-linux-tar-command">The Linux <code>tar</code> command</h2>
<p>The <code>tar</code> command is used to create an archive, grouping multiple files in a single file.</p>
<p>Its name comes from the past and means <em>tape archive</em> (back when archives were stored on tapes).</p>
<p>This command creates an archive named <code>archive.tar</code> with the content of <code>file1</code> and <code>file2</code>:</p>
<pre><code class="lang-bash">tar -cf archive.tar file1 file2
</code></pre>
<blockquote>
<p>The <code>c</code> option stands for <em>create</em>. The <code>f</code> option is used to write to file the archive.</p>
</blockquote>
<p>To extract files from an archive in the current folder, use:</p>
<pre><code class="lang-bash">tar -xf archive.tar
</code></pre>
<blockquote>
<p>the <code>x</code> option stands for <em>extract</em>.</p>
</blockquote>
<p>And to extract them to a specific directory, use:</p>
<pre><code class="lang-bash">tar -xf archive.tar -C directory
</code></pre>
<p>You can also just list the files contained in an archive:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-09-at-16.56.33.png" alt="Screen-Shot-2020-09-09-at-16.56.33" width="600" height="400" loading="lazy">
<code>tar</code> is often used to create a <strong>compressed archive</strong>, gzipping the archive.</p>
<p>This is done using the <code>z</code> option:</p>
<pre><code class="lang-bash">tar -czf archive.tar.gz file1 file2
</code></pre>
<p>This is just like creating a tar archive, and then running <code>gzip</code> on it.</p>
<p>To unarchive a gzipped archive, you can use <code>gunzip</code>, or <code>gzip -d</code>, and then unarchive it. But <code>tar -xf</code> will recognize it's a gzipped archive, and do it for you:</p>
<pre><code class="lang-bash">tar -xf archive.tar.gz
</code></pre>
<h2 id="heading-the-linux-alias-command">The Linux <code>alias</code> command</h2>
<p>It's common to always run a program with a set of options that you like using.</p>
<p>For example, take the <code>ls</code> command. By default it prints very little information:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-15.21.00.png" alt="Screen-Shot-2020-09-03-at-15.21.00" width="600" height="400" loading="lazy"></p>
<p>But if you use the <code>-al</code> option it will print something more useful, including the file modification date, the size, the owner, and the permissions. It will also list hidden files (files starting with a <code>.</code>):</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-15.21.08.png" alt="Screen-Shot-2020-09-03-at-15.21.08" width="600" height="400" loading="lazy"></p>
<p>You can create a new command, for example I like to call it <code>ll</code>, that is an alias to <code>ls -al</code>.</p>
<p>You do it like this:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">alias</span> ll=<span class="hljs-string">'ls -al'</span>
</code></pre>
<p>Once you do, you can call <code>ll</code> just like it was a regular UNIX command:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-15.22.51.png" alt="Screen-Shot-2020-09-03-at-15.22.51" width="600" height="400" loading="lazy"></p>
<p>Now calling <code>alias</code> without any option will list the aliases defined:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-15.30.19.png" alt="Screen-Shot-2020-09-03-at-15.30.19" width="600" height="400" loading="lazy">
The alias will work until the terminal session is closed.</p>
<p>To make it permanent, you need to add it to the shell configuration. This could be <code>~/.bashrc</code> or <code>~/.profile</code> or <code>~/.bash_profile</code> if you use the Bash shell, depending on the use case.</p>
<p>Be careful with quotes if you have variables in the command: if you use double quotes, the variable is resolved at definition time. If you use use single quotes, it's resolved at invocation time. Those 2 are different:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">alias</span> lsthis=<span class="hljs-string">"ls <span class="hljs-variable">$PWD</span>"</span>
<span class="hljs-built_in">alias</span> lscurrent=<span class="hljs-string">'ls $PWD'</span>
</code></pre>
<p>\$PWD refers to the current folder the shell is in. If you now navigate away to a new folder, <code>lscurrent</code> lists the files in the new folder, whereas <code>lsthis</code> still lists the files in the folder where you were when you defined the alias.</p>
<h2 id="heading-the-linux-cat-command">The Linux <code>cat</code> command</h2>
<p>Similar to <a target="_blank" href="https://www.freecodecamp.org/news/unix-command-tail/"><code>tail</code></a> in some ways, we have <code>cat</code>. Except <code>cat</code> can also add content to a file, and this makes it super powerful.</p>
<p>In its simplest usage, <code>cat</code> prints a file's content to the standard output:</p>
<pre><code class="lang-bash">cat file
</code></pre>
<p>You can print the content of multiple files:</p>
<pre><code class="lang-bash">cat file1 file2
</code></pre>
<p>and using the output redirection operator <code>&gt;</code> you can concatenate the content of multiple files into a new file:</p>
<pre><code class="lang-bash">cat file1 file2 &gt; file3
</code></pre>
<p>Using <code>&gt;&gt;</code> you can append the content of multiple files into a new file, creating it if it does not exist:</p>
<pre><code class="lang-bash">cat file1 file2 &gt;&gt; file3
</code></pre>
<p>When you're looking at source code files it's helpful to see the line numbers. You can have <code>cat</code> print them using the <code>-n</code> option:</p>
<pre><code class="lang-bash">cat -n file1
</code></pre>
<p>You can only add a number to non-blank lines using <code>-b</code>, or you can also remove all the multiple empty lines using <code>-s</code>.</p>
<p><code>cat</code> is often used in combination with the pipe operator <code>|</code> to feed a file's content as input to another command: <code>cat file1 | anothercommand</code>.</p>
<h2 id="heading-the-linux-less-command">The Linux <code>less</code> command</h2>
<p>The <code>less</code> command is one I use a lot. It shows you the content stored inside a file, in a nice and interactive UI.</p>
<p>Usage: <code>less &lt;filename&gt;</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screenshot-2019-02-10-at-09.11.05.png" alt="Screenshot-2019-02-10-at-09.11.05" width="600" height="400" loading="lazy"></p>
<p>Once you are inside a <code>less</code> session, you can quit by pressing <code>q</code>.</p>
<p>You can navigate the file contents using the <code>up</code> and <code>down</code> keys, or using the <code>space bar</code> and <code>b</code> to navigate page by page. You can also jump to the end of the file pressing <code>G</code> and jump back to the start by pressing <code>g</code>.</p>
<p>You can search contents inside the file by pressing <code>/</code> and typing a word to search. This searches <em>forward</em>. You can search backwards using the <code>?</code> symbol and typing a word.</p>
<p>This command just visualises the file's content. You can directly open an editor by pressing <code>v</code>. It will use the system editor, which in most cases is <code>vim</code>.</p>
<p>Pressing the <code>F</code> key enters <em>follow mode</em>, or <em>watch mode</em>. When the file is changed by someone else, like from another program, you get to see the changes <em>live</em>. </p>
<p>This doesn't happen by default, and you only see the file version at the time you opened it. You need to press <code>ctrl-C</code> to quit this mode. In this case the behaviour is similar to running the <code>tail -f &lt;filename&gt;</code> command.</p>
<p>You can open multiple files, and navigate through them using <code>:n</code> (to go to the next file) and <code>:p</code> (to go to the previous).</p>
<h2 id="heading-the-linux-tail-command">The Linux <code>tail</code> command</h2>
<p>The best use case of tail in my opinion is when called with the <code>-f</code> option. It opens the file at the end, and watches for file changes. </p>
<p>Any time there is new content in the file, it is printed in the window. This is great for watching log files, for example:</p>
<pre><code class="lang-bash">tail -f /var/<span class="hljs-built_in">log</span>/system.log
</code></pre>
<p>To exit, press <code>ctrl-C</code>.</p>
<p>You can print the last 10 lines in a file:</p>
<pre><code class="lang-bash">tail -n 10 &lt;filename&gt;
</code></pre>
<p>You can print the whole file content starting from a specific line using <code>+</code> before the line number:</p>
<pre><code class="lang-bash">tail -n +10 &lt;filename&gt;
</code></pre>
<p><code>tail</code> can do much more and as always my advice is to check <code>man tail</code>.</p>
<h2 id="heading-the-linux-wc-command">The Linux <code>wc</code> command</h2>
<p>The <code>wc</code> command gives us useful information about a file or input it receives via pipes.</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-built_in">test</span> &gt;&gt; test.txt
wc test.txt
1       1       5 test.txt
</code></pre>
<p>Example via pipes, we can count the output of running the <code>ls -al</code> command:</p>
<pre><code class="lang-bash">ls -al | wc
6      47     284
</code></pre>
<p>The first column returned is the number of lines. The second is the number of words. The third is the number of bytes.</p>
<p>We can tell it to just count the lines:</p>
<pre><code class="lang-bash">wc -l test.txt
</code></pre>
<p>or just the words:</p>
<pre><code class="lang-bash">wc -w test.txt
</code></pre>
<p>or just the bytes:</p>
<pre><code class="lang-bash">wc -c test.txt
</code></pre>
<p>Bytes in ASCII charsets equate to characters. But with non-ASCII charsets, the number of characters might differ because some characters might take multiple bytes (for example this happens in Unicode).</p>
<p>In this case the <code>-m</code> flag will help you get the correct value:</p>
<pre><code class="lang-bash">wc -m test.txt
</code></pre>
<h2 id="heading-the-linux-grep-command">The Linux <code>grep</code> command</h2>
<p>The <code>grep</code> command is a very useful tool. When you master it, it will help you tremendously in your day to day coding.</p>
<blockquote>
<p>If you're wondering, <code>grep</code> stands for <em>global regular expression print</em>.</p>
</blockquote>
<p>You can use <code>grep</code> to search in files, or combine it with pipes to filter the output of another command.</p>
<p>For example here's how we can find the occurences of the <code>document.getElementById</code> line in the <code>index.md</code> file:</p>
<pre><code class="lang-bash">grep -n document.getElementById index.md
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-04-at-09.42.10.png" alt="Screen-Shot-2020-09-04-at-09.42.10" width="600" height="400" loading="lazy"></p>
<p>Using the <code>-n</code> option it will show the line numbers:</p>
<pre><code class="lang-bash">grep -n document.getElementById index.md
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-04-at-09.47.04.png" alt="Screen-Shot-2020-09-04-at-09.47.04" width="600" height="400" loading="lazy"></p>
<p>One very useful thing is to tell grep to print 2 lines before and 2 lines after the matched line to give you more context. That's done using the <code>-C</code> option, which accepts a number of lines:</p>
<pre><code class="lang-bash">grep -nC 2 document.getElementById index.md
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-04-at-09.44.35.png" alt="Screen-Shot-2020-09-04-at-09.44.35" width="600" height="400" loading="lazy"></p>
<p>Search is case sensitive by default. Use the <code>-i</code> flag to make it insensitive.</p>
<p>As mentioned, you can use grep to filter the output of another command. We can replicate the same functionality as above using:</p>
<pre><code class="lang-bash">less index.md | grep -n document.getElementById
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-04-at-09.43.15.png" alt="Screen-Shot-2020-09-04-at-09.43.15" width="600" height="400" loading="lazy"></p>
<p>The search string can be a regular expression, and this makes <code>grep</code> very powerful.</p>
<p>Another thing you might find very useful is to invert the result, excluding the lines that match a particular string, using the <code>-v</code> option:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-04-at-09.42.04.png" alt="Screen-Shot-2020-09-04-at-09.42.04" width="600" height="400" loading="lazy"></p>
<h2 id="heading-the-linux-sort-command">The Linux <code>sort</code> command</h2>
<p>Suppose you have a text file which contains the names of dogs:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-07-at-07.56.28.png" alt="Screen-Shot-2020-09-07-at-07.56.28" width="600" height="400" loading="lazy"></p>
<p>This list is unordered.</p>
<p>The <code>sort</code> command helps you sort them by name:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-07-at-07.57.08.png" alt="Screen-Shot-2020-09-07-at-07.57.08" width="600" height="400" loading="lazy"></p>
<p>Use the <code>r</code> option to reverse the order:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-07-at-07.57.28.png" alt="Screen-Shot-2020-09-07-at-07.57.28" width="600" height="400" loading="lazy"></p>
<p>Sorting by default is case sensitive, and alphabetic. Use the <code>--ignore-case</code> option to sort case insensitive, and the <code>-n</code> option to sort using a numeric order.</p>
<p>If the file contains duplicate lines:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-07-at-07.59.03.png" alt="Screen-Shot-2020-09-07-at-07.59.03" width="600" height="400" loading="lazy"></p>
<p>You can use the <code>-u</code> option to remove them:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-07-at-07.59.16.png" alt="Screen-Shot-2020-09-07-at-07.59.16" width="600" height="400" loading="lazy"></p>
<p><code>sort</code> does not just work on files, as many UNIX commands do – it also works with pipes. So you can use it on the output of another command. For example you can order the files returned by <code>ls</code> with:</p>
<pre><code class="lang-bash">ls | sort
</code></pre>
<p><code>sort</code> is very powerful and has lots more options, which you can explore by calling <code>man sort</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-07-at-08.01.27.png" alt="Screen-Shot-2020-09-07-at-08.01.27" width="600" height="400" loading="lazy"></p>
<h2 id="heading-the-linux-uniq-command">The Linux <code>uniq</code> command</h2>
<p><code>uniq</code> is a command that helps you sort lines of text.</p>
<p>You can get those lines from a file, or using pipes from the output of another command:</p>
<pre><code class="lang-bash">uniq dogs.txt

ls | uniq
</code></pre>
<p>You need to consider this key thing: <code>uniq</code> will only detect adjacent duplicate lines.</p>
<p>This implies that you will most likely use it along with <code>sort</code>:</p>
<pre><code class="lang-bash">sort dogs.txt | uniq
</code></pre>
<p>The <code>sort</code> command has its own way to remove duplicates with the <code>-u</code> (<em>unique</em>) option. But <code>uniq</code> has more power.</p>
<p>By default it removes duplicate lines:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-07-at-08.39.35.png" alt="Screen-Shot-2020-09-07-at-08.39.35" width="600" height="400" loading="lazy"></p>
<p>You can tell it to only display duplicate lines, for example, with the <code>-d</code> option:</p>
<pre><code class="lang-bash">sort dogs.txt | uniq -d
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-07-at-08.36.50.png" alt="Screen-Shot-2020-09-07-at-08.36.50" width="600" height="400" loading="lazy"></p>
<p>You can use the <code>-u</code> option to only display non-duplicate lines:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-07-at-08.38.50.png" alt="Screen-Shot-2020-09-07-at-08.38.50" width="600" height="400" loading="lazy"></p>
<p>You can count the occurrences of each line with the <code>-c</code> option:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-07-at-08.37.15.png" alt="Screen-Shot-2020-09-07-at-08.37.15" width="600" height="400" loading="lazy"></p>
<p>Use the special combination:</p>
<pre><code class="lang-bash">sort dogs.txt | uniq -c | sort -nr
</code></pre>
<p>to then sort those lines by most frequent:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-07-at-08.37.49.png" alt="Screen-Shot-2020-09-07-at-08.37.49" width="600" height="400" loading="lazy"></p>
<h2 id="heading-the-linux-diff-command">The Linux <code>diff</code> command</h2>
<p><code>diff</code> is a handy command. Suppose you have 2 files, which contain almost the same information, but you can't find the difference between the two.</p>
<p><code>diff</code> will process the files and will tell you what's the difference.</p>
<p>Suppose you have 2 files: <code>dogs.txt</code> and <code>moredogs.txt</code>. The difference is that <code>moredogs.txt</code> contains one more dog name:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-07-at-08.55.18.png" alt="Screen-Shot-2020-09-07-at-08.55.18" width="600" height="400" loading="lazy"></p>
<p><code>diff dogs.txt moredogs.txt</code> will tell you the second file has one more line, line 3 with the line <code>Vanille</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-07-at-08.56.05.png" alt="Screen-Shot-2020-09-07-at-08.56.05" width="600" height="400" loading="lazy"></p>
<p>If you invert the order of the files, it will tell you that the second file is missing line 3, whose content is <code>Vanille</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-07-at-08.56.10.png" alt="Screen-Shot-2020-09-07-at-08.56.10" width="600" height="400" loading="lazy"></p>
<p>Using the <code>-y</code> option will compare the 2 files line by line:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-07-at-08.57.56.png" alt="Screen-Shot-2020-09-07-at-08.57.56" width="600" height="400" loading="lazy"></p>
<p>The <code>-u</code> option however will be more familiar to you, because that's the same used by the Git version control system to display differences between versions:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-07-at-08.58.23.png" alt="Screen-Shot-2020-09-07-at-08.58.23" width="600" height="400" loading="lazy"></p>
<p>Comparing directories works in the same way. You must use the <code>-r</code> option to compare recursively (going into subdirectories):</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-07-at-09.01.07.png" alt="Screen-Shot-2020-09-07-at-09.01.07" width="600" height="400" loading="lazy"></p>
<p>In case you're interested in which files differ, rather than the content, use the <code>r</code> and <code>q</code> options:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-07-at-09.01.30.png" alt="Screen-Shot-2020-09-07-at-09.01.30" width="600" height="400" loading="lazy"></p>
<p>There are many more options you can explore in the man page by running <code>man diff</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-07-at-09.02.32.png" alt="Screen-Shot-2020-09-07-at-09.02.32" width="600" height="400" loading="lazy"></p>
<h2 id="heading-the-linux-echo-command">The Linux <code>echo</code> command</h2>
<p>The <code>echo</code> command does one simple job: it prints to the output the argument passed to it.</p>
<p>This example:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"hello"</span>
</code></pre>
<p>will print <code>hello</code> to the terminal.</p>
<p>We can append the output to a file:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"hello"</span> &gt;&gt; output.txt
</code></pre>
<p>We can interpolate environment variables:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"The path variable is <span class="hljs-variable">$PATH</span>"</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-15.44.33.png" alt="Screen-Shot-2020-09-03-at-15.44.33" width="600" height="400" loading="lazy"></p>
<p>Beware that special characters need to be escaped with a backslash <code>\</code>. <code>$</code> for example:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-15.51.18.png" alt="Screen-Shot-2020-09-03-at-15.51.18" width="600" height="400" loading="lazy">
This is just the start. We can do some nice things when it comes to interacting with the shell features.</p>
<p>We can echo the files in the current folder:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> *
</code></pre>
<p>We can echo the files in the current folder that start with the letter <code>o</code>:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> o*
</code></pre>
<p>Any valid Bash (or any shell you are using) command and feature can be used here.</p>
<p>You can print your home folder path:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> ~
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-15.46.36.png" alt="Screen-Shot-2020-09-03-at-15.46.36" width="600" height="400" loading="lazy"></p>
<p>You can also execute commands, and print the result to the standard output (or to file, as you saw):</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> $(ls -al)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-15.48.55.png" alt="Screen-Shot-2020-09-03-at-15.48.55" width="600" height="400" loading="lazy"></p>
<p>Note that whitespace is not preserved by default. You need to wrap the command in double quotes to do so:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-15.49.53.png" alt="Screen-Shot-2020-09-03-at-15.49.53" width="600" height="400" loading="lazy"></p>
<p>You can generate a list of strings, for example ranges:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> {1..5}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-15.47.19.png" alt="Screen-Shot-2020-09-03-at-15.47.19" width="600" height="400" loading="lazy"></p>
<h2 id="heading-the-linux-chown-command">The Linux <code>chown</code> command</h2>
<p>Every file/directory in an Operating System like Linux or macOS (and every UNIX system in general) has an <strong>owner</strong>.</p>
<p>The owner of a file can do everything with it. It can decide the fate of that file.</p>
<p>The owner (and the <code>root</code> user) can change the owner to another user, too, using the <code>chown</code> command:</p>
<pre><code class="lang-bash">chown &lt;owner&gt; &lt;file&gt;
</code></pre>
<p>Like this:</p>
<pre><code class="lang-bash">chown flavio test.txt
</code></pre>
<p>For example if you have a file that's owned by <code>root</code>, you can't write to it as another user:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-18.40.49.png" alt="Screen-Shot-2020-09-03-at-18.40.49" width="600" height="400" loading="lazy"></p>
<p>You can use <code>chown</code> to transfer the ownership to you:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-18.40.58.png" alt="Screen-Shot-2020-09-03-at-18.40.58" width="600" height="400" loading="lazy">
It's rather common to need to change the ownership of a directory, and recursively all the files contained, plus all the subdirectories and the files contained in them, too.</p>
<p>You can do so using the <code>-R</code> flag:</p>
<pre><code class="lang-bash">chown -R &lt;owner&gt; &lt;file&gt;
</code></pre>
<p>Files/directories don't just have an owner, they also have a <strong>group</strong>. Through this command you can change that simultaneously while you change the owner:</p>
<pre><code class="lang-bash">chown &lt;owner&gt;:&lt;group&gt; &lt;file&gt;
</code></pre>
<p>Example:</p>
<pre><code class="lang-bash">chown flavio:users test.txt
</code></pre>
<p>You can also just change the group of a file using the <code>chgrp</code> command:</p>
<pre><code class="lang-bash">chgrp &lt;group&gt; &lt;filename&gt;
</code></pre>
<h2 id="heading-the-linux-chmod-command">The Linux <code>chmod</code> command</h2>
<p>Every file in the Linux / macOS Operating Systems (and UNIX systems in general) has 3 permissions: read, write, and execute.</p>
<p>Go into a folder, and run the <code>ls -al</code> command.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-18.49.22.png" alt="Screen-Shot-2020-09-03-at-18.49.22" width="600" height="400" loading="lazy">
The weird strings you see on each file line, like <code>drwxr-xr-x</code>, define the permissions of the file or folder.</p>
<p>Let's dissect it.</p>
<p>The first letter indicates the type of file:</p>
<ul>
<li><code>-</code> means it's a normal file</li>
<li><code>d</code> means it's a directory</li>
<li><code>l</code> means it's a link</li>
</ul>
<p>Then you have 3 sets of values:</p>
<ul>
<li>The first set represents the permissions of the <strong>owner</strong> of the file</li>
<li>The second set represents the permissions of the members of the <strong>group</strong> the file is associated to</li>
<li>The third set represents the permissions of the <strong>everyone else</strong></li>
</ul>
<p>Those sets are composed by 3 values. <code>rwx</code> means that specific <em>persona</em> has read, write and execution access. Anything that is removed is swapped with a <code>-</code>, which lets you form various combinations of values and relative permissions: <code>rw-</code>, <code>r--</code>, <code>r-x</code>, and so on.</p>
<p>You can change the permissions given to a file using the <code>chmod</code> command.</p>
<p><code>chmod</code> can be used in 2 ways. The first is using symbolic arguments, the second is using numeric arguments. Let's start with symbols first, which is more intuitive.</p>
<p>You type <code>chmod</code> followed by a space, and a letter:</p>
<ul>
<li><code>a</code> stands for <em>all</em></li>
<li><code>u</code> stands for <em>user</em></li>
<li><code>g</code> stands for <em>group</em></li>
<li><code>o</code> stands for <em>others</em></li>
</ul>
<p>Then you type either <code>+</code> or <code>-</code> to add a permission, or to remove it. Then you enter one or more permission symbols (<code>r</code>, <code>w</code>, <code>x</code>).</p>
<p>All followed by the file or folder name.</p>
<p>Here are some examples:</p>
<pre><code class="lang-bash">chmod a+r filename <span class="hljs-comment">#everyone can now read</span>
chmod a+rw filename <span class="hljs-comment">#everyone can now read and write</span>
chmod o-rwx filename <span class="hljs-comment">#others (not the owner, not in the same group of the file) cannot read, write or execute the file</span>
</code></pre>
<p>You can apply the same permissions to multiple personas by adding multiple letters before the <code>+</code>/<code>-</code>:</p>
<pre><code class="lang-bash">chmod og-r filename <span class="hljs-comment">#other and group can't read any more</span>
</code></pre>
<p>In case you are editing a folder, you can apply the permissions to every file contained in that folder using the <code>-r</code> (recursive) flag.</p>
<p>Numeric arguments are faster but I find them hard to remember when you are not using them day to day. You use a digit that represents the permissions of the persona. This number value can be a maximum of 7, and it's calculated in this way:</p>
<ul>
<li><code>1</code> if has execution permission</li>
<li><code>2</code> if has write permission</li>
<li><code>4</code> if has read permission</li>
</ul>
<p>This gives us 4 combinations:</p>
<ul>
<li><code>0</code> no permissions</li>
<li><code>1</code> can execute</li>
<li><code>2</code> can write</li>
<li><code>3</code> can write, execute</li>
<li><code>4</code> can read</li>
<li><code>5</code> can read, execute</li>
<li><code>6</code> can read, write</li>
<li><code>7</code> can read, write and execute</li>
</ul>
<p>We use them in pairs of 3, to set the permissions of all the 3 groups altogether:</p>
<pre><code class="lang-bash">chmod 777 filename
chmod 755 filename
chmod 644 filename
</code></pre>
<h2 id="heading-the-linux-umask-command">The Linux <code>umask</code> command</h2>
<p>When you create a file, you don't have to decide permissions up front. Permissions have defaults.</p>
<p>Those defaults can be controlled and modified using the <code>umask</code> command.</p>
<p>Typing <code>umask</code> with no arguments will show you the current umask, in this case <code>0022</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-04-at-09.04.19.png" alt="Screen-Shot-2020-09-04-at-09.04.19" width="600" height="400" loading="lazy"></p>
<p>What does <code>0022</code> mean? That's an octal value that represents the permissions.</p>
<p>Another common value is <code>0002</code>.</p>
<p>Use <code>umask -S</code> to see a human-readable notation:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-04-at-09.08.18.png" alt="Screen-Shot-2020-09-04-at-09.08.18" width="600" height="400" loading="lazy">
In this case, the user (<code>u</code>), owner of the file, has read, write and execution permissions on files.</p>
<p>Other users belonging to the same group (<code>g</code>) have read and execution permission, same as all the other users (<code>o</code>).</p>
<p>In the numeric notation, we typically change the last 3 digits.</p>
<p>Here's a list that gives a meaning to the number:</p>
<ul>
<li><code>0</code> read, write, execute</li>
<li><code>1</code> read and write</li>
<li><code>2</code> read and execute</li>
<li><code>3</code> read only</li>
<li><code>4</code> write and execute</li>
<li><code>5</code> write only</li>
<li><code>6</code> execute only</li>
<li><code>7</code> no permissions</li>
</ul>
<p>Note that this numeric notation differs from the one we use in <code>chmod</code>.</p>
<p>We can set a new value for the mask setting the value in numeric format:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">umask</span> 002
</code></pre>
<p>or you can change a specific role's permission:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">umask</span> g+r
</code></pre>
<h2 id="heading-the-linux-du-command">The Linux <code>du</code> command</h2>
<p>The <code>du</code> command will calculate the size of a directory as a whole:</p>
<pre><code class="lang-bash">du
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-04-at-08.11.30.png" alt="Screen-Shot-2020-09-04-at-08.11.30" width="600" height="400" loading="lazy"></p>
<p>The <code>32</code> number here is a value expressed in bytes.</p>
<p>Running <code>du *</code> will calculate the size of each file individually:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-04-at-08.12.35.png" alt="Screen-Shot-2020-09-04-at-08.12.35" width="600" height="400" loading="lazy"></p>
<p>You can set <code>du</code> to display values in MegaBytes using <code>du -m</code>, and GigaBytes using <code>du -g</code>.</p>
<p>The <code>-h</code> option will show a human-readable notation for sizes, adapting to the size:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-04-at-08.14.40.png" alt="Screen-Shot-2020-09-04-at-08.14.40" width="600" height="400" loading="lazy"></p>
<p>Adding the <code>-a</code> option will print the size of each file in the directories, too:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-04-at-08.20.12.png" alt="Screen-Shot-2020-09-04-at-08.20.12" width="600" height="400" loading="lazy"></p>
<p>A handy thing is to sort the directories by size:</p>
<pre><code class="lang-bash">du -h &lt;directory&gt; | sort -nr
</code></pre>
<p>and then piping to <code>head</code> to only get the first 10 results:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-04-at-08.22.25.png" alt="Screen-Shot-2020-09-04-at-08.22.25" width="600" height="400" loading="lazy"></p>
<h2 id="heading-the-linux-df-command">The Linux <code>df</code> command</h2>
<p>The <code>df</code> command is used to get disk usage information.</p>
<p>Its basic form will print information about the volumes mounted:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-08-at-08.40.39.png" alt="Screen-Shot-2020-09-08-at-08.40.39" width="600" height="400" loading="lazy"></p>
<p>Using the <code>-h</code> option (<code>df -h</code>) will show those values in a human-readable format:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-08-at-08.40.50.png" alt="Screen-Shot-2020-09-08-at-08.40.50" width="600" height="400" loading="lazy"></p>
<p>You can also specify a file or directory name to get information about the specific volume it lives on:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-08-at-08.41.27.png" alt="Screen-Shot-2020-09-08-at-08.41.27" width="600" height="400" loading="lazy"></p>
<h2 id="heading-the-linux-basename-command">The Linux <code>basename</code> command</h2>
<p>Suppose you have a path to a file, for example <code>/Users/flavio/test.txt</code>.</p>
<p>Running</p>
<pre><code class="lang-bash">basename /Users/flavio/test.txt
</code></pre>
<p>will return the <code>test.txt</code> string:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-10-at-08.27.52.png" alt="Screen-Shot-2020-09-10-at-08.27.52" width="600" height="400" loading="lazy"></p>
<p>If you run <code>basename</code> on a path string that points to a directory, you will get the last segment of the path. In this example, <code>/Users/flavio</code> is a directory:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-10-at-08.28.11.png" alt="Screen-Shot-2020-09-10-at-08.28.11" width="600" height="400" loading="lazy"></p>
<h2 id="heading-the-linux-dirname-command">The Linux <code>dirname</code> command</h2>
<p>Suppose you have a path to a file, for example <code>/Users/flavio/test.txt</code>.</p>
<p>Running</p>
<pre><code class="lang-bash">dirname /Users/flavio/test.txt
</code></pre>
<p>will return the <code>/Users/flavio</code> string:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-10-at-08.31.08-1.png" alt="Screen-Shot-2020-09-10-at-08.31.08-1" width="600" height="400" loading="lazy"></p>
<h2 id="heading-the-linux-ps-command">The Linux <code>ps</code> command</h2>
<p>Your computer is running tons of different processes at all times.</p>
<p>You can inspect them all using the <code>ps</code> command:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-02-at-12.25.08.png" alt="Screen-Shot-2020-09-02-at-12.25.08" width="600" height="400" loading="lazy"></p>
<p>This is the list of user-initiated processes currently running in the current session.</p>
<p>Here I have a few <code>fish</code> shell instances, mostly opened by VS Code inside the editor, and an instance of Hugo running the development preview of a site.</p>
<p>Those are just the commands assigned to the current user. To list <strong>all</strong> processes we need to pass some options to <code>ps</code>.</p>
<p>The most common one I use is <code>ps ax</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-02-at-12.26.00.png" alt="Screen-Shot-2020-09-02-at-12.26.00" width="600" height="400" loading="lazy"></p>
<blockquote>
<p>The <code>a</code> option is used to also list other users' processes, not just your own. <code>x</code> shows processes not linked to any terminal (not initiated by users through a terminal).</p>
</blockquote>
<p>As you can see, the longer commands are cut. Use the command <code>ps axww</code> to continue the command listing on a new line instead of cutting it:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-02-at-12.30.22.png" alt="Screen-Shot-2020-09-02-at-12.30.22" width="600" height="400" loading="lazy"></p>
<blockquote>
<p>We need to specify <code>w</code> 2 times to apply this setting (it's not a typo).</p>
</blockquote>
<p>You can search for a specific process combining <code>grep</code> with a pipe, like this:</p>
<pre><code class="lang-bash">ps axww | grep <span class="hljs-string">"Visual Studio Code"</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-02-at-12.33.45.png" alt="Screen-Shot-2020-09-02-at-12.33.45" width="600" height="400" loading="lazy">
The columns returned by <code>ps</code> represent some key information.</p>
<p>The first information is <code>PID</code>, the process ID. This is key when you want to reference this process in another command, for example to kill it.</p>
<p>Then we have <code>TT</code> that tells us the terminal id used.</p>
<p>Then <code>STAT</code> tells us the state of the process:</p>
<p><code>I</code> a process that is idle (sleeping for longer than about 20 seconds)
<code>R</code> a runnable process
<code>S</code> a process that is sleeping for less than about 20 seconds
<code>T</code> a stopped process
<code>U</code> a process in uninterruptible wait
<code>Z</code> a dead process (a <em>zombie</em>)</p>
<p>If you have more than one letter, the second represents further information, which can be very technical.</p>
<p>It's common to have <code>+</code> which indicates that the process is in the foreground in its terminal. <code>s</code> means the process is a <a target="_blank" href="https://unix.stackexchange.com/questions/18166/what-are-session-leaders-in-ps">session leader</a>.</p>
<p><code>TIME</code> tells us how long the process has been running.</p>
<h2 id="heading-the-linux-top-command">The Linux <code>top</code> command</h2>
<p>The <code>top</code> command is used to display dynamic real-time information about running processes in the system.</p>
<p>It's really handy to understand what is going on.</p>
<p>Its usage is simple – you just type <code>top</code>, and the terminal will be fully immersed in this new view:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-11.39.53.png" alt="Screen-Shot-2020-09-03-at-11.39.53" width="600" height="400" loading="lazy">
The process is long-running. To quit, you can type the <code>q</code> letter or <code>ctrl-C</code>.</p>
<p>There's a lot of information being given to us: the number of processes, how many are running or sleeping, the system load, the CPU usage, and a lot more.</p>
<p>Below, the list of processes taking the most memory and CPU is constantly updated.</p>
<p>By default, as you can see from the <code>%CPU</code> column highlighted, they are sorted by the CPU used.</p>
<p>You can add a flag to sort processes by memory utilized:</p>
<pre><code class="lang-bash">top -o mem
</code></pre>
<h2 id="heading-the-linux-kill-command">The Linux <code>kill</code> command</h2>
<p>Linux processes can receive <strong>signals</strong> and react to them.</p>
<p>That's one way we can interact with running programs.</p>
<p>The <code>kill</code> program can send a variety of signals to a program.</p>
<p>It's not just used to terminate a program, like the name would suggest, but that's its main job.</p>
<p>We use it in this way:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">kill</span> &lt;PID&gt;
</code></pre>
<p>By default, this sends the <code>TERM</code> signal to the process id specified.</p>
<p>We can use flags to send other signals, including:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">kill</span> -HUP &lt;PID&gt;
<span class="hljs-built_in">kill</span> -INT &lt;PID&gt;
<span class="hljs-built_in">kill</span> -KILL &lt;PID&gt;
<span class="hljs-built_in">kill</span> -TERM &lt;PID&gt;
<span class="hljs-built_in">kill</span> -CONT &lt;PID&gt;
<span class="hljs-built_in">kill</span> -STOP &lt;PID&gt;
</code></pre>
<p><code>HUP</code> means <strong>hang up</strong>. It's sent automatically when a terminal window that started a process is closed before terminating the process.</p>
<p><code>INT</code> means <strong>interrupt</strong>, and it sends the same signal used when we press <code>ctrl-C</code> in the terminal, which usually terminates the process.</p>
<p><code>KILL</code> is not sent to the process, but to the operating system kernel, which immediately stops and terminates the process.</p>
<p><code>TERM</code> means <strong>terminate</strong>. The process will receive it and terminate itself. It's the default signal sent by <code>kill</code>.</p>
<p><code>CONT</code> means <strong>continue</strong>. It can be used to resume a stopped process.</p>
<p><code>STOP</code> is not sent to the process, but to the operating system kernel, which immediately stops (but does not terminate) the process.</p>
<p>You might see numbers used instead, like <code>kill -1 &lt;PID&gt;</code>. In this case,</p>
<p><code>1</code> corresponds to <code>HUP</code>.
<code>2</code> corresponds to <code>INT</code>.
<code>9</code> corresponds to <code>KILL</code>.
<code>15</code> corresponds to <code>TERM</code>.
<code>18</code> corresponds to <code>CONT</code>.
<code>15</code> corresponds to <code>STOP</code>.</p>
<h2 id="heading-the-linux-killall-command">The Linux <code>killall</code> command</h2>
<p>Similar to the <code>kill</code> command, <code>killall</code> will send the signal to multiple processes at once instead of sending a signal to a specific process id.</p>
<p>This is the syntax:</p>
<pre><code class="lang-bash">killall &lt;name&gt;
</code></pre>
<p>where <code>name</code> is the name of a program. For example you can have multiple instances of the <code>top</code> program running, and <code>killall top</code> will terminate them all.</p>
<p>You can specify the signal, like with <code>kill</code> (and check the <code>kill</code> tutorial to read more about the specific kinds of signals we can send), for example:</p>
<pre><code class="lang-bash">killall -HUP top
</code></pre>
<h2 id="heading-the-linux-jobs-command">The Linux <code>jobs</code> command</h2>
<p>When we run a command in Linux / macOS, we can set it to run in the background using the <code>&amp;</code> symbol after the command.</p>
<p>For example we can run <code>top</code> in the background:</p>
<pre><code class="lang-bash">top &amp;
</code></pre>
<p>This is very handy for long-running programs.</p>
<p>We can get back to that program using the <code>fg</code> command. This works fine if we just have one job in the background, otherwise we need to use the job number: <code>fg 1</code>, <code>fg 2</code> and so on.</p>
<p>To get the job number, we use the <code>jobs</code> command.</p>
<p>Say we run <code>top &amp;</code> and then <code>top -o mem &amp;</code>, so we have 2 top instances running. <code>jobs</code> will tell us this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-11.49.42.png" alt="Screen-Shot-2020-09-03-at-11.49.42" width="600" height="400" loading="lazy">
Now we can switch back to one of those using <code>fg &lt;jobid&gt;</code>. To stop the program again we can hit <code>cmd-Z</code>.</p>
<p>Running <code>jobs -l</code> will also print the process id of each job.</p>
<h2 id="heading-the-linux-bg-command">The Linux <code>bg</code> command</h2>
<p>When a command is running you can suspend it using <code>ctrl-Z</code>.</p>
<p>The command will immediately stop, and you get back to the shell terminal.</p>
<p>You can resume the execution of the command in the background, so it will keep running but it will not prevent you from doing other work in the terminal.</p>
<p>In this example I have 2 commands stopped:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-16.06.18.png" alt="Screen-Shot-2020-09-03-at-16.06.18" width="600" height="400" loading="lazy">
I can run <code>bg 1</code> to resume in the background the execution of the job #1.</p>
<p>I could have also said <code>bg</code> without any option, as the default is to pick the job #1 in the list.</p>
<h2 id="heading-the-linux-fg-command">The Linux <code>fg</code> command</h2>
<p>When a command is running in the background, because you started it with <code>&amp;</code> at the end (example: <code>top &amp;</code> or because you put it in the background with the <code>bg</code> command), you can put it to the foreground using <code>fg</code>.</p>
<p>Running</p>
<pre><code class="lang-bash"><span class="hljs-built_in">fg</span>
</code></pre>
<p>will resume in the foreground the last job that was suspended.</p>
<p>You can also specify which job you want to resume to the foreground passing the job number, which you can get using the <code>jobs</code> command.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-16.12.46.png" alt="Screen-Shot-2020-09-03-at-16.12.46" width="600" height="400" loading="lazy"></p>
<p>Running <code>fg 2</code> will resume job #2:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-16.12.54.png" alt="Screen-Shot-2020-09-03-at-16.12.54" width="600" height="400" loading="lazy"></p>
<h2 id="heading-the-linux-type-command">The Linux <code>type</code> command</h2>
<p>A command can be one of those 4 types:</p>
<ul>
<li>an executable</li>
<li>a shell built-in program</li>
<li>a shell function</li>
<li>an alias</li>
</ul>
<p>The <code>type</code> command can help figure this out, in case we want to know or we're just curious. It will tell you how the command will be interpreted.</p>
<p>The output will depend on the shell used. This is Bash:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-16.32.50.png" alt="Screen-Shot-2020-09-03-at-16.32.50" width="600" height="400" loading="lazy"></p>
<p>This is Zsh:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-16.32.57.png" alt="Screen-Shot-2020-09-03-at-16.32.57" width="600" height="400" loading="lazy"></p>
<p>This is Fish:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-16.33.06.png" alt="Screen-Shot-2020-09-03-at-16.33.06" width="600" height="400" loading="lazy">
One of the most interesting things here is that for aliases it will tell you what it is aliasing to. You can see the <code>ll</code> alias, in the case of Bash and Zsh, but Fish provides it by default, so it will tell you it's a built-in shell function.</p>
<h2 id="heading-the-linux-which-command">The Linux <code>which</code> command</h2>
<p>Suppose you have a command you can execute, because it's in the shell path, but you want to know where it is located.</p>
<p>You can do so using <code>which</code>. The command will return the path to the command specified:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-17.22.47.png" alt="Screen-Shot-2020-09-03-at-17.22.47" width="600" height="400" loading="lazy">
<code>which</code> will only work for executables stored on disk, not aliases or built-in shell functions.</p>
<h2 id="heading-the-linux-nohup-command">The Linux <code>nohup</code> command</h2>
<p>Sometimes you have to run a long-lived process on a remote machine, and then you need to disconnect.</p>
<p>Or you simply want to prevent the command from being halted if there's any network issue between you and the server.</p>
<p>The way to make a command run even after you log out or close the session to a server is to use the <code>nohup</code> command.</p>
<p>Use <code>nohup &lt;command&gt;</code> to let the process continue working even after you log out.</p>
<h2 id="heading-the-linux-xargs-command">The Linux <code>xargs</code> command</h2>
<p>The <code>xargs</code> command is used in a UNIX shell to convert input from standard input into arguments to a command.</p>
<p>In other words, through the use of <code>xargs</code> the output of a command is used as the input of another command.</p>
<p>Here's the syntax you will use:</p>
<pre><code class="lang-bash">command1 | xargs command2
</code></pre>
<p>We use a pipe (<code>|</code>) to pass the output to <code>xargs</code>. That will take care of running the <code>command2</code> command, using the output of <code>command1</code> as its argument(s).</p>
<p>Let's do a simple example. You want to remove some specific files from a directory. Those files are listed inside a text file.</p>
<p>We have 3 files: <code>file1</code>, <code>file2</code>, <code>file3</code>.</p>
<p>In <code>todelete.txt</code> we have a list of files we want to delete, in this example <code>file1</code> and <code>file3</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-08-at-07.45.28.png" alt="Screen-Shot-2020-09-08-at-07.45.28" width="600" height="400" loading="lazy"></p>
<p>We will channel the output of <code>cat todelete.txt</code> to the <code>rm</code> command, through <code>xargs</code>.</p>
<p>In this way:</p>
<pre><code class="lang-bash">cat todelete.txt | xargs rm
</code></pre>
<p>That's the result, the files we listed are now deleted:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-08-at-07.46.39.png" alt="Screen-Shot-2020-09-08-at-07.46.39" width="600" height="400" loading="lazy"></p>
<p>The way it works is that <code>xargs</code> will run <code>rm</code> 2 times, one for each line returned by <code>cat</code>.</p>
<p>This is the simplest usage of <code>xargs</code>. There are several options we can use.</p>
<p>One of the most useful, in my opinion (especially when starting to learn <code>xargs</code>), is <code>-p</code>. Using this option will make <code>xargs</code> print a confirmation prompt with the action it's going to take:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-08-at-08.19.09.png" alt="Screen-Shot-2020-09-08-at-08.19.09" width="600" height="400" loading="lazy"></p>
<p>The <code>-n</code> option lets you tell <code>xargs</code> to perform one iteration at a time, so you can individually confirm them with <code>-p</code>. Here we tell <code>xargs</code> to perform one iteration at a time with <code>-n1</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-08-at-08.32.58.png" alt="Screen-Shot-2020-09-08-at-08.32.58" width="600" height="400" loading="lazy"></p>
<p>The <code>-I</code> option is another widely used one. It allows you to get the output into a placeholder, and then you can do various things.</p>
<p>One of them is to run multiple commands:</p>
<pre><code class="lang-bash">command1 | xargs -I % /bin/bash -c <span class="hljs-string">'command2 %; command3 %'</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-08-at-08.35.37.png" alt="Screen-Shot-2020-09-08-at-08.35.37" width="600" height="400" loading="lazy"></p>
<blockquote>
<p>You can swap the <code>%</code> symbol I used above with anything else – it's a variable.</p>
</blockquote>
<h2 id="heading-the-linux-vim-editor-command">The Linux <code>vim</code> editor command</h2>
<p><code>vim</code> is a <strong>very</strong> popular file editor, especially among programmers. It's actively developed and frequently updated, and there's a big community around it. There's even a <a target="_blank" href="https://vimconf.org/">Vim conference</a>!</p>
<p><code>vi</code> in modern systems is just an alias for <code>vim</code>, which means <code>vi</code> i<code>m</code>proved.</p>
<p>You start it by running <code>vi</code> on the command line.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screenshot-2019-02-10-at-11.44.36.png" alt="Screenshot-2019-02-10-at-11.44.36" width="600" height="400" loading="lazy"></p>
<p>You can specify a filename at invocation time to edit that specific file:</p>
<pre><code class="lang-bash">vi test.txt
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screenshot-2019-02-10-at-11.36.21.png" alt="Screenshot-2019-02-10-at-11.36.21" width="600" height="400" loading="lazy"></p>
<p>You have to know that Vim has 2 main modes:</p>
<ul>
<li><em>command</em> (or <em>normal</em>) mode</li>
<li><em>insert</em> mode</li>
</ul>
<p>When you start the editor, you are in command mode. You can't enter text like you expect from a GUI-based editor. You have to enter <strong>insert mode</strong>. </p>
<p>You can do this by pressing the <code>i</code> key. Once you do so, the <code>-- INSERT --</code> word appears at the bottom of the editor:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screenshot-2019-02-10-at-11.47.39.png" alt="Screenshot-2019-02-10-at-11.47.39" width="600" height="400" loading="lazy"></p>
<p>Now you can start typing and filling the screen with the file contents:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screenshot-2019-02-10-at-11.48.39.png" alt="Screenshot-2019-02-10-at-11.48.39" width="600" height="400" loading="lazy"></p>
<p>You can move around the file with the arrow keys, or using the <code>h</code> - <code>j</code> - <code>k</code> - <code>l</code> keys. <code>h-l</code> for left-right, <code>j-k</code> for down-up.</p>
<p>Once you are done editing you can press the <code>esc</code> key to exit insert mode and go back to <strong>command mode</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screenshot-2019-02-10-at-11.48.44.png" alt="Screenshot-2019-02-10-at-11.48.44" width="600" height="400" loading="lazy">
At this point you can navigate the file, but you can't add content to it (and be careful which keys you press, as they might be commands).</p>
<p>One thing you might want to do now is <strong>save the file</strong>. You can do so by pressing <code>:</code> (colon), then <code>w</code>.</p>
<p>You can <strong>save and quit</strong> by pressing <code>:</code> then <code>w</code> and <code>q</code>: <code>:wq</code></p>
<p>You can <strong>quit without saving</strong> by pressing <code>:</code> then <code>q</code> and <code>!</code>: <code>:q!</code></p>
<p>You can <strong>undo</strong> and edit by going to command mode and pressing <code>u</code>. You can <strong>redo</strong> (cancel an undo) by pressing <code>ctrl-r</code>.</p>
<p>Those are the basics of working with Vim. From here starts a rabbit hole we can't go into in this little introduction.</p>
<p>I will only mention those commands that will get you started editing with Vim:</p>
<ul>
<li>pressing the <code>x</code> key deletes the character currently highlighted</li>
<li>pressing <code>A</code> goes to the end of the currently selected line</li>
<li>press <code>0</code> to go to the start of the line</li>
<li>go to the first character of a word and press <code>d</code> followed by <code>w</code> to delete that word. If you follow it with <code>e</code> instead of <code>w</code>, the white space before the next word is preserved</li>
<li>use a number between <code>d</code> and <code>w</code> to delete more than 1 word, for example use <code>d3w</code> to delete 3 words forward</li>
<li>press <code>d</code> followed by <code>d</code> to delete a whole entire line. Press <code>d</code> followed by <code>$</code> to delete the entire line from where the cursor is, until the end</li>
</ul>
<p>To find out more about Vim I can recommend the <a target="_blank" href="https://vimhelp.org/vim_faq.txt.html">Vim FAQ</a>. You can also run the <code>vimtutor</code> command, which should already be installed in your system and will greatly help you start your <code>vim</code> exploration.</p>
<h2 id="heading-the-linux-emacs-editor-command">The Linux <code>emacs</code> editor command</h2>
<p><code>emacs</code> is an awesome editor and it's historically regarded as <em>the</em> editor for UNIX systems. Famously, <code>vi</code> vs <code>emacs</code> flame wars and heated discussions have caused many unproductive hours for developers around the world.</p>
<p><code>emacs</code> is very powerful. Some people use it all day long as a kind of operating system (https://news.ycombinator.com/item?id=19127258). We'll just talk about the basics here.</p>
<p>You can open a new emacs session simply by invoking <code>emacs</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screenshot-2019-02-10-at-12.14.18.png" alt="Screenshot-2019-02-10-at-12.14.18" width="600" height="400" loading="lazy"></p>
<blockquote>
<p>macOS users, stop a second now. If you are on Linux there are no problems, but macOS does not ship applications using GPLv3, and every built-in UNIX command that has been updated to GPLv3 has not been updated. </p>
<p>While there is a little problem with the commands I listed up to now, in this case using an emacs version from 2007 is not exactly the same as using a version with 12 years of improvements and change. </p>
<p>This is not a problem with Vim, which is up to date. To fix this, run <code>brew install emacs</code> and running <code>emacs</code> will use the new version from Homebrew (make sure you have <a target="_blank" href="https://flaviocopes.com/homebrew/">Homebrew</a> installed).</p>
</blockquote>
<p>You can also edit an existing file by calling <code>emacs &lt;filename&gt;</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screenshot-2019-02-10-at-13.12.49.png" alt="Screenshot-2019-02-10-at-13.12.49" width="600" height="400" loading="lazy"></p>
<p>You can now start editing. Once you are done, press <code>ctrl-x</code> followed by <code>ctrl-w</code>. You confirm the folder:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screenshot-2019-02-10-at-13.14.29.png" alt="Screenshot-2019-02-10-at-13.14.29" width="600" height="400" loading="lazy"></p>
<p>and Emacs tells you the file exists, asking you if it should overwrite it:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screenshot-2019-02-10-at-13.14.32.png" alt="Screenshot-2019-02-10-at-13.14.32" width="600" height="400" loading="lazy"></p>
<p>Answer <code>y</code>, and you get a confirmation of success:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screenshot-2019-02-10-at-13.14.35.png" alt="Screenshot-2019-02-10-at-13.14.35" width="600" height="400" loading="lazy">
You can exit Emacs by pressing <code>ctrl-x</code> followed by <code>ctrl-c</code>.
Or <code>ctrl-x</code> followed by <code>c</code> (keep <code>ctrl</code> pressed).</p>
<p>There is a lot to know about Emacs, certainly more than I am able to write in this little introduction. I encourage you to open Emacs and press <code>ctrl-h</code> <code>r</code> to open the built-in manual and <code>ctrl-h</code> <code>t</code> to open the official tutorial.</p>
<h2 id="heading-the-linux-nano-editor-command">The Linux <code>nano</code> editor command</h2>
<p><code>nano</code> is a beginner friendly editor.</p>
<p>Run it using <code>nano &lt;filename&gt;</code>.</p>
<p>You can directly type characters into the file without worrying about modes.</p>
<p>You can quit without editing using <code>ctrl-X</code>. If you edited the file buffer, the editor will ask you for confirmation and you can save the edits, or discard them. </p>
<p>The help at the bottom shows you the keyboard commands that let you work with the file:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screenshot-2019-02-10-at-11.03.51.png" alt="Screenshot-2019-02-10-at-11.03.51" width="600" height="400" loading="lazy">
<code>pico</code> is more or less the same, although <code>nano</code> is the GNU version of <code>pico</code> which at some point in history was not open source. The <code>nano</code> clone was made to satisfy the GNU operating system license requirements.</p>
<h2 id="heading-the-linux-whoami-command">The Linux <code>whoami</code> command</h2>
<p>Type <code>whoami</code> to print the user name currently logged in to the terminal session:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-18.08.05.png" alt="Screen-Shot-2020-09-03-at-18.08.05" width="600" height="400" loading="lazy"></p>
<blockquote>
<p>Note: this is different from the <code>who am i</code> command, which prints more information</p>
</blockquote>
<h2 id="heading-the-linux-who-command">The Linux <code>who</code> command</h2>
<p>The <code>who</code> command displays the users logged in to the system.</p>
<p>Unless you're using a server multiple people have access to, chances are you will be the only user logged in, multiple times:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-18.03.05.png" alt="Screen-Shot-2020-09-03-at-18.03.05" width="600" height="400" loading="lazy"></p>
<p>Why multiple times? Because each shell opened will count as an access.</p>
<p>You can see the name of the terminal used, and the time/day the session was started.</p>
<p>The <code>-aH</code> flags will tell <code>who</code> to display more information, including the idle time and the process ID of the terminal:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-18.05.29.png" alt="Screen-Shot-2020-09-03-at-18.05.29" width="600" height="400" loading="lazy"></p>
<p>The special <code>who am i</code> command will list the current terminal session details:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-18.06.35.png" alt="Screen-Shot-2020-09-03-at-18.06.35" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-18.07.30.png" alt="Screen-Shot-2020-09-03-at-18.07.30" width="600" height="400" loading="lazy"></p>
<h2 id="heading-the-linux-su-command">The Linux <code>su</code> command</h2>
<p>While you're logged in to the terminal shell with one user, you might need to switch to another user.</p>
<p>For example you're logged in as root to perform some maintenance, but then you want to switch to a user account.</p>
<p>You can do so with the <code>su</code> command:</p>
<pre><code class="lang-bash">su &lt;username&gt;
</code></pre>
<p>For example: <code>su flavio</code>.</p>
<p>If you're logged in as a user, running <code>su</code> without anything else will prompt you to enter the <code>root</code> user password, as that's the default behavior.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-18.18.09.png" alt="Screen-Shot-2020-09-03-at-18.18.09" width="600" height="400" loading="lazy">
<code>su</code> will start a new shell as another user.</p>
<p>When you're done, typing <code>exit</code> in the shell will close that shell, and will return you back to the current user's shell.</p>
<h2 id="heading-the-linux-sudo-command">The Linux <code>sudo</code> command</h2>
<p><code>sudo</code> is commonly used to run a command as root.</p>
<p>You must be enabled to use <code>sudo</code>, and once you are, you can run commands as root by entering your user's password (<em>not</em> the root user password).</p>
<p>The permissions are highly configurable, which is great especially in a multi-user server environment. Some users can be granted access to running specific commands through <code>sudo</code>.</p>
<p>For example you can edit a system configuration file:</p>
<pre><code class="lang-bash">sudo nano /etc/hosts
</code></pre>
<p>which would otherwise fail to save since you don't have the permissions
for it.</p>
<p>You can run <code>sudo -i</code> to start a shell as root:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-18.25.50.png" alt="Screen-Shot-2020-09-03-at-18.25.50" width="600" height="400" loading="lazy"></p>
<p>You can use <code>sudo</code> to run commands as any user. <code>root</code> is the default, but use the <code>-u</code> option to specify another user:</p>
<pre><code class="lang-bash">sudo -u flavio ls /Users/flavio
</code></pre>
<h2 id="heading-the-linux-passwd-command">The Linux <code>passwd</code> command</h2>
<p>Users in Linux have a password assigned. You can change the password using the <code>passwd</code> command.</p>
<p>There are two situations here.</p>
<p>The first is when you want to change your password. In this case you type:</p>
<pre><code class="lang-bash">passwd
</code></pre>
<p>and an interactive prompt will ask you for the old password, then it will ask you for the new one:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-04-at-07.32.05.png" alt="Screen-Shot-2020-09-04-at-07.32.05" width="600" height="400" loading="lazy"></p>
<p>When you're <code>root</code> (or have superuser privileges) you can set the username for which you want to change the password:</p>
<pre><code class="lang-bash">passwd &lt;username&gt; &lt;new password&gt;
</code></pre>
<p>In this case you don't need to enter the old one.</p>
<h2 id="heading-the-linux-ping-command">The Linux <code>ping</code> command</h2>
<p>The <code>ping</code> command pings a specific network host, on the local network or on the Internet.</p>
<p>You use it with the syntax <code>ping &lt;host&gt;</code> where <code>&lt;host&gt;</code> could be a domain name, or an IP address.</p>
<p>Here's an example pinging <code>google.com</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-09-at-15.21.46.png" alt="Screen-Shot-2020-09-09-at-15.21.46" width="600" height="400" loading="lazy">
The command sends a request to the server, and the server returns a response.</p>
<p><code>ping</code> keeps sending the request every second, by default. It will keep running until you stop it with <code>ctrl-C</code>, unless you pass the number of times you want to try with the <code>-c</code> option: <code>ping -c 2 google.com</code>.</p>
<p>Once <code>ping</code> is stopped, it will print some statistics about the results: the percentage of packages lost, and statistics about the network performance.</p>
<p>As you can see the screen prints the host IP address, and the time that it took to get the response back.</p>
<p>Not all servers support pinging, in case the request times out:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-09-at-15.21.27.png" alt="Screen-Shot-2020-09-09-at-15.21.27" width="600" height="400" loading="lazy"></p>
<p>Sometimes this is done on purpose, to "hide" the server, or just to reduce the load. The ping packets can also be filtered by firewalls.</p>
<p><code>ping</code> works using the <strong>ICMP protocol</strong> (<em>Internet Control Message Protocol</em>), a network layer protocol just like TCP or UDP.</p>
<p>The request sends a packet to the server with the <code>ECHO_REQUEST</code> message, and the server returns a <code>ECHO_REPLY</code> message. I won't go into details, but this is the basic concept.</p>
<p>Pinging a host is useful to know if the host is reachable (supposing it implements ping), and how distant it is in terms of how long it takes to get back to you. </p>
<p>Usually the nearer the server is geographically, the less time it will take to return back to you. Simple physical laws cause a longer distance to introduce more delay in the cables.</p>
<h2 id="heading-the-linux-traceroute-command">The Linux <code>traceroute</code> command</h2>
<p>When you try to reach a host on the Internet, you go through your home router. Then you reach your ISP network, which in turn goes through its own upstream network router, and so on, until you finally reach the host.</p>
<p>Have you ever wanted to know what steps your packets go through to do that?</p>
<p>The <code>traceroute</code> command is made for this.</p>
<p>You invoke</p>
<pre><code class="lang-bash">traceroute &lt;host&gt;
</code></pre>
<p>and it will (slowly) gather all the information while the packet travels.</p>
<p>In this example I tried reaching for my blog with <code>traceroute flaviocopes.com</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-09-at-16.32.01.png" alt="Screen-Shot-2020-09-09-at-16.32.01" width="600" height="400" loading="lazy"></p>
<p>Not every router travelled returns us information. In this case, <code>traceroute</code> prints <code>* * *</code>. Otherwise, we can see the hostname, the IP address, and some performance indicator.</p>
<p>For every router we can see 3 samples, which means traceroute tries by default 3 times to get you a good indication of the time needed to reach it. </p>
<p>This is why it takes this long to execute <code>traceroute</code> compared to simply doing a <code>ping</code> to that host.</p>
<p>You can customize this number with the <code>-q</code> option:</p>
<pre><code class="lang-bash">traceroute -q 1 flaviocopes.com
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-09-at-16.36.07.png" alt="Screen-Shot-2020-09-09-at-16.36.07" width="600" height="400" loading="lazy"></p>
<h2 id="heading-the-linux-clear-command">The Linux <code>clear</code> command</h2>
<p>Type <code>clear</code> to clear all the previous commands that were run in the current terminal.</p>
<p>The screen will clear and you will just see the prompt at the top:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-03-at-18.10.32.png" alt="Screen-Shot-2020-09-03-at-18.10.32" width="600" height="400" loading="lazy"></p>
<blockquote>
<p>Note: this command has a handy shortcut: <code>ctrl-L</code></p>
</blockquote>
<p>Once you do that, you will lose access to scrolling to see the output of the previous commands entered.</p>
<p>So you might want to use <code>clear -x</code> instead, which still clears the screen, but lets you go back to see the previous work by scrolling up.</p>
<h2 id="heading-the-linux-history-command">The Linux <code>history</code> command</h2>
<p>Every time you run a command, it's memorized in the history.</p>
<p>You can display all the history using:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">history</span>
</code></pre>
<p>This shows the history with numbers:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-04-at-08.03.10.png" alt="Screen-Shot-2020-09-04-at-08.03.10" width="600" height="400" loading="lazy"></p>
<p>You can use the syntax <code>!&lt;command number&gt;</code> to repeat a command stored in the history. In the above example typing <code>!121</code> will repeat the <code>ls -al | wc -l</code> command.</p>
<p>Typically the last 500 commands are stored in the history.</p>
<p>You can combine this with <code>grep</code> to find a command you ran:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">history</span> | grep docker
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-04-at-08.04.50.png" alt="Screen-Shot-2020-09-04-at-08.04.50" width="600" height="400" loading="lazy">
To clear the history, run <code>history -c</code>.</p>
<h2 id="heading-the-linux-export-command">The Linux <code>export</code> command</h2>
<p>The <code>export</code> command is used to export variables to child processes.</p>
<p>What does this mean?</p>
<p>Suppose you have a variable TEST defined in this way:</p>
<pre><code class="lang-bash">TEST=<span class="hljs-string">"test"</span>
</code></pre>
<p>You can print its value using <code>echo $TEST</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-09-at-17.32.49.png" alt="Screen-Shot-2020-09-09-at-17.32.49" width="600" height="400" loading="lazy"></p>
<p>But if you try defining a Bash script in a file <code>script.sh</code> with the above command:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-09-at-17.35.23.png" alt="Screen-Shot-2020-09-09-at-17.35.23" width="600" height="400" loading="lazy"></p>
<p>Then when you set <code>chmod u+x script.sh</code> and you execute this script with <code>./script.sh</code>, the <code>echo $TEST</code> line will print nothing!</p>
<p>This is because in Bash the <code>TEST</code> variable was defined local to the shell. When executing a shell script or another command, a subshell is launched to execute it, which does not contain the current shell local variables.</p>
<p>To make the variable available there we need to define <code>TEST</code> not in this way:</p>
<pre><code class="lang-bash">TEST=<span class="hljs-string">"test"</span>
</code></pre>
<p>but in this way:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">export</span> TEST=<span class="hljs-string">"test"</span>
</code></pre>
<p>Try that, and running <code>./script.sh</code> now should print "test":</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-09-at-17.37.56.png" alt="Screen-Shot-2020-09-09-at-17.37.56" width="600" height="400" loading="lazy">
Sometimes you need to append something to a variable. It's often done with the <code>PATH</code> variable. You use this syntax:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">export</span> PATH=<span class="hljs-variable">$PATH</span>:/new/path
</code></pre>
<p>It's common to use <code>export</code> when you create new variables in this way. But you can also use it when you create variables in the <code>.bash_profile</code> or <code>.bashrc</code> configuration files with Bash, or in <code>.zshenv</code> with Zsh.</p>
<p>To remove a variable, use the <code>-n</code> option:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">export</span> -n TEST
</code></pre>
<p>Calling <code>export</code> without any option will list all the exported variables.</p>
<h2 id="heading-the-linux-crontab-command">The Linux <code>crontab</code> command</h2>
<p>Cron jobs are jobs that are scheduled to run at specific intervals. You might have a command perform something every hour, or every day, or every 2 weeks. Or on weekends. </p>
<p>They are very powerful, especially when used on servers to perform maintenance and automations.</p>
<p>The <code>crontab</code> command is the entry point to work with cron jobs.</p>
<p>The first thing you can do is to explore which cron jobs are defined by you:</p>
<pre><code class="lang-bash">crontab -l
</code></pre>
<p>You might have none, like me:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-09-at-17.54.31.png" alt="Screen-Shot-2020-09-09-at-17.54.31" width="600" height="400" loading="lazy"></p>
<p>Run</p>
<pre><code class="lang-bash">crontab -e
</code></pre>
<p>to edit the cron jobs, and add new ones.</p>
<p>By default this opens with the default editor, which is usually <code>vim</code>. I like <code>nano</code> more. You can use this line to use a different editor:</p>
<pre><code class="lang-bash">EDITOR=nano crontab -e
</code></pre>
<p>Now you can add one line for each cron job.</p>
<p>The syntax to define cron jobs is kind of scary. This is why I usually use a website to help me generate it without errors: <a target="_blank" href="https://crontab-generator.org/">https://crontab-generator.org/</a></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-09-at-18.03.57.png" alt="Screen-Shot-2020-09-09-at-18.03.57" width="600" height="400" loading="lazy"></p>
<p>You pick a time interval for the cron job, and you type the command to execute.</p>
<p>I chose to run a script located in <code>/Users/flavio/test.sh</code> every 12 hours. This is the crontab line I need to run:</p>
<pre><code class="lang-txt">* */12 * * * /Users/flavio/test.sh &gt;/dev/null 2&gt;&amp;1
</code></pre>
<p>I run <code>crontab -e</code>:</p>
<pre><code class="lang-bash">EDITOR=nano crontab -e
</code></pre>
<p>and I add that line, then I press <code>ctrl-X</code> and press <code>y</code> to save.</p>
<p>If all goes well, the cron job is set up:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-09-at-18.06.19.png" alt="Screen-Shot-2020-09-09-at-18.06.19" width="600" height="400" loading="lazy"></p>
<p>Once this is done, you can see the list of active cron jobs by running:</p>
<pre><code class="lang-bash">crontab -l
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-09-at-18.07.00.png" alt="Screen-Shot-2020-09-09-at-18.07.00" width="600" height="400" loading="lazy"></p>
<p>You can remove a cron job running <code>crontab -e</code> again, removing the line and exiting the editor:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-09-at-18.07.40.png" alt="Screen-Shot-2020-09-09-at-18.07.40" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-09-at-18.07.49.png" alt="Screen-Shot-2020-09-09-at-18.07.49" width="600" height="400" loading="lazy"></p>
<h2 id="heading-the-linux-uname-command">The Linux <code>uname</code> command</h2>
<p>Calling <code>uname</code> without any options will return the Operating System codename:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-07-at-07.37.41.png" alt="Screen-Shot-2020-09-07-at-07.37.41" width="600" height="400" loading="lazy"></p>
<p>The <code>m</code> option shows the hardware name (<code>x86_64</code> in this example) and the <code>p</code> option prints the processor architecture name (<code>i386</code> in this example):</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-07-at-07.37.51.png" alt="Screen-Shot-2020-09-07-at-07.37.51" width="600" height="400" loading="lazy"></p>
<p>The <code>s</code> option prints the Operating System name. <code>r</code> prints the release, and <code>v</code> prints the version:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-07-at-07.37.56.png" alt="Screen-Shot-2020-09-07-at-07.37.56" width="600" height="400" loading="lazy"></p>
<p>The <code>n</code> option prints the node network name:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-07-at-07.38.01.png" alt="Screen-Shot-2020-09-07-at-07.38.01" width="600" height="400" loading="lazy"></p>
<p>The <code>a</code> option prints all the information available:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-07-at-07.38.06.png" alt="Screen-Shot-2020-09-07-at-07.38.06" width="600" height="400" loading="lazy"></p>
<p>On macOS you can also use the <code>sw_vers</code> command to print more information about the macOS Operating System. Note that this differs from the Darwin (the Kernel) version, which above is <code>19.6.0</code>.</p>
<blockquote>
<p>Darwin is the name of the kernel of macOS. The kernel is the "core" of the Operating System, while the Operating System as a whole is called macOS. In Linux, Linux is the kernel, and GNU/Linux would be the Operating System name (although we all refer to it as "Linux").</p>
</blockquote>
<h2 id="heading-the-linux-env-command">The Linux <code>env</code> command</h2>
<p>The <code>env</code> command can be used to pass environment variables without setting them on the outer environment (the current shell).</p>
<p>Suppose you want to run a Node.js app and set the <code>USER</code> variable to it.</p>
<p>You can run</p>
<pre><code class="lang-bash">env USER=flavio node app.js
</code></pre>
<p>and the <code>USER</code> environment variable will be accessible from the Node.js app via the Node <code>process.env</code> interface.</p>
<p>You can also run the command clearing all the environment variables already set, using the <code>-i</code> option:</p>
<pre><code class="lang-bash">env -i node app.js
</code></pre>
<p>In this case you will get an error saying <code>env: node: No such file or directory</code> because the <code>node</code> command is not reachable, as the <code>PATH</code> variable used by the shell to look up commands in the common paths is unset.</p>
<p>So you need to pass the full path to the <code>node</code> program:</p>
<pre><code class="lang-bash">env -i /usr/<span class="hljs-built_in">local</span>/bin/node app.js
</code></pre>
<p>Try with a simple <code>app.js</code> file with this content:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(process.env.NAME)
<span class="hljs-built_in">console</span>.log(process.env.PATH)
</code></pre>
<p>You will see the output as</p>
<pre><code><span class="hljs-literal">undefined</span>
<span class="hljs-literal">undefined</span>
</code></pre><p>You can pass an env variable:</p>
<pre><code class="lang-bash">env -i NAME=flavio node app.js
</code></pre>
<p>and the output will be</p>
<pre><code>flavio
<span class="hljs-literal">undefined</span>
</code></pre><p>Removing the <code>-i</code> option will make <code>PATH</code> available again inside the program:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-10-at-16.55.17.png" alt="Screen-Shot-2020-09-10-at-16.55.17" width="600" height="400" loading="lazy"></p>
<p>The <code>env</code> command can also be used to print out all the environment variables. If run with no options:</p>
<pre><code class="lang-bash">env
</code></pre>
<p>it will return a list of the environment variables set, for example:</p>
<pre><code class="lang-txt">HOME=/Users/flavio
LOGNAME=flavio
PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin
PWD=/Users/flavio
SHELL=/usr/local/bin/fish
</code></pre>
<p>You can also make a variable inaccessible inside the program you run, using the <code>-u</code> option. For example this code removes the <code>HOME</code> variable from the command environment:</p>
<pre><code class="lang-bash">env -u HOME node app.js
</code></pre>
<h2 id="heading-the-linux-printenv-command">The Linux <code>printenv</code> command</h2>
<p>Here's a quick guide to the <code>printenv</code> command, used to print the values of environment variables</p>
<p>In any shell there are a good number of environment variables, set either by the system, or by your own shell scripts and configuration.</p>
<p>You can print them all to the terminal using the <code>printenv</code> command. The output will be something like this:</p>
<pre><code class="lang-txt">HOME=/Users/flavio
LOGNAME=flavio
PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin
PWD=/Users/flavio
SHELL=/usr/local/bin/fish
</code></pre>
<p>with a few more lines, usually.</p>
<p>You can append a variable name as a parameter, to only show that variable value:</p>
<pre><code class="lang-bash">printenv PATH
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/Screen-Shot-2020-09-10-at-16.31.20.png" alt="Screen-Shot-2020-09-10-at-16.31.20" width="600" height="400" loading="lazy"></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Thanks a lot for reading this handbook.</p>
<p>I hope it will inspire you to learn more about Linux and its capabilities. It's evergreen knowledge that will not be out of date any time soon.</p>
<p>Remember that you can <a target="_blank" href="https://flaviocopes.com/page/linux-commands-handbook/">download this handbook in PDF / ePUB / Mobi format</a> if you want!</p>
<p>I <strong>publish programming tutorials</strong> every day on my website <a target="_blank" href="https://flaviocopes.com">flaviocopes.com</a> if you want to check out more great content like this.</p>
<p>You can reach me on Twitter <a target="_blank" href="https://twitter.com/flaviocopes">@flaviocopes</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Deno Handbook – A TypeScript Runtime Tutorial with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ I explore new projects every week, and it’s rare that one grabs my attention as much as Deno did. In this post I want to get you up to speed with Deno quickly. We'll compare it with Node.js, and build your first REST API with it. Table of contents W... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-deno-handbook/</link>
                <guid isPermaLink="false">66bb5aa3965d5c9ed5487bb4</guid>
                
                    <category>
                        <![CDATA[ Deno ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Flavio Copes ]]>
                </dc:creator>
                <pubDate>Tue, 12 May 2020 12:00:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/05/Screen-Shot-2020-05-11-at-18.55.24.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>I explore new projects every week, and it’s rare that one grabs my attention as much as <a target="_blank" href="https://deno.land/">Deno</a> did.</p>
<p>In this post I want to get you up to speed with Deno quickly. We'll compare it with Node.js, and build your first REST API with it.</p>
<h2 id="heading-table-of-contents">Table of contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-what-is-deno">What is Deno?</a></li>
<li><a class="post-section-overview" href="#heading-why-deno-why-now">Why Deno? Why now?</a></li>
<li><a class="post-section-overview" href="#heading-should-you-learn-deno">Should you learn Deno?</a></li>
<li><a class="post-section-overview" href="#heading-will-it-replace-nodejs">Will it replace Node.js?</a></li>
<li><a class="post-section-overview" href="#heading-first-class-typescript-support">First-class TypeScript support</a></li>
<li><a class="post-section-overview" href="#heading-similarities-and-differences-with-nodejs">Similarities and differences with Node.js</a></li>
<li><a class="post-section-overview" href="#heading-no-package-manager">No package manager</a></li>
<li><a class="post-section-overview" href="#heading-install-deno">Install Deno</a></li>
<li><a class="post-section-overview" href="#heading-the-deno-commands">The Deno commands</a></li>
<li><a class="post-section-overview" href="#heading-your-first-deno-app">Your first Deno app</a></li>
<li><a class="post-section-overview" href="#heading-deno-code-examples">Deno code examples</a></li>
<li><a class="post-section-overview" href="#heading-your-first-deno-app-for-real">Your first Deno app (for real)</a></li>
<li><a class="post-section-overview" href="#heading-the-deno-sandbox">The Deno sandbox</a></li>
<li><a class="post-section-overview" href="#heading-formatting-code">Formatting code</a></li>
<li><a class="post-section-overview" href="#heading-the-standard-library">The standard library</a></li>
<li><a class="post-section-overview" href="#heading-another-deno-example">Another Deno example</a></li>
<li><a class="post-section-overview" href="#heading-is-there-an-expresshapikoa-for-deno">Is there an Express/Hapi/Koa/* for Deno?</a></li>
<li><a class="post-section-overview" href="#heading-example-use-oak-to-build-a-rest-api">Example: use Oak to build a REST API</a></li>
<li><a class="post-section-overview" href="#heading-find-out-more">Find out more</a></li>
<li><a class="post-section-overview" href="#heading-a-few-more-random-tidbits">A few more random tidbits</a></li>
</ul>
<p>And note: <a target="_blank" href="https://flaviocopes.com/page/deno-handbook/">You can get a PDF/ePub/Mobi version of this Deno Handbook here</a>.</p>
<h2 id="heading-what-is-deno">What is Deno?</h2>
<p>If you are familiar with Node.js, the popular server-side JavaScript ecosystem, then Deno is just like Node. Except deeply improved in many ways.</p>
<p>Let’s start from a quick list of the features I like the most about Deno:</p>
<ul>
<li>It is based on modern features of the JavaScript language</li>
<li>It has an extensive standard library</li>
<li>It has TypeScript at its core, which brings a huge advantage in many different ways, including a first-class TypeScript support (you don’t have to separately compile TypeScript, it’s automatically done by Deno)</li>
<li>It embraces <a target="_blank" href="https://flaviocopes.com/es-modules/">ES modules</a></li>
<li>It has no package manager</li>
<li>It has a first-class <code>await</code></li>
<li>It has a built-in testing facility</li>
<li>It aims to be browser-compatible as much as it can, for example by providing a built-in <code>fetch</code> and the global <code>window</code> object</li>
</ul>
<p>We’ll explore all of those features in this guide.</p>
<p>After you use Deno and learn to appreciate its features, Node.js will look like something <em>old</em>.</p>
<p>Especially because the Node.js API is callback-based, as it was written way before promises and async/await. There’s no change available for that in Node, because such a change would be monumental. So we’re stuck with callbacks or with promisifying API calls.</p>
<p>Node.js is <strong>awesome</strong> and will continue to be the de facto standard in the JavaScript world. But I think we’ll gradually see Deno get adopted more and more because of its first-class TypeScript support and modern standard library.</p>
<p>Deno can afford to have everything written with modern technologies, since there’s no backward compatibility to maintain. Of course there’s no guarantee that in a decade the same will happen to Deno and a new technology will emerge, but this is the reality at the moment.</p>
<h2 id="heading-why-deno-why-now">Why Deno? Why now?</h2>
<p>Deno was announced almost 2 years ago by the original creator of Node.js, Ryan Dahl, at JSConf EU. Watch <a target="_blank" href="https://www.youtube.com/watch?v=M3BM9TB-8yA">the YouTube video of the talk</a>, it’s very interesting and it’s a mandatory watch if you are involved in Node.js and JavaScript in general.</p>
<p>Every project manager must make decisions. Ryan regretted some early decisions in Node. Also, technology evolves, and today JavaScript is a totally different language than what it was back in 2009 when Node started. Think about the modern ES6/2016/2017 features, and so on.</p>
<p>So he started a new project to create some sort of second wave of JavaScript-powered server side apps.</p>
<p>The reason I am writing this guide now and not back then is because technologies need a lot of time to mature. And we have finally reached <strong>Deno 1.0</strong> (1.0 should be released on May 13, 2020), the first release of Deno officially declared stable.</p>
<p>That’s might seem to be just a number, but 1.0 means there will not be major breaking changes until Deno 2.0. This is a big deal when you dive into a new technology - you don’t want to learn something and then have it change too fast.</p>
<h2 id="heading-should-you-learn-deno">Should you learn Deno?</h2>
<p>That’s a big question.</p>
<p>Learning something new such as Deno is a big effort. My suggestion is that if you are starting out now with server-side JS and you don’t know Node yet, and have never written any TypeScript, I’d start with Node.</p>
<p>No one was ever fired for choosing Node.js (paraphrasing a common quote).</p>
<p>But if you love TypeScript, don’t depend on a gazillion npm packages in your projects and you want to use <code>await</code> anywhere, hey Deno might be what you’re looking for.</p>
<h2 id="heading-will-it-replace-nodejs">Will it replace Node.js?</h2>
<p>No. Node.js is a giant, well established, incredibly well-supported technology that is going to stay around for decades.</p>
<h2 id="heading-first-class-typescript-support">First-class TypeScript support</h2>
<p>Deno is written in Rust and TypeScript, two of the languages that are really growing fast today.</p>
<p>In particular, being written in TypeScript means we get a lot of the benefits of TypeScript even if we might choose to write our code in plain JavaScript.</p>
<p>And running TypeScript code with Deno does not require a compilation step - Deno does that automatically for you.</p>
<p>You are not forced to write in TypeScript, but the fact the core of Deno is written in TypeScript is huge.</p>
<p>First, an increasingly large percentage of JavaScript programmers love TypeScript.</p>
<p>Second, the tools you use can infer many information about software written in TypeScript, like Deno.</p>
<p>This means that when we code in VS Code, for example (which of course has a tight integration with TypeScript since both are developed at MicroSoft), we can get benefits like type checking as we write our code, and advanced <a target="_blank" href="https://code.visualstudio.com/docs/editor/intellisense">IntelliSense</a> features. In other words the editor can help us in a deeply useful way.</p>
<h2 id="heading-similarities-and-differences-with-nodejs">Similarities and differences with Node.js</h2>
<p>Since Deno is basically a Node.js replacement, it’s useful to compare the two directly.</p>
<p>Similarities:</p>
<ul>
<li>Both are developed upon the <a target="_blank" href="https://flaviocopes.com/v8/">V8 Chromium Engine</a></li>
<li>Both are great for developing server-side with JavaScript</li>
</ul>
<p>Differences:</p>
<ul>
<li>Node is written in C++ and JavaScript. Deno is written in Rust and TypeScript.</li>
<li>Node has an official package manager called <code>npm</code>. Deno does not, and instead lets you import any ES Module from URLs.</li>
<li>Node uses the CommonJS syntax for importing pacakges. Deno uses ES Modules, the official way.</li>
<li>Deno uses modern ECMAScript features in all its API and standard library, while Node.js uses a callbacks-based standard library and has no plans to upgrade it.</li>
<li>Deno offers a sandbox security layer through permissions. A program can only access the permissions set to the executable as flags by the user. A Node.js program can access anything the user can access.</li>
<li>Deno has for a long time envisioned the possibility of compiling a program into an executable that you can run without external dependencies, like Go, but <a target="_blank" href="https://github.com/denoland/deno/issues/986">it’s still not a thing yet</a>. That’d be a game changer.</li>
</ul>
<h2 id="heading-no-package-manager">No package manager</h2>
<p>Having no package manager and having to rely on URLs to host and import packages has pros and cons. I really like the pros: it’s very flexible, and we can create packages without publishing them on a repository like npm.</p>
<p>I think that some sort of package manager will emerge, but nothing official is out yet.</p>
<p>The Deno website provides code hosting (and thus distribution through URLs) to 3rd party packages: <a target="_blank" href="https://deno.land/x/">https://deno.land/x/</a></p>
<h2 id="heading-install-deno">Install Deno</h2>
<p>Enough talk! Let’s install Deno.</p>
<p>The easiest way is to use <a target="_blank" href="https://flaviocopes.com/homebrew/">Homebrew</a>:</p>
<pre><code class="lang-sh">brew install deno
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/Screen-Shot-2020-05-09-at-12.04.45.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Once this is done, you will have access to the <code>deno</code> command. Here’s the help that you can get using <code>deno --help</code>:</p>
<pre><code>flavio@mbp~&gt; deno --help
deno <span class="hljs-number">0.42</span><span class="hljs-number">.0</span>
A secure JavaScript and TypeScript runtime

<span class="hljs-attr">Docs</span>: https:<span class="hljs-comment">//deno.land/std/manual.md</span>
Modules: https:<span class="hljs-comment">//deno.land/std/ https://deno.land/x/</span>
Bugs: https:<span class="hljs-comment">//github.com/denoland/deno/issues</span>

To start the REPL, supply no <span class="hljs-built_in">arguments</span>:
  deno

To execute a script:
  deno run https:<span class="hljs-comment">//deno.land/std/examples/welcome.ts</span>
  deno https:<span class="hljs-comment">//deno.land/std/examples/welcome.ts</span>

To evaluate code <span class="hljs-keyword">in</span> the shell:
  deno <span class="hljs-built_in">eval</span> <span class="hljs-string">"console.log(30933 + 404)"</span>

Run <span class="hljs-string">'deno help run'</span> <span class="hljs-keyword">for</span> <span class="hljs-string">'run'</span>-specific flags.

USAGE:
    deno [OPTIONS] [SUBCOMMAND]

<span class="hljs-attr">OPTIONS</span>:
    -h, --help
            Prints help information

    -L, --log-level &lt;log-level&gt;
            <span class="hljs-built_in">Set</span> log level [possible values: debug, info]

    -q, --quiet
            Suppress diagnostic output
            By <span class="hljs-keyword">default</span>, subcommands print human-readable diagnostic messages to stderr.
            If the flag is set, restrict these messages to errors.
    -V, --version
            Prints version information


<span class="hljs-attr">SUBCOMMANDS</span>:
    bundle         Bundle <span class="hljs-built_in">module</span> and dependencies into single file
    cache          Cache the dependencies
    completions    Generate shell completions
    doc            Show documentation <span class="hljs-keyword">for</span> a <span class="hljs-built_in">module</span>
    <span class="hljs-built_in">eval</span>           Eval script
    fmt            Format source files
    help           Prints <span class="hljs-built_in">this</span> message or the help <span class="hljs-keyword">of</span> the given subcommand(s)
    info           Show info about cache or info related to source file
    install        Install script <span class="hljs-keyword">as</span> an executable
    repl           Read Eval Print Loop
    run            Run a program given a filename or url to the <span class="hljs-built_in">module</span>
    test           Run tests
    types          Print runtime TypeScript declarations
    upgrade        Upgrade deno executable to newest version

ENVIRONMENT VARIABLES:
    DENO_DIR             <span class="hljs-built_in">Set</span> deno<span class="hljs-string">'s base directory (defaults to $HOME/.deno)
    DENO_INSTALL_ROOT    Set deno install'</span>s output directory
                         (defaults to $HOME/.deno/bin)
    NO_COLOR             <span class="hljs-built_in">Set</span> to disable color
    HTTP_PROXY           <span class="hljs-built_in">Proxy</span> address <span class="hljs-keyword">for</span> HTTP requests
                         (<span class="hljs-built_in">module</span> downloads, fetch)
    HTTPS_PROXY          Same but <span class="hljs-keyword">for</span> HTTPS
</code></pre><h2 id="heading-the-deno-commands">The Deno commands</h2>
<p>Note the <code>SUBCOMMANDS</code> section in the help, that lists all the commands we can run. What subcommands do we have?</p>
<ul>
<li><code>bundle</code> bundle module and dependencies of a project into single file</li>
<li><code>cache</code> cache the dependencies</li>
<li><code>completions</code> generate shell completions</li>
<li><code>doc</code> show documentation for a module</li>
<li><code>eval</code> to evaluate a piece of code, e.g. <code>deno eval "console.log(1 + 2)"</code></li>
<li><code>fmt</code> a built-in code formatter (similar to <code>gofmt</code> in Go)</li>
<li><code>help</code> prints this message or the help of the given subcommand(s)</li>
<li><code>info</code> show info about cache or info related to source file</li>
<li><code>install</code> install script as an executable</li>
<li><code>repl</code> Read-Eval-Print-Loop (the default)</li>
<li><code>run</code> run a program given a filename or url to the module</li>
<li><code>test</code> run tests</li>
<li><code>types</code> print runtime TypeScript declarations</li>
<li><code>upgrade</code> upgrade <code>deno</code> to the newest version</li>
</ul>
<p>You can run <code>deno &lt;subcommand&gt; help</code> to get specific additional documentation for the command, for example <code>deno run --help</code>.</p>
<p>As the help says, we can use this command to start a REPL (Read-Execute-Print-Loop) using <code>deno</code> without any other option.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/Screen-Shot-2020-05-09-at-12.07.50.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This is the same as running <code>deno repl</code>.</p>
<p>A more common way you’ll use this command is to execute a Deno app contained in a TypeScript file.</p>
<p>You can run both TypeScript (<code>.ts</code>) files, or JavaScript (<code>.js</code>) files.</p>
<p>If you are unfamiliar with TypeScript, don’t worry: Deno is written in TypeScript, buf you can write your “client” applications in JavaScript.</p>
<p><em>My <a target="_blank" href="https://flaviocopes.com/typescript/">TypeScript tutorial</a> will help you get up and running quickly with TypeScript if you want.</em></p>
<h2 id="heading-your-first-deno-app">Your first Deno app</h2>
<p>Let’s run a Deno app for the first time.</p>
<p>What I find pretty amazing is that you don’t even have to write a single line - you can run a command from any URL.</p>
<p>Deno downloads the program, compiles it and then runs it:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/Screen-Shot-2020-05-09-at-12.22.30.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Of course running arbitrary code from the Internet is not a practice</em> I'd generally <em>recommend. In this case we are running it from the Deno official site, plus Deno has a sandbox that prevents programs to do anything you don’t want to allow. More on this later.</em></p>
<p>This program is very simple, just a <code>console.log()</code> call:</p>
<pre><code class="lang-ts"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Welcome to Deno ?'</span>)
</code></pre>
<p>If you open the <a target="_blank" href="https://deno.land/std/examples/welcome.ts">https://deno.land/std/examples/welcome.ts</a> URL with the browser, you’ll see this page:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/Screen-Shot-2020-05-09-at-13.50.00.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Weird, right? You’d probably expect a TypeScript file, but instead we have a web page. The reason is the Web server of the Deno website knows you’re using a browser and serves you a more user friendly page.</p>
<p>Download the same UR using <code>wget</code> for example, which requests the <code>text/plain</code> version of it instead of <code>text/html</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/Screen-Shot-2020-05-09-at-13.52.25.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If you want to run the program again, it’s now cached by Deno and it does not need to download it again:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/Screen-Shot-2020-05-09-at-12.22.47.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You can force a reload of the original source with the <code>--reload</code> flag:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/Screen-Shot-2020-05-09-at-12.28.57.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p><code>deno run</code> has lots of different options that were not listed in the <code>deno --help</code>. Instead, you need to run <code>deno run --help</code> to reveal them:</p>
<pre><code>flavio@mbp~&gt; deno run --help
deno-run
Run a program given a filename or url to the <span class="hljs-built_in">module</span>.

By <span class="hljs-keyword">default</span> all programs are run <span class="hljs-keyword">in</span> sandbox without access to disk, network or
ability to spawn subprocesses.
  deno run https:<span class="hljs-comment">//deno.land/std/examples/welcome.ts</span>

Grant all permissions:
  deno run -A https:<span class="hljs-comment">//deno.land/std/http/file_server.ts</span>

Grant permission to read <span class="hljs-keyword">from</span> disk and listen to network:
  deno run --allow-read --allow-net https:<span class="hljs-comment">//deno.land/std/http/file_server.ts</span>

Grant permission to read whitelisted files <span class="hljs-keyword">from</span> disk:
  deno run --allow-read=<span class="hljs-regexp">/etc https:/</span><span class="hljs-regexp">/deno.land/</span>std/http/file_server.ts

<span class="hljs-attr">USAGE</span>:
    deno run [OPTIONS] &lt;SCRIPT_ARG&gt;...

OPTIONS:
    -A, --allow-all
            Allow all permissions

        --allow-env
            Allow environment access

        --allow-hrtime
            Allow high resolution time measurement

        --allow-net=&lt;allow-net&gt;
            Allow network access

        --allow-plugin
            Allow loading plugins

        --allow-read=&lt;allow-read&gt;
            Allow file system read access

        --allow-run
            Allow running subprocesses

        --allow-write=&lt;allow-write&gt;
            Allow file system write access

        --cached-only
            Require that remote dependencies are already cached

        --cert &lt;FILE&gt;
            Load certificate authority from PEM encoded file

    -c, --config &lt;FILE&gt;
            Load tsconfig.json configuration file

    -h, --help
            Prints help information

        --importmap &lt;FILE&gt;
            UNSTABLE:
            Load import map file
            Docs: https://deno.land/std/manual.md#import-maps
            Specification: https://wicg.github.io/import-maps/
            Examples: https://github.com/WICG/import-maps#the-import-map
        --inspect=&lt;HOST:PORT&gt;
            activate inspector on host:port (default: 127.0.0.1:9229)

        --inspect-brk=&lt;HOST:PORT&gt;
            activate inspector on host:port and break at start of user script

        --lock &lt;FILE&gt;
            Check the specified lock file

        --lock-write
            Write lock file. Use with --lock.

    -L, --log-level &lt;log-level&gt;
            Set log level [possible values: debug, info]

        --no-remote
            Do not resolve remote modules

    -q, --quiet
            Suppress diagnostic output
            By default, subcommands print human-readable diagnostic messages to stderr.
            If the flag is set, restrict these messages to errors.
    -r, --reload=&lt;CACHE_BLACKLIST&gt;
            Reload source code cache (recompile TypeScript)
            --reload
              Reload everything
            --reload=https://deno.land/std
              Reload only standard modules
            --reload=https://deno.land/std/fs/utils.ts,https://deno.land/std/fmt/colors.ts
              Reloads specific modules
        --seed &lt;NUMBER&gt;
            Seed Math.random()

        --unstable
            Enable unstable APIs

        --v8-flags=&lt;v8-flags&gt;
            Set V8 command line options. For help: --v8-flags=--help


ARGS:
    &lt;SCRIPT_ARG&gt;...
            script args
</code></pre><h2 id="heading-deno-code-examples">Deno code examples</h2>
<p>In addition to the one we ran above, the Deno website provides some other examples you can check out: <a target="_blank" href="https://deno.land/std/examples/">https://deno.land/std/examples/</a>.</p>
<p>At the time of writing we can find:</p>
<ul>
<li><code>cat.ts</code> prints the content a list of files provided as arguments</li>
<li><code>catj.ts</code> prints the content a list of files provided as arguments</li>
<li><code>chat/</code> an implementation of a chat</li>
<li><code>colors.ts</code> an example of</li>
<li><code>curl.ts</code> a simple implementation of <code>curl</code> that prints the content of the URL specified as argument</li>
<li><code>echo_server.ts</code> a TCP echo server</li>
<li><code>gist.ts</code> a program to post files to gist.github.com</li>
<li><code>test.ts</code> a sample test suite</li>
<li><code>welcome.ts</code> a simple console.log statement (the first program we ran above)</li>
<li><code>xeval.ts</code> allows you to run any TypeScript code for any line of standard input received. <a target="_blank" href="https://youtu.be/HjdJzNoT_qg?t=1932">Once known as <code>deno xeval</code></a> but since removed from the official command.</li>
</ul>
<h2 id="heading-your-first-deno-app-for-real">Your first Deno app (for real)</h2>
<p>Let’s write some code.</p>
<p>Your first Deno app you ran using <code>deno run https://deno.land/std/examples/welcome.ts</code> was an app that someone else wrote, so you didn’t see anything in regards to how Deno code looks like.</p>
<p>We’ll start from the default example app listed on the Deno official website:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { serve } <span class="hljs-keyword">from</span> <span class="hljs-string">'https://deno.land/std/http/server.ts'</span>
<span class="hljs-keyword">const</span> s = serve({ port: <span class="hljs-number">8000</span> })
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'http://localhost:8000/'</span>)
<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> req <span class="hljs-keyword">of</span> s) {
  req.respond({ body: <span class="hljs-string">'Hello World\n'</span> })
}
</code></pre>
<p>This code imports the <code>serve</code> function from the <code>http/server</code> module. See? We don’t have to install it first, and it’s also not stored on your local machine like it happens with Node modules. This is one reason why the Deno installation was so fast.</p>
<p>Importing from <code>https://deno.land/std/http/server.ts</code> imports the latest version of the module. You can import a specific version using <code>@VERSION</code>, like this:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { serve } <span class="hljs-keyword">from</span> <span class="hljs-string">'https://deno.land/std@v0.42.0/http/server.ts'</span>
</code></pre>
<p>The <code>serve</code> function is defined like this in this file:</p>
<pre><code class="lang-ts"><span class="hljs-comment">/**
 * Create a HTTP server
 *
 *     import { serve } from "https://deno.land/std/http/server.ts";
 *     const body = "Hello World\n";
 *     const s = serve({ port: 8000 });
 *     for await (const req of s) {
 *       req.respond({ body });
 *     }
 */</span>
<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">serve</span>(<span class="hljs-params">addr: <span class="hljs-built_in">string</span> | HTTPOptions</span>): <span class="hljs-title">Server</span> </span>{
  <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> addr === <span class="hljs-string">'string'</span>) {
    <span class="hljs-keyword">const</span> [hostname, port] = addr.split(<span class="hljs-string">':'</span>)
    addr = { hostname, port: <span class="hljs-built_in">Number</span>(port) }
  }

  <span class="hljs-keyword">const</span> listener = listen(addr)
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Server(listener)
}
</code></pre>
<p>We proceed to instantiate a server calling the <code>serve()</code> function passing an object with the <code>port</code> property.</p>
<p>Then we run this loop to respond to every request coming from the server.</p>
<pre><code class="lang-ts"><span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> req <span class="hljs-keyword">of</span> s) {
  req.respond({ body: <span class="hljs-string">'Hello World\n'</span> })
}
</code></pre>
<p>Note that we use the <code>await</code> keyword without having to wrap it into an <code>async</code> function because Deno implements <a target="_blank" href="https://flaviocopes.com/javascript-await-top-level/">top-level await</a>.</p>
<p>Let’s run this program locally. I assume you use <a target="_blank" href="https://flaviocopes.com/vscode/">VS Code</a>, but you can use any editor you like.</p>
<p>I recommend installing the Deno extension from <code>justjavac</code> (there was another one with the same name when I tried, but deprecated - might disappear in the future)</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/Screen-Shot-2020-05-09-at-15.28.06.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The extension will provide several utilities and nice thing to VS Code to help you write your apps.</p>
<p>Now create an <code>app.ts</code> file in a folder and paste the above code:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/Screen-Shot-2020-05-09-at-15.40.18.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now run it using <code>deno run app.ts</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/Screen-Shot-2020-05-09-at-15.39.28.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Deno downloads all the dependencies it needs, by first downloading the one we imported.</p>
<p>The <a target="_blank" href="https://deno.land/std/http/server.ts">https://deno.land/std/http/server.ts</a> file has several dependencies on its own:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { encode } <span class="hljs-keyword">from</span> <span class="hljs-string">'../encoding/utf8.ts'</span>
<span class="hljs-keyword">import</span> { BufReader, BufWriter } <span class="hljs-keyword">from</span> <span class="hljs-string">'../io/bufio.ts'</span>
<span class="hljs-keyword">import</span> { assert } <span class="hljs-keyword">from</span> <span class="hljs-string">'../testing/asserts.ts'</span>
<span class="hljs-keyword">import</span> { deferred, Deferred, MuxAsyncIterator } <span class="hljs-keyword">from</span> <span class="hljs-string">'../async/mod.ts'</span>
<span class="hljs-keyword">import</span> {
  bodyReader,
  chunkedBodyReader,
  emptyReader,
  writeResponse,
  readRequest,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'./_io.ts'</span>
<span class="hljs-keyword">import</span> Listener = Deno.Listener
<span class="hljs-keyword">import</span> Conn = Deno.Conn
<span class="hljs-keyword">import</span> Reader = Deno.Reader
</code></pre>
<p>and those are imported automatically.</p>
<p>At the end though we have a problem:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/Screen-Shot-2020-05-09-at-15.42.05.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>What is happening? We have a permission denied problem.</p>
<p>Let’s talk about the sandbox.</p>
<h2 id="heading-the-deno-sandbox">The Deno sandbox</h2>
<p>I mentioned previously that Deno has a sandbox that prevents programs from doing anything you don’t want to allow.</p>
<p>What does this mean?</p>
<p>One of the things that Ryan mentions in the Deno introduction talk is that sometimes you want to run a JavaScript program outside of the Web Browser, and yet do not want allow it to access to anything it wants on your system. Or talk to the external world using a network.</p>
<p>There’s nothing stopping a Node.js app from getting your SSH keys or any other thing on your system and sending it to a server. This is why we usually only install Node packages from trusted sources. But how can we know if one of the projects we use gets hacked and in turn everyone else does?</p>
<p>Deno tries to replicate the same permission model that the browser implements. No JavaScript running in the browser can do shady things on your system unless you explicitly allow it.</p>
<p>Going back to Deno, if a program want to access the network like in the previous case, then we need to give it permission.</p>
<p>We can do so by passing a flag when we run the command, in this case <code>--allow-net</code>:</p>
<pre><code class="lang-sh">deno run --allow-net app.ts
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/Screen-Shot-2020-05-09-at-15.48.41.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The app is now running an HTTP server on port 8000:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/Screen-Shot-2020-05-09-at-15.49.02.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Other flags allow Deno to unlock other functionality:</p>
<ul>
<li><code>--allow-env</code> allow environment access</li>
<li><code>--allow-hrtime</code> allow high resolution time measurement</li>
<li><code>--allow-net=&lt;allow-net&gt;</code> allow network access</li>
<li><code>--allow-plugin</code> allow loading plugins</li>
<li><code>--allow-read=&lt;allow-read&gt;</code> allow file system read access</li>
<li><code>--allow-run</code> allow running subprocesses</li>
<li><code>--allow-write=&lt;allow-write&gt;</code> allow file system write access</li>
<li><code>--allow-all</code> allow all permissions (same as <code>-A</code>)</li>
</ul>
<p>Permissions for <code>net</code>, <code>read</code> and <code>write</code> can be granular. For example, you can allow reading from a specific folder using <code>--allow-read=/dev</code></p>
<h2 id="heading-formatting-code">Formatting code</h2>
<p>One of the things I really liked from Go was the <code>gofmt</code> command that came with the Go compiler. All Go code looks the same. Everyone uses <code>gofmt</code>.</p>
<p>JavaScript programmers are used to running <a target="_blank" href="https://flaviocopes.com/prettier/">Prettier</a>, and <code>deno fmt</code> actually runs that under the hood.</p>
<p>Say you have a file formatted badly like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/Screen-Shot-2020-05-09-at-16.06.58.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You run <code>deno fmt app.ts</code> and it’s automatically formatted properly, also adding semicolons where missing:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/Screen-Shot-2020-05-09-at-16.07.25.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-the-standard-library">The standard library</h2>
<p>The Deno standard library is extensive despite the project being very young.</p>
<p>It includes:</p>
<ul>
<li><code>archive</code> tar archive utilities</li>
<li><code>async</code> async utilties</li>
<li><code>bytes</code> helpers to manipulate bytes slices</li>
<li><code>datetime</code> date/time parsing</li>
<li><code>encoding</code> encoding/decoding for various formats</li>
<li><code>flags</code> parse command-line flags</li>
<li><code>fmt</code> formatting and printing</li>
<li><code>fs</code> file system API</li>
<li><code>hash</code> crypto lib</li>
<li><code>http</code> HTTP server</li>
<li><code>io</code> I/O lib</li>
<li><code>log</code> logging utilities</li>
<li><code>mime</code> support for multipart data</li>
<li><code>node</code> Node.js compatibility layer</li>
<li><code>path</code> path manipulation</li>
<li><code>ws</code> websockets</li>
</ul>
<h2 id="heading-another-deno-example">Another Deno example</h2>
<p>Let’s see another example of a Deno app, from the Deno examples: <a target="_blank" href="https://deno.land/std/examples/cat.ts"><code>cat</code></a>:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">const</span> filenames = Deno.args
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> filename <span class="hljs-keyword">of</span> filenames) {
  <span class="hljs-keyword">const</span> file = <span class="hljs-keyword">await</span> Deno.open(filename)
  <span class="hljs-keyword">await</span> Deno.copy(file, Deno.stdout)
  file.close()
}
</code></pre>
<p>This assigns to the <code>filenames</code> variable the content of <code>Deno.args</code>, which is a variable containing all the arguments sent to the command.</p>
<p>We iterate through them, and for each we use <code>Deno.open()</code> to open the file and we use <code>Deno.copy()</code> to print the content of the file to <code>Deno.stdout</code>. Finally we close the file.</p>
<p>If you run this using</p>
<pre><code class="lang-sh">deno run https://deno.land/std/examples/cat.ts
</code></pre>
<p>The program is downloaded and compiled, and nothing happens because we didn’t specify any argument.</p>
<p>Try now</p>
<pre><code class="lang-sh">deno run https://deno.land/std/examples/cat.ts app.ts
</code></pre>
<p>assuming you have <code>app.ts</code> from the previous project in the same folder.</p>
<p>You’ll get a permission error:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/Screen-Shot-2020-05-09-at-17.06.31-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Because Deno disallows access to the filesystem by default. Grant access to the current folder using <code>--allow-read=./</code>:</p>
<pre><code>deno run --allow-read=./ https:<span class="hljs-comment">//deno.land/std/examples/cat.ts app.ts</span>
</code></pre><p><img src="https://www.freecodecamp.org/news/content/images/2020/05/Screen-Shot-2020-05-09-at-17.07.54-6.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-is-there-an-expresshapikoa-for-deno">Is there an Express/Hapi/Koa/* for Deno?</h2>
<p>Yes, definitely. Check out projects like</p>
<ul>
<li><a target="_blank" href="https://github.com/drashland/deno-drash">deno-drash</a></li>
<li><a target="_blank" href="https://github.com/NMathar/deno-express">deno-express</a></li>
<li><a target="_blank" href="https://github.com/oakserver/oak">oak</a></li>
<li><a target="_blank" href="https://github.com/sholladay/pogo">pogo</a></li>
<li><a target="_blank" href="https://github.com/keroxp/servest">servest</a></li>
</ul>
<h2 id="heading-example-use-oak-to-build-a-rest-api">Example: use Oak to build a REST API</h2>
<p>I want to make a simple example of how to build a REST API using Oak. Oak is interesting because it’s inspired by <a target="_blank" href="https://github.com/koajs/koa">Koa</a>, the popular Node.js middleware, and due to this it’s very familiar if you’ve used that before.</p>
<p>The API we’re going to build is very simple.</p>
<p>Our server will store, in memory, a list of dogs with name and age.</p>
<p>We want to:</p>
<ul>
<li>add new dogs</li>
<li>list dogs</li>
<li>get details about a specific dog</li>
<li>remove a dog from the list</li>
<li>update a dog's age</li>
</ul>
<p>We’ll do this in TypeScript, but nothing stops you from writing the API in JavaScript - you simply remove the types.</p>
<p>Create a <code>app.ts</code> file.</p>
<p>Let’s start by importing the <code>Application</code> and <code>Router</code> objects from Oak:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { Application, Router } <span class="hljs-keyword">from</span> <span class="hljs-string">'https://deno.land/x/oak/mod.ts'</span>
</code></pre>
<p>then we get the environment variables PORT and HOST:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">const</span> env = Deno.env.toObject()
<span class="hljs-keyword">const</span> PORT = env.PORT || <span class="hljs-number">4000</span>
<span class="hljs-keyword">const</span> HOST = env.HOST || <span class="hljs-string">'127.0.0.1'</span>
</code></pre>
<p>By default our app will run on localhost:4000.</p>
<p>Now we create the Oak application and we start it:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">const</span> router = <span class="hljs-keyword">new</span> Router()

<span class="hljs-keyword">const</span> app = <span class="hljs-keyword">new</span> Application()

app.use(router.routes())
app.use(router.allowedMethods())

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Listening on port <span class="hljs-subst">${PORT}</span>...`</span>)

<span class="hljs-keyword">await</span> app.listen(<span class="hljs-string">`<span class="hljs-subst">${HOST}</span>:<span class="hljs-subst">${PORT}</span>`</span>)
</code></pre>
<p>Now the app should be compiling fine.</p>
<p>Run</p>
<pre><code class="lang-sh">deno run --allow-env --allow-net app.ts
</code></pre>
<p>and Deno will download the dependencies:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/Screen-Shot-2020-05-10-at-16.31.11.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>and then listen on port 4000.</p>
<p>The next times you run the command, Deno will skip the installation part because those packages are already cached:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/Screen-Shot-2020-05-10-at-16.32.40.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>At the top of the file, let’s define an interface for a dog, then we declare an initial <code>dogs</code> array of Dog objects:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">interface</span> Dog {
  name: <span class="hljs-built_in">string</span>
  age: <span class="hljs-built_in">number</span>
}

<span class="hljs-keyword">let</span> dogs: <span class="hljs-built_in">Array</span>&lt;Dog&gt; = [
  {
    name: <span class="hljs-string">'Roger'</span>,
    age: <span class="hljs-number">8</span>,
  },
  {
    name: <span class="hljs-string">'Syd'</span>,
    age: <span class="hljs-number">7</span>,
  },
]
</code></pre>
<p>Now let’s actually implement the API.</p>
<p>We have everything in place. After you create the router, let’s add some functions that will be invoked any time one of those endpoints is hit:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">const</span> router = <span class="hljs-keyword">new</span> Router()

router
  .get(<span class="hljs-string">'/dogs'</span>, getDogs)
  .get(<span class="hljs-string">'/dogs/:name'</span>, getDog)
  .post(<span class="hljs-string">'/dogs'</span>, addDog)
  .put(<span class="hljs-string">'/dogs/:name'</span>, updateDog)
  .delete(<span class="hljs-string">'/dogs/:name'</span>, removeDog)
</code></pre>
<p>See? We define</p>
<ul>
<li><code>GET /dogs</code></li>
<li><code>GET /dogs/:name</code></li>
<li><code>POST /dogs</code></li>
<li><code>PUT /dogs/:name</code></li>
<li><code>DELETE /dogs/:name</code></li>
</ul>
<p>Let’s implement those one-by-one.</p>
<p>Starting from <code>GET /dogs</code>, which returns the list of all the dogs:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> getDogs = <span class="hljs-function">(<span class="hljs-params">{ response }: { response: <span class="hljs-built_in">any</span> }</span>) =&gt;</span> {
  response.body = dogs
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/Screen-Shot-2020-05-10-at-16.47.53.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Next, here’s how we can retrieve a single dog by name:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> getDog = <span class="hljs-function">(<span class="hljs-params">{
  params,
  response,
}: {
  params: {
    name: <span class="hljs-built_in">string</span>
  }
  response: <span class="hljs-built_in">any</span>
}</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> dog = dogs.filter(<span class="hljs-function">(<span class="hljs-params">dog</span>) =&gt;</span> dog.name === params.name)
  <span class="hljs-keyword">if</span> (dog.length) {
    response.status = <span class="hljs-number">200</span>
    response.body = dog[<span class="hljs-number">0</span>]
    <span class="hljs-keyword">return</span>
  }

  response.status = <span class="hljs-number">400</span>
  response.body = { msg: <span class="hljs-string">`Cannot find dog <span class="hljs-subst">${params.name}</span>`</span> }
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/Screen-Shot-2020-05-10-at-16.48.02.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Here is how we add a new dog:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> addDog = <span class="hljs-keyword">async</span> ({
  request,
  response,
}: {
  request: <span class="hljs-built_in">any</span>
  response: <span class="hljs-built_in">any</span>
}) =&gt; {
  <span class="hljs-keyword">const</span> body = <span class="hljs-keyword">await</span> request.body()
  <span class="hljs-keyword">const</span> dog: Dog = body.value
  dogs.push(dog)

  response.body = { msg: <span class="hljs-string">'OK'</span> }
  response.status = <span class="hljs-number">200</span>
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/Screen-Shot-2020-05-10-at-16.47.41.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Notice that I now used <code>const body = await request.body()</code> to get the content of the body, since the <code>name</code> and <code>age</code> values are passed as JSON.</p>
<p>Here’s how we update a dog’s age:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> updateDog = <span class="hljs-keyword">async</span> ({
  params,
  request,
  response,
}: {
  params: {
    name: <span class="hljs-built_in">string</span>
  }
  request: <span class="hljs-built_in">any</span>
  response: <span class="hljs-built_in">any</span>
}) =&gt; {
  <span class="hljs-keyword">const</span> temp = dogs.filter(<span class="hljs-function">(<span class="hljs-params">existingDog</span>) =&gt;</span> existingDog.name === params.name)
  <span class="hljs-keyword">const</span> body = <span class="hljs-keyword">await</span> request.body()
  <span class="hljs-keyword">const</span> { age }: { age: <span class="hljs-built_in">number</span> } = body.value

  <span class="hljs-keyword">if</span> (temp.length) {
    temp[<span class="hljs-number">0</span>].age = age
    response.status = <span class="hljs-number">200</span>
    response.body = { msg: <span class="hljs-string">'OK'</span> }
    <span class="hljs-keyword">return</span>
  }

  response.status = <span class="hljs-number">400</span>
  response.body = { msg: <span class="hljs-string">`Cannot find dog <span class="hljs-subst">${params.name}</span>`</span> }
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/Screen-Shot-2020-05-10-at-16.48.11.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>and here is how we can remove a dog from our list:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> removeDog = <span class="hljs-function">(<span class="hljs-params">{
  params,
  response,
}: {
  params: {
    name: <span class="hljs-built_in">string</span>
  }
  response: <span class="hljs-built_in">any</span>
}</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> lengthBefore = dogs.length
  dogs = dogs.filter(<span class="hljs-function">(<span class="hljs-params">dog</span>) =&gt;</span> dog.name !== params.name)

  <span class="hljs-keyword">if</span> (dogs.length === lengthBefore) {
    response.status = <span class="hljs-number">400</span>
    response.body = { msg: <span class="hljs-string">`Cannot find dog <span class="hljs-subst">${params.name}</span>`</span> }
    <span class="hljs-keyword">return</span>
  }

  response.body = { msg: <span class="hljs-string">'OK'</span> }
  response.status = <span class="hljs-number">200</span>
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/Screen-Shot-2020-05-10-at-16.48.32.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Here’s the complete example code:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { Application, Router } <span class="hljs-keyword">from</span> <span class="hljs-string">'https://deno.land/x/oak/mod.ts'</span>

<span class="hljs-keyword">const</span> env = Deno.env.toObject()
<span class="hljs-keyword">const</span> PORT = env.PORT || <span class="hljs-number">4000</span>
<span class="hljs-keyword">const</span> HOST = env.HOST || <span class="hljs-string">'127.0.0.1'</span>

<span class="hljs-keyword">interface</span> Dog {
  name: <span class="hljs-built_in">string</span>
  age: <span class="hljs-built_in">number</span>
}

<span class="hljs-keyword">let</span> dogs: <span class="hljs-built_in">Array</span>&lt;Dog&gt; = [
  {
    name: <span class="hljs-string">'Roger'</span>,
    age: <span class="hljs-number">8</span>,
  },
  {
    name: <span class="hljs-string">'Syd'</span>,
    age: <span class="hljs-number">7</span>,
  },
]

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> getDogs = <span class="hljs-function">(<span class="hljs-params">{ response }: { response: <span class="hljs-built_in">any</span> }</span>) =&gt;</span> {
  response.body = dogs
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> getDog = <span class="hljs-function">(<span class="hljs-params">{
  params,
  response,
}: {
  params: {
    name: <span class="hljs-built_in">string</span>
  }
  response: <span class="hljs-built_in">any</span>
}</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> dog = dogs.filter(<span class="hljs-function">(<span class="hljs-params">dog</span>) =&gt;</span> dog.name === params.name)
  <span class="hljs-keyword">if</span> (dog.length) {
    response.status = <span class="hljs-number">200</span>
    response.body = dog[<span class="hljs-number">0</span>]
    <span class="hljs-keyword">return</span>
  }

  response.status = <span class="hljs-number">400</span>
  response.body = { msg: <span class="hljs-string">`Cannot find dog <span class="hljs-subst">${params.name}</span>`</span> }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> addDog = <span class="hljs-keyword">async</span> ({
  request,
  response,
}: {
  request: <span class="hljs-built_in">any</span>
  response: <span class="hljs-built_in">any</span>
}) =&gt; {
  <span class="hljs-keyword">const</span> body = <span class="hljs-keyword">await</span> request.body()
  <span class="hljs-keyword">const</span> { name, age }: { name: <span class="hljs-built_in">string</span>; age: <span class="hljs-built_in">number</span> } = body.value
  dogs.push({
    name: name,
    age: age,
  })

  response.body = { msg: <span class="hljs-string">'OK'</span> }
  response.status = <span class="hljs-number">200</span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> updateDog = <span class="hljs-keyword">async</span> ({
  params,
  request,
  response,
}: {
  params: {
    name: <span class="hljs-built_in">string</span>
  }
  request: <span class="hljs-built_in">any</span>
  response: <span class="hljs-built_in">any</span>
}) =&gt; {
  <span class="hljs-keyword">const</span> temp = dogs.filter(<span class="hljs-function">(<span class="hljs-params">existingDog</span>) =&gt;</span> existingDog.name === params.name)
  <span class="hljs-keyword">const</span> body = <span class="hljs-keyword">await</span> request.body()
  <span class="hljs-keyword">const</span> { age }: { age: <span class="hljs-built_in">number</span> } = body.value

  <span class="hljs-keyword">if</span> (temp.length) {
    temp[<span class="hljs-number">0</span>].age = age
    response.status = <span class="hljs-number">200</span>
    response.body = { msg: <span class="hljs-string">'OK'</span> }
    <span class="hljs-keyword">return</span>
  }

  response.status = <span class="hljs-number">400</span>
  response.body = { msg: <span class="hljs-string">`Cannot find dog <span class="hljs-subst">${params.name}</span>`</span> }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> removeDog = <span class="hljs-function">(<span class="hljs-params">{
  params,
  response,
}: {
  params: {
    name: <span class="hljs-built_in">string</span>
  }
  response: <span class="hljs-built_in">any</span>
}</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> lengthBefore = dogs.length
  dogs = dogs.filter(<span class="hljs-function">(<span class="hljs-params">dog</span>) =&gt;</span> dog.name !== params.name)

  <span class="hljs-keyword">if</span> (dogs.length === lengthBefore) {
    response.status = <span class="hljs-number">400</span>
    response.body = { msg: <span class="hljs-string">`Cannot find dog <span class="hljs-subst">${params.name}</span>`</span> }
    <span class="hljs-keyword">return</span>
  }

  response.body = { msg: <span class="hljs-string">'OK'</span> }
  response.status = <span class="hljs-number">200</span>
}

<span class="hljs-keyword">const</span> router = <span class="hljs-keyword">new</span> Router()
router
  .get(<span class="hljs-string">'/dogs'</span>, getDogs)
  .get(<span class="hljs-string">'/dogs/:name'</span>, getDog)
  .post(<span class="hljs-string">'/dogs'</span>, addDog)
  .put(<span class="hljs-string">'/dogs/:name'</span>, updateDog)
  .delete(<span class="hljs-string">'/dogs/:name'</span>, removeDog)

<span class="hljs-keyword">const</span> app = <span class="hljs-keyword">new</span> Application()

app.use(router.routes())
app.use(router.allowedMethods())

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Listening on port <span class="hljs-subst">${PORT}</span>...`</span>)

<span class="hljs-keyword">await</span> app.listen(<span class="hljs-string">`<span class="hljs-subst">${HOST}</span>:<span class="hljs-subst">${PORT}</span>`</span>)
</code></pre>
<h2 id="heading-find-out-more">Find out more</h2>
<p>The Deno official website is <a target="_blank" href="https://deno.land/">https://deno.land</a></p>
<p>The API documentation is available at <a target="_blank" href="https://doc.deno.land/">https://doc.deno.land</a> and <a target="_blank" href="https://deno.land/typedoc/index.html">https://deno.land/typedoc/index.html</a></p>
<p>awesome-deno <a target="_blank" href="https://github.com/denolib/awesome-deno">https://github.com/denolib/awesome-deno</a></p>
<h2 id="heading-a-few-more-random-tidbits">A few more random tidbits</h2>
<ul>
<li>Deno provides a built-in <code>fetch</code> implementation that matches the one available in the browser</li>
<li>Deno has a compatibility layer with the Node.js stdlib <a target="_blank" href="https://github.com/denoland/deno/tree/master/std/node">in progress</a></li>
</ul>
<h2 id="heading-final-words">Final words</h2>
<p>I hope you enjoyed this Deno tutorial!</p>
<p>Reminder: <a target="_blank" href="https://flaviocopes.com/page/deno-handbook/">You can get a PDF/ePub/Mobi version of this Deno Handbook here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The C Beginner's Handbook: Learn C Programming Language basics in just a few hours ]]>
                </title>
                <description>
                    <![CDATA[ This C Beginner's Handbook follows the 80/20 rule. You'll learn 80% of the C programming language in 20% of the time. This approach will give you a well-rounded overview of the language. This handbook does not try to cover everything under the sun re... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-c-beginners-handbook/</link>
                <guid isPermaLink="false">66bb5a94b6e566d0c2aea60b</guid>
                
                    <category>
                        <![CDATA[ c programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Flavio Copes ]]>
                </dc:creator>
                <pubDate>Mon, 09 Mar 2020 11:50:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/06/coverc-1-opt.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>This C Beginner's Handbook follows the 80/20 rule. You'll learn 80% of the C programming language in 20% of the time.</p>
<p>This approach will give you a well-rounded overview of the language.</p>
<p>This handbook does not try to cover everything under the sun related to C. It focuses on the core of the language, trying to simplify the more complex topics.</p>
<p>And note: <a target="_blank" href="https://flaviocopes.com/page/c-handbook/">You can get a PDF and ePub version of this C Beginner's Handbook here</a>.</p>
<p>Enjoy!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-introduction-to-c">Introduction to C</a></li>
<li><a class="post-section-overview" href="#heading-variables-and-types">Variables and types</a></li>
<li><a class="post-section-overview" href="#heading-constants">Constants</a></li>
<li><a class="post-section-overview" href="#heading-operators">Operators</a></li>
<li><a class="post-section-overview" href="#heading-conditionals">Conditionals</a></li>
<li><a class="post-section-overview" href="#heading-loops">Loops</a></li>
<li><a class="post-section-overview" href="#heading-arrays">Arrays</a></li>
<li><a class="post-section-overview" href="#heading-strings">Strings</a></li>
<li><a class="post-section-overview" href="#heading-pointers">Pointers</a></li>
<li><a class="post-section-overview" href="#heading-functions">Functions</a></li>
<li><a class="post-section-overview" href="#heading-input-and-output">Input and output</a></li>
<li><a class="post-section-overview" href="#variables-scope">Variables scope</a></li>
<li><a class="post-section-overview" href="#heading-static-variables">Static variables</a></li>
<li><a class="post-section-overview" href="#heading-global-variables">Global variables</a></li>
<li><a class="post-section-overview" href="#heading-type-definitions">Type definitions</a></li>
<li><a class="post-section-overview" href="#heading-enumerated-types">Enumerated Types</a></li>
<li><a class="post-section-overview" href="#heading-structures">Structures</a></li>
<li><a class="post-section-overview" href="#heading-command-line-parameters">Command line parameters</a></li>
<li><a class="post-section-overview" href="#header-files">Header files</a></li>
<li><a class="post-section-overview" href="#heading-the-preprocessor">The preprocessor</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<h2 id="heading-introduction-to-c">Introduction to C</h2>
<p>C is probably the most widely known programming language. It is used as the reference language for computer science courses all over the world, and it's probably the language that people learn the most in school along with Python and Java.</p>
<p>I remember it being my second programming language ever, after Pascal.</p>
<p>C is not just what students use to learn programming. It's not an academic language. And I would say it's not the easiest language, because C is a rather low level programming language.</p>
<p>Today, C is widely used in embedded devices, and it powers most of the Internet servers, which are built using Linux. The Linux kernel is built using C, and this also means that C powers the core of all Android devices. We can say that C code runs a good portion of the entire world. Right now. Pretty remarkable.</p>
<p>When it was created, C was considered a high level language, because it was portable across machines. Today we kind of take for granted that we can run a program written on a Mac on Windows or Linux, perhaps using Node.js or Python. </p>
<p>Once upon a time, this was not the case at all. What C brought to the table was a language that was simple to implement and that had a compiler that could be easily ported to different machines.</p>
<p>I said compiler: C is a compiled programming language, like Go, Java, Swift or Rust. Other popular programming language like Python, Ruby or JavaScript are interpreted. The difference is consistent: a compiled language generates a binary file that can be directly executed and distributed.</p>
<p>C is not garbage collected. This means we have to manage memory ourselves. It's a complex task and one that requires a lot of attention to prevent bugs, but it is also what makes C ideal to write programs for embedded devices like Arduino.</p>
<p>C does not hide the complexity and the capabilities of the machine underneath. You have a lot of power, once you know what you can do.</p>
<p>I want to introduce the first C program now, which we'll call "Hello, World!"</p>
<p>hello.c</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Hello, World!"</span>);
}
</code></pre>
<p>Let's describe the program source code: we first import the <code>stdio</code> library (the name stands for standard input-output library).</p>
<p>This library gives us access to input/output functions.</p>
<p>C is a very small language at its core, and anything that's not part of the core is provided by libraries. Some of those libraries are built by normal programmers, and made available for others to use. Some other libraries are built into the compiler. Like <code>stdio</code> and others.</p>
<p><code>stdio</code> is the library that provides the <code>printf()</code> function.</p>
<p>This function is wrapped into a <code>main()</code> function. The <code>main()</code> function is the entry point of any C program.</p>
<p>But what is a function, anyway?</p>
<p>A function is a routine that takes one or more arguments, and returns a single value.</p>
<p>In the case of <code>main()</code>, the function gets no arguments, and returns an integer. We identify that using the <code>void</code> keyword for the argument, and the <code>int</code> keyword for the return value.</p>
<p>The function has a body, which is wrapped in curly braces. Inside the body we have all the code that the function needs to perform its operations.</p>
<p>The <code>printf()</code> function is written differently, as you can see. It has no return value defined, and we pass a string, wrapped in double quotes. We didn't specify the type of the argument.</p>
<p>That's because this is a function invocation. Somewhere, inside the <code>stdio</code> library, <code>printf</code> is defined as</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">printf</span><span class="hljs-params">(<span class="hljs-keyword">const</span> <span class="hljs-keyword">char</span> *format, ...)</span></span>;
</code></pre>
<p>You don't need to understand what this means now, but in short, this is the definition. And when we call <code>printf("Hello, World!");</code>, that's where the function is run.</p>
<p>The <code>main()</code> function we defined above:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Hello, World!"</span>);
}
</code></pre>
<p>will be run by the operating system when the program is executed.</p>
<p>How do we execute a C program?</p>
<p>As mentioned, C is a compiled language. To run the program we must first compile it. Any Linux or macOS computer already comes with a C compiler built-in. For Windows, you can use the Windows Subsystem for Linux (WSL).</p>
<p>In any case, when you open the terminal window you can type <code>gcc</code>, and this command should return an error saying that you didn't specify any file:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Screen-Shot-2020-01-29-at-10.10.50.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>That's good. It means the C compiler is there, and we can start using it.</p>
<p>Now type the program above into a <code>hello.c</code> file. You can use any editor, but for the sake of simplicity I'm going to use the <code>nano</code> editor in the command line:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Screen-Shot-2020-01-29-at-10.11.39.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Type the program:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Screen-Shot-2020-01-29-at-10.16.52.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now press <code>ctrl-X</code> to exit: </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Screen-Shot-2020-01-29-at-10.18.11.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Confirm by pressing the <code>y</code> key, then press enter to confirm the file name:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Screen-Shot-2020-01-29-at-10.18.15.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>That's it, we should be back to the terminal now: </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Screen-Shot-2020-01-29-at-10.13.46.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now type</p>
<pre><code class="lang-sh">gcc hello.c -o hello
</code></pre>
<p>The program should give you no errors:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Screen-Shot-2020-01-29-at-10.16.31.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>but it should have generated a <code>hello</code> executable. Now type</p>
<pre><code class="lang-sh">./hello
</code></pre>
<p>to run it:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Screen-Shot-2020-01-29-at-10.19.20.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>I prepend <code>./</code> to the program name to tell the terminal that the command is in the current folder</p>
<p>Awesome!</p>
<p>Now if you call <code>ls -al hello</code>, you can see that the program is only 12KB in size:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Screen-Shot-2020-01-29-at-10.19.55.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This is one of the pros of C: it's highly optimized, and this is also one of the reasons it's this good for embedded devices that have a very limited amount of resources.</p>
<h2 id="heading-variables-and-types">Variables and types</h2>
<p>C is a statically typed language.</p>
<p>This means that any variable has an associated type, and this type is known at compilation time.</p>
<p>This is very different than how you work with variables in Python, JavaScript, PHP and other interpreted languages.</p>
<p>When you create a variable in C, you have to specify the type of a variable at the declaration.</p>
<p>In this example we initialize a variable <code>age</code> with type <code>int</code>:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> age;
</code></pre>
<p>A variable name can contain any uppercase or lowercase letter, can contain digits and the underscore character, but it can't start with a  digit. <code>AGE</code> and <code>Age10</code> are valid variable names, <code>1age</code> is not.</p>
<p>You can also initialize a variable at declaration, specifying the initial value:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> age = <span class="hljs-number">37</span>;
</code></pre>
<p>Once you declare a variable, you are then able to use it in your program code. You can change its value at any time, using the <code>=</code> operator for example, like in <code>age = 100;</code> (provided the new value is of the same type).</p>
<p>In this case:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
    <span class="hljs-keyword">int</span> age = <span class="hljs-number">0</span>;
    age = <span class="hljs-number">37.2</span>;
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%u"</span>, age);
}
</code></pre>
<p>the compiler will raise a warning at compile time, and will convert the decimal number to an integer value.</p>
<p>The C built-in data types are <code>int</code>, <code>char</code>, <code>short</code>, <code>long</code>, <code>float</code>, <code>double</code>, <code>long double</code>. Let's find out more about those.</p>
<h3 id="heading-integer-numbers">Integer numbers</h3>
<p>C provides us the following types to define integer values:</p>
<ul>
<li><code>char</code></li>
<li><code>int</code></li>
<li><code>short</code></li>
<li><code>long</code></li>
</ul>
<p>Most of the time, you'll likely use an <code>int</code> to store an integer. But in some cases, you might want to choose one of the other 3 options.</p>
<p>The <code>char</code> type is commonly used to store letters of the ASCII chart, but it can be used to hold small integers from <code>-128</code> to <code>127</code>. It takes at least 1 byte.</p>
<p><code>int</code> takes at least 2 bytes. <code>short</code> takes at least 2 bytes. <code>long</code> takes at least 4 bytes.</p>
<p>As you can see, we are not guaranteed the same values for different environments. We only have an indication. The problem is that the exact numbers that can be stored in each data type depends on the implementation and the architecture.</p>
<p>We're guaranteed that <code>short</code> is not longer than <code>int</code>. And we're guaranteed <code>long</code> is not shorter than <code>int</code>.</p>
<p>The ANSI C spec standard determines the minimum values of each type, and thanks to it we can at least know what's the minimum value we can expect to have at our disposal.</p>
<p>If you are programming C on an Arduino, different board will have different limits.</p>
<p>On an Arduino Uno board, <code>int</code> stores a 2 byte value, ranging from <code>-32,768</code> to <code>32,767</code>. On a Arduino MKR 1010, <code>int</code> stores a 4 bytes value, ranging from <code>-2,147,483,648</code> to <code>2,147,483,647</code>. Quite a big difference.</p>
<p>On all Arduino boards, <code>short</code> stores a 2 bytes value, ranging from <code>-32,768</code> to <code>32,767</code>. <code>long</code> store 4 bytes, ranging from <code>-2,147,483,648</code> to <code>2,147,483,647</code>.</p>
<h3 id="heading-unsigned-integers">Unsigned integers</h3>
<p>For all the above data types, we can prepend <code>unsigned</code> to start the range at 0, instead of a negative number. This might make sense in many cases.</p>
<ul>
<li><code>unsigned char</code> will range from <code>0</code> to at least <code>255</code></li>
<li><code>unsigned int</code> will range from <code>0</code> to at least <code>65,535</code></li>
<li><code>unsigned short</code> will range from <code>0</code> to at least <code>65,535</code></li>
<li><code>unsigned long</code> will range from <code>0</code> to at least <code>4,294,967,295</code></li>
</ul>
<h3 id="heading-the-problem-with-overflow">The problem with overflow</h3>
<p>Given all those limits, a question might come up: how can we make sure our numbers do not exceed the limit? And what happens if we do exceed the limit?</p>
<p>If you have an <code>unsigned int</code> number at 255, and you increment it, you'll get 256 in return. As expected. If you have an <code>unsigned char</code> number at 255, and you increment it, you'll get 0 in return. It resets starting from the initial possible value.</p>
<p>If you have a <code>unsigned char</code> number at 255 and you add 10 to it, you'll get the number <code>9</code>:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
  <span class="hljs-keyword">unsigned</span> <span class="hljs-keyword">char</span> j = <span class="hljs-number">255</span>;
  j = j + <span class="hljs-number">10</span>;
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%u"</span>, j); <span class="hljs-comment">/* 9 */</span>
}
</code></pre>
<p>If you don't have a signed value, the behavior is undefined. It will basically give you a huge number which can vary, like in this case:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
  <span class="hljs-keyword">char</span> j = <span class="hljs-number">127</span>;
  j = j + <span class="hljs-number">10</span>;
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%u"</span>, j); <span class="hljs-comment">/* 4294967177 */</span>
}
</code></pre>
<p>In other words, C does not protect you from going over the limits of a type. You need to take care of this yourself.</p>
<h3 id="heading-warnings-when-declaring-the-wrong-type">Warnings when declaring the wrong type</h3>
<p>When you declare the variable and initialize it with the wrong value, the <code>gcc</code> compiler (the one you're probably using) should warn you:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
  <span class="hljs-keyword">char</span> j = <span class="hljs-number">1000</span>;
}
</code></pre>
<pre><code>hello.c:<span class="hljs-number">4</span>:<span class="hljs-number">11</span>: warning: implicit conversion 
  <span class="hljs-keyword">from</span> <span class="hljs-string">'int'</span> to
      <span class="hljs-string">'char'</span> changes value <span class="hljs-keyword">from</span> <span class="hljs-number">1000</span> to <span class="hljs-number">-24</span>
      [-Wconstant-conversion]
        char j = <span class="hljs-number">1000</span>;
             ~   ^~~~
<span class="hljs-number">1</span> warning generated.
</code></pre><p>And it also warns you in direct assignments:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
  <span class="hljs-keyword">char</span> j;
  j = <span class="hljs-number">1000</span>;
}
</code></pre>
<p>But not if you increase the number using, for example, <code>+=</code>:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
  <span class="hljs-keyword">char</span> j = <span class="hljs-number">0</span>;
  j += <span class="hljs-number">1000</span>;
}
</code></pre>
<h3 id="heading-floating-point-numbers">Floating point numbers</h3>
<p>Floating point types can represent a much larger set of values than integers can, and can also represent fractions, something that integers can't do.</p>
<p>Using floating point numbers, we represent numbers as decimal numbers times powers of 10.</p>
<p>You might see floating point numbers written as</p>
<ul>
<li><code>1.29e-3</code></li>
<li><code>-2.3e+5</code></li>
</ul>
<p>and in other seemingly weird ways.</p>
<p>The following types:</p>
<ul>
<li><code>float</code></li>
<li><code>double</code></li>
<li><code>long double</code></li>
</ul>
<p>are used to represent numbers with decimal points (floating point types). All can represent both positive and negative numbers.</p>
<p>The minimum requirements for any C implementation is that <code>float</code> can represent a range between 10^-37 and 10^+37, and is typically implemented using 32 bits. <code>double</code> can represent a bigger set of numbers. <code>long double</code> can hold even more numbers.</p>
<p>The exact figures, as with integer values, depend on the implementation.</p>
<p>On a modern Mac, a <code>float</code> is represented in 32 bits, and has a precision of 24 significant bits. 8 bits are used to encode the exponent. </p>
<p>A <code>double</code> number is represented in 64 bits, with a precision of 53 significant bits. 11 bits are used to encode the exponent. </p>
<p>The type <code>long double</code> is represented in 80 bits, has a precision of 64 significant bits. 15 bits are used to encode the exponent.</p>
<p>On your specific computer, how can you determine the specific size of the types? You can write a program to do that:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"char size: %lu bytes\n"</span>, <span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">char</span>));
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"int size: %lu bytes\n"</span>, <span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">int</span>));
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"short size: %lu bytes\n"</span>, <span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">short</span>));
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"long size: %lu bytes\n"</span>, <span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">long</span>));
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"float size: %lu bytes\n"</span>, <span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">float</span>));
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"double size: %lu bytes\n"</span>, 
    <span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">double</span>));
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"long double size: %lu bytes\n"</span>, 
    <span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">long</span> <span class="hljs-keyword">double</span>));
}
</code></pre>
<p>In my system, a modern Mac, it prints:</p>
<pre><code>char size: <span class="hljs-number">1</span> bytes
int size: <span class="hljs-number">4</span> bytes
short size: <span class="hljs-number">2</span> bytes
long size: <span class="hljs-number">8</span> bytes
float size: <span class="hljs-number">4</span> bytes
double size: <span class="hljs-number">8</span> bytes
long double size: <span class="hljs-number">16</span> bytes
</code></pre><h2 id="heading-constants">Constants</h2>
<p>Let's now talk about constants.</p>
<p>A constant is declared similarly to variables, except it is prepended with the <code>const</code> keyword, and you always need to specify a value.</p>
<p>Like this:</p>
<pre><code class="lang-c"><span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> age = <span class="hljs-number">37</span>;
</code></pre>
<p>This is perfectly valid C, although it is common to declare constants uppercase, like this:</p>
<pre><code class="lang-c"><span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> AGE = <span class="hljs-number">37</span>;
</code></pre>
<p>It's just a convention, but one that can greatly help you while reading or writing a C program as it improves readability. Uppercase name means constant, lowercase name means variable.</p>
<p>A constant name follows the same rules for variable names: can contain any uppercase or lowercase letter, can contain digits and the underscore character, but it can't start with a digit. <code>AGE</code> and <code>Age10</code> are valid variable names, <code>1AGE</code> is not.</p>
<p>Another way to define constants is by using this syntax:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> AGE 37</span>
</code></pre>
<p>In this case, you don't need to add a type, and you don't also need the <code>=</code> equal sign, and you omit the semicolon at the end.</p>
<p>The C compiler will infer the type from the value specified, at compile time.</p>
<h2 id="heading-operators">Operators</h2>
<p>C offers us a wide variety of operators that we can use to operate on data.</p>
<p>In particular, we can identify various groups of operators:</p>
<ul>
<li>arithmetic operators</li>
<li>comparison operators</li>
<li>logical operators</li>
<li>compound assignment operators</li>
<li>bitwise operators</li>
<li>pointer operators</li>
<li>structure operators</li>
<li>miscellaneous operators</li>
</ul>
<p>In this section I'm going to detail all of them, using 2 imaginary variables <code>a</code> and <code>b</code> as examples.</p>
<p>I am keeping bitwise operators, structure operators and pointer operators out of this list, to keep things simpler</p>
<h3 id="heading-arithmetic-operators">Arithmetic operators</h3>
<p>In this macro group I am going to separate binary operators and unary operators.</p>
<p>Binary operators work using two operands:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Operator</td><td>Name</td><td>Example</td></tr>
</thead>
<tbody>
<tr>
<td><code>=</code></td><td>Assignment</td><td><code>a = b</code></td></tr>
<tr>
<td><code>+</code></td><td>Addition</td><td><code>a + b</code></td></tr>
<tr>
<td><code>-</code></td><td>Subtraction</td><td><code>a - b</code></td></tr>
<tr>
<td><code>*</code></td><td>Multiplication</td><td><code>a * b</code></td></tr>
<tr>
<td><code>/</code></td><td>Division</td><td><code>a / b</code></td></tr>
<tr>
<td><code>%</code></td><td>Modulo</td><td><code>a % b</code></td></tr>
</tbody>
</table>
</div><p>Unary operators only take one operand:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Operator</td><td>Name</td><td>Example</td></tr>
</thead>
<tbody>
<tr>
<td><code>+</code></td><td>Unary plus</td><td><code>+a</code></td></tr>
<tr>
<td><code>-</code></td><td>Unary minus</td><td><code>-a</code></td></tr>
<tr>
<td><code>++</code></td><td>Increment</td><td><code>a++</code> or <code>++a</code></td></tr>
<tr>
<td><code>--</code></td><td>Decrement</td><td><code>a--</code> or <code>--a</code></td></tr>
</tbody>
</table>
</div><p>The difference between <code>a++</code> and <code>++a</code> is that <code>a++</code> increments the <code>a</code> variable after using it. <code>++a</code> increments the <code>a</code> variable before using it.</p>
<p>For example:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> a = <span class="hljs-number">2</span>;
<span class="hljs-keyword">int</span> b;
b = a++ <span class="hljs-comment">/* b is 2, a is 3 */</span>
b = ++a <span class="hljs-comment">/* b is 4, a is 4 */</span>
</code></pre>
<p>The same applies to the decrement operator.</p>
<h3 id="heading-comparison-operators">Comparison operators</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Operator</td><td>Name</td><td>Example</td></tr>
</thead>
<tbody>
<tr>
<td><code>==</code></td><td>Equal operator</td><td><code>a == b</code></td></tr>
<tr>
<td><code>!=</code></td><td>Not equal operator</td><td><code>a != b</code></td></tr>
<tr>
<td><code>&gt;</code></td><td>Bigger than</td><td><code>a &gt; b</code></td></tr>
<tr>
<td><code>&lt;</code></td><td>Less than</td><td><code>a &lt; b</code></td></tr>
<tr>
<td><code>&gt;=</code></td><td>Bigger than or equal to</td><td><code>a &gt;= b</code></td></tr>
<tr>
<td><code>&lt;=</code></td><td>Less than or equal to</td><td><code>a &lt;= b</code></td></tr>
</tbody>
</table>
</div><h3 id="heading-logical-operators">Logical operators</h3>
<ul>
<li><code>!</code> NOT (example: <code>!a</code>)</li>
<li><code>&amp;&amp;</code> AND (example: <code>a &amp;&amp; b</code>)</li>
<li><code>||</code> OR (example: <code>a || b</code>)</li>
</ul>
<p>Those operators are great when working with boolean values.</p>
<h3 id="heading-compound-assignment-operators">Compound assignment operators</h3>
<p>Those operators are useful to perform an assignment and at the same time perform an arithmetic operation:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Operator</td><td>Name</td><td>Example</td></tr>
</thead>
<tbody>
<tr>
<td><code>+=</code></td><td>Addition assignment</td><td><code>a += b</code></td></tr>
<tr>
<td><code>-=</code></td><td>Subtraction assignment</td><td><code>a -= b</code></td></tr>
<tr>
<td><code>*=</code></td><td>Multiplication assignment</td><td><code>a *= b</code></td></tr>
<tr>
<td><code>/=</code></td><td>Division assignment</td><td><code>a /= b</code></td></tr>
<tr>
<td><code>%=</code></td><td>Modulo assignment</td><td><code>a %= b</code></td></tr>
</tbody>
</table>
</div><h3 id="heading-the-ternary-operator">The ternary operator</h3>
<p>The ternary operator is the only operator in C that works with 3 operands, and it’s a short way to express conditionals.</p>
<p>This is how it looks:</p>
<pre><code class="lang-c">&lt;condition&gt; ? &lt;expression&gt; : &lt;expression&gt;
</code></pre>
<p>Example:</p>
<pre><code class="lang-c">a ? b : c
</code></pre>
<p>If <code>a</code> is evaluated to <code>true</code>, then the <code>b</code> statement is executed, otherwise <code>c</code> is.</p>
<p>The ternary operator is functionality-wise same as an if/else conditional, except it is shorter to express and it can be inlined into an expression.</p>
<h3 id="heading-sizeof">sizeof</h3>
<p>The <code>sizeof</code> operator returns the size of the operand you pass. You can pass a variable, or even a type.</p>
<p>Example usage:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
  <span class="hljs-keyword">int</span> age = <span class="hljs-number">37</span>;
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%ld\n"</span>, <span class="hljs-keyword">sizeof</span>(age));
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%ld"</span>, <span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">int</span>));
}
</code></pre>
<h3 id="heading-operator-precedence">Operator precedence</h3>
<p>With all those operators (and more, which I haven't covered in this post, including bitwise, structure operators, and pointer operators), we must pay attention when using them together in a single expression.</p>
<p>Suppose we have this operation:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> a = <span class="hljs-number">2</span>;
<span class="hljs-keyword">int</span> b = <span class="hljs-number">4</span>;
<span class="hljs-keyword">int</span> c = b + a * a / b - a;
</code></pre>
<p>What's the value of <code>c</code>? Do we get the addition being executed before the multiplication and the division?</p>
<p>There is a set of rules that help us solve this puzzle.</p>
<p>In order from less precedence to more precedence, we have:</p>
<ul>
<li>the <code>=</code> assignment operator</li>
<li>the <code>+</code> and <code>-</code> <strong>binary</strong> operators</li>
<li>the <code>*</code> and <code>/</code> operators</li>
<li>the <code>+</code> and <code>-</code> unary operators</li>
</ul>
<p>Operators also have an associativity rule, which is always left to right except for the unary operators and the assignment.</p>
<p>In:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> c = b + a * a / b - a;
</code></pre>
<p>We first execute <code>a * a / b</code>, which, due to being left-to-right, we can separate into <code>a * a</code> and the result <code>/ b</code>: <code>2 * 2 = 4</code>, <code>4 / 4 = 1</code>.</p>
<p>Then we can perform the sum and the subtraction: 4 + 1 - 2. The value of <code>c</code> is <code>3</code>.</p>
<p>In all cases, however, I want to make sure you realize you can use parentheses to make any similar expression easier to read and comprehend.</p>
<p>Parentheses have higher priority over anything else.</p>
<p>The above example expression can be rewritten as:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> c = b + ((a * a) / b) - a;
</code></pre>
<p>and we don't have to think about it that much.</p>
<h2 id="heading-conditionals">Conditionals</h2>
<p>Any programming language provides the programmers the ability to perform choices.</p>
<p>We want to do X in some cases, and Y in other cases.</p>
<p>We want to check data, and make choices based on the state of that data.</p>
<p>C provides us 2 ways to do so.</p>
<p>The first is the <code>if</code> statement, with its <code>else</code> helper, and the second is the <code>switch</code> statement.</p>
<h3 id="heading-if">if</h3>
<p>In an <code>if</code> statement, you can check for a condition to be true, and then execute the block provided in the curly brackets:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> a = <span class="hljs-number">1</span>;

<span class="hljs-keyword">if</span> (a == <span class="hljs-number">1</span>) {
  <span class="hljs-comment">/* do something */</span>
}
</code></pre>
<p>You can append an <code>else</code> block to execute a different block if the original condition turns out to be false:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> a = <span class="hljs-number">1</span>;

<span class="hljs-keyword">if</span> (a == <span class="hljs-number">2</span>) {
  <span class="hljs-comment">/* do something */</span>
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">/* do something else */</span>
}
</code></pre>
<p>Beware of one common source of bugs - always use the comparison operator <code>==</code> in comparisons, and not the assignment operator <code>=</code>. If you don't, the <code>if</code> conditional check will always be true, unless the argument is <code>0</code>, for example if you do:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> a = <span class="hljs-number">0</span>;

<span class="hljs-keyword">if</span> (a = <span class="hljs-number">0</span>) {
  <span class="hljs-comment">/* never invoked */</span>
}
</code></pre>
<p>Why does this happen? Because the conditional check will look for a boolean result (the result of a comparison), and the <code>0</code> number always equates to a false value. Everything else is true, including negative numbers.</p>
<p>You can have multiple <code>else</code> blocks by stacking together multiple <code>if</code> statements:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> a = <span class="hljs-number">1</span>;

<span class="hljs-keyword">if</span> (a == <span class="hljs-number">2</span>) {
  <span class="hljs-comment">/* do something */</span>
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (a == <span class="hljs-number">1</span>) {
  <span class="hljs-comment">/* do something else */</span>
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">/* do something else again */</span>
}
</code></pre>
<h3 id="heading-switch">switch</h3>
<p>If you need to do too many if / else / if blocks to perform a check, perhaps because you need to check the exact value of a variable, then <code>switch</code> can be very useful to you.</p>
<p>You can provide a variable as condition, and a series of <code>case</code> entry points for each value you expect:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> a = <span class="hljs-number">1</span>;

<span class="hljs-keyword">switch</span> (a) {
  <span class="hljs-keyword">case</span> <span class="hljs-number">0</span>:
    <span class="hljs-comment">/* do something */</span>
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-number">1</span>:
    <span class="hljs-comment">/* do something else */</span>
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-number">2</span>:
    <span class="hljs-comment">/* do something else */</span>
    <span class="hljs-keyword">break</span>;
}
</code></pre>
<p>We need a <code>break</code> keyword at the end of each case to avoid the next case being executed when the one before ends. This "cascade" effect can be useful in some creative ways.</p>
<p>You can add a "catch-all" case at the end, labeled <code>default</code>:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> a = <span class="hljs-number">1</span>;

<span class="hljs-keyword">switch</span> (a) {
  <span class="hljs-keyword">case</span> <span class="hljs-number">0</span>:
    <span class="hljs-comment">/* do something */</span>
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-number">1</span>:
    <span class="hljs-comment">/* do something else */</span>
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-number">2</span>:
    <span class="hljs-comment">/* do something else */</span>
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">default</span>:
    <span class="hljs-comment">/* handle all the other cases */</span>
    <span class="hljs-keyword">break</span>;
}
</code></pre>
<h2 id="heading-loops">Loops</h2>
<p>C offers us three ways to perform a loop: <strong>for loops</strong>, <strong>while loops</strong> and <strong>do while loops</strong>. They all allow you to iterate over arrays, but with a few differences. Let's see them in detail.</p>
<h3 id="heading-for-loops">For loops</h3>
<p>The first and probably most common way to perform a loop is <strong>for loops</strong>.</p>
<p>Using the <code>for</code> keyword we can define the <em>rules</em> of the loop up front, and then provide the block that is going to be executed repeatedly.</p>
<p>Like this:</p>
<pre><code class="lang-c"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt;= <span class="hljs-number">10</span>; i++) {
  <span class="hljs-comment">/* instructions to be repeated */</span>
}
</code></pre>
<p>The <code>(int i = 0; i &lt;= 10; i++)</code> block contains 3 parts of the looping details:</p>
<ul>
<li>the initial condition (<code>int i = 0</code>)</li>
<li>the test (<code>i &lt;= 10</code>)</li>
<li>the increment (<code>i++</code>)</li>
</ul>
<p>We first define a loop variable, in this case named <code>i</code>. <code>i</code> is a common variable name to be used for loops, along with <code>j</code> for nested loops (a loop inside another loop). It's just a convention.</p>
<p>The variable is initialized at the 0 value, and the first iteration is done. Then it is incremented as the increment part says (<code>i++</code> in this case, incrementing by 1), and all the cycle repeats until you get to the number 10.</p>
<p>Inside the loop main block we can access the variable <code>i</code> to know at which iteration we are. This program should print <code>0 1 2 3 4 5 5 6 7 8 9 10</code>:</p>
<pre><code class="lang-c"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt;= <span class="hljs-number">10</span>; i++) {
  <span class="hljs-comment">/* instructions to be repeated */</span>
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%u "</span>, i);
}
</code></pre>
<p>Loops can also start from a high number, and go a lower number, like this:</p>
<pre><code class="lang-c"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">10</span>; i &gt; <span class="hljs-number">0</span>; i--) {
  <span class="hljs-comment">/* instructions to be repeated */</span>
}
</code></pre>
<p>You can also increment the loop variable by 2 or another value:</p>
<pre><code class="lang-c"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1000</span>; i = i + <span class="hljs-number">30</span>) {
  <span class="hljs-comment">/* instructions to be repeated */</span>
}
</code></pre>
<h3 id="heading-while-loops">While loops</h3>
<p><strong>While loops</strong> is simpler to write than a <code>for</code> loop, because it requires a bit more work on your part.</p>
<p>Instead of defining all the loop data up front when you start the loop, like you do in the <code>for</code> loop, using <code>while</code> you just check for a condition:</p>
<pre><code class="lang-c"><span class="hljs-keyword">while</span> (i &lt; <span class="hljs-number">10</span>) {

}
</code></pre>
<p>This assumes that <code>i</code> is already defined and initialized with a value.</p>
<p>And this loop will be an <strong>infinite loop</strong> unless you increment the <code>i</code> variable at some point inside the loop. An infinite loop is bad because it will block the program, allowing nothing else to happen.</p>
<p>This is what you need for a "correct" while loop:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>;

<span class="hljs-keyword">while</span> (i &lt; <span class="hljs-number">10</span>) {
  <span class="hljs-comment">/* do something */</span>

  i++;
}
</code></pre>
<p>There's one exception to this, and we'll see it in one minute. Before, let me introduce <code>do while</code>.</p>
<h3 id="heading-do-while-loops">Do while loops</h3>
<p>While loops are great, but there might be times when you need to do one particular thing: you want to always execute a block, and then <em>maybe</em> repeat it.</p>
<p>This is done using the <code>do while</code> keyword. In a way it's very similar to a <code>while</code> loop, but slightly different:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>;

<span class="hljs-keyword">do</span> {
  <span class="hljs-comment">/* do something */</span>

  i++;
} <span class="hljs-keyword">while</span> (i &lt; <span class="hljs-number">10</span>);
</code></pre>
<p>The block that contains the <code>/* do something */</code> comment is always executed at least once, regardless of the condition check at the bottom.</p>
<p>Then, until <code>i</code> is less than 10, we'll repeat the block.</p>
<h3 id="heading-breaking-out-of-a-loop-using-break">Breaking out of a loop using break</h3>
<p>In all the C loops we have a way to break out of a loop at any point  in time, immediately, regardless of the conditions set for the loop.</p>
<p>This is done using the <code>break</code> keyword.</p>
<p>This is useful in many cases. You might want to check for the value of a variable, for example:</p>
<pre><code class="lang-c"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt;= <span class="hljs-number">10</span>; i++) {
  <span class="hljs-keyword">if</span> (i == <span class="hljs-number">4</span> &amp;&amp; someVariable == <span class="hljs-number">10</span>) {
    <span class="hljs-keyword">break</span>;
  }
}
</code></pre>
<p>Having this option to break out of a loop is particularly interesting for <code>while</code> loops (and <code>do while</code> too), because we can create seemingly infinite loops that end when a  condition occurs. You define this inside the loop block:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>;
<span class="hljs-keyword">while</span> (<span class="hljs-number">1</span>) {
  <span class="hljs-comment">/* do something */</span>

  i++;
  <span class="hljs-keyword">if</span> (i == <span class="hljs-number">10</span>) <span class="hljs-keyword">break</span>;
}
</code></pre>
<p>It's rather common to have this kind of loop in C.</p>
<h2 id="heading-arrays">Arrays</h2>
<p>An array is a variable that stores multiple values.</p>
<p>Every value in the array, in C, must have the <strong>same type</strong>. This means you will have arrays of <code>int</code> values, arrays of <code>double</code> values, and more.</p>
<p>You can define an array of <code>int</code> values like this:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> prices[<span class="hljs-number">5</span>];
</code></pre>
<p>You must always specify the size of the array. C does not provide dynamic arrays out of the box (you have to use a data structure like a linked list for that).</p>
<p>You can use a constant to define the size:</p>
<pre><code class="lang-c"><span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> SIZE = <span class="hljs-number">5</span>;
<span class="hljs-keyword">int</span> prices[SIZE];
</code></pre>
<p>You can initialize an array at definition time, like this:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> prices[<span class="hljs-number">5</span>] = { <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span> };
</code></pre>
<p>But you can also assign a value after the definition, in this way:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> prices[<span class="hljs-number">5</span>];

prices[<span class="hljs-number">0</span>] = <span class="hljs-number">1</span>;
prices[<span class="hljs-number">1</span>] = <span class="hljs-number">2</span>;
prices[<span class="hljs-number">2</span>] = <span class="hljs-number">3</span>;
prices[<span class="hljs-number">3</span>] = <span class="hljs-number">4</span>;
prices[<span class="hljs-number">4</span>] = <span class="hljs-number">5</span>;
</code></pre>
<p>Or, more practical, using a loop:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> prices[<span class="hljs-number">5</span>];

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">5</span>; i++) {
  prices[i] = i + <span class="hljs-number">1</span>;
}
</code></pre>
<p>And you can reference an item in the array by using square brackets after the array variable name, adding an integer to determine the index value. Like this:</p>
<pre><code class="lang-c">prices[<span class="hljs-number">0</span>]; <span class="hljs-comment">/* array item value: 1 */</span>
prices[<span class="hljs-number">1</span>]; <span class="hljs-comment">/* array item value: 2 */</span>
</code></pre>
<p>Array indexes start from 0, so an array with 5 items, like the <code>prices</code> array above, will have items ranging from <code>prices[0]</code> to <code>prices[4]</code>.</p>
<p>The interesting thing about C arrays is that all elements of an array are stored sequentially, one right after another. Not something that normally happens with higher-level programming languages.</p>
<p>Another interesting thing is this: the variable name of the array, <code>prices</code> in the above example, is a <strong>pointer</strong> to the first element of the array. As such it can be used like a normal pointer.</p>
<p>More on pointers soon.</p>
<h2 id="heading-strings">Strings</h2>
<p>In C, strings are one special kind of array: a string is an array of <code>char</code> values:</p>
<pre><code class="lang-c"><span class="hljs-keyword">char</span> name[<span class="hljs-number">7</span>];
</code></pre>
<p>I introduced the <code>char</code> type when I introduced types, but in short it is commonly used to store letters of the ASCII chart.</p>
<p>A string can be initialized like you initialize a normal array:</p>
<pre><code class="lang-c"><span class="hljs-keyword">char</span> name[<span class="hljs-number">7</span>] = { <span class="hljs-string">"F"</span>, <span class="hljs-string">"l"</span>, <span class="hljs-string">"a"</span>, <span class="hljs-string">"v"</span>, <span class="hljs-string">"i"</span>, <span class="hljs-string">"o"</span> };
</code></pre>
<p>Or more conveniently with a string literal (also called string constant), a sequence of characters enclosed in double quotes:</p>
<pre><code class="lang-c"><span class="hljs-keyword">char</span> name[<span class="hljs-number">7</span>] = <span class="hljs-string">"Flavio"</span>;
</code></pre>
<p>You can print a string via <code>printf()</code> using <code>%s</code>:</p>
<pre><code class="lang-c"><span class="hljs-built_in">printf</span>(<span class="hljs-string">"%s"</span>, name);
</code></pre>
<p>Do you notice how "Flavio" is 6 chars long, but I defined an array of length 7? Why? This is because the last character in a string must be a  <code>0</code> value, the string terminator, and we must make space for it.</p>
<p>This is important to keep in mind especially when manipulating strings.</p>
<p>Speaking of manipulating strings, there's one important standard library that is provided by C: <code>string.h</code>.</p>
<p>This library is essential because it abstracts many of the low level details of working with strings, and provides us with a set of useful functions.</p>
<p>You can load the library in your program by adding on top:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;string.h&gt;</span></span>
</code></pre>
<p>And once you do that, you have access to:</p>
<ul>
<li><code>strcpy()</code> to copy a string over another string</li>
<li><code>strcat()</code> to append a string to another string</li>
<li><code>strcmp()</code> to compare two strings for equality</li>
<li><code>strncmp()</code> to compare the first <code>n</code> characters of two strings</li>
<li><code>strlen()</code> to calculate the length of a string</li>
</ul>
<p>and many, many more.</p>
<h2 id="heading-pointers">Pointers</h2>
<p>Pointers are one of the most confusing/challenging parts of C, in my opinion. Especially if you are new to programming, but also if you come from a higher level programming language like Python or JavaScript.</p>
<p>In this section I want to introduce them in the simplest yet not-dumbed-down way possible.</p>
<p>A pointer is the address of a block of memory that contains a variable.</p>
<p>When you declare an integer number like this:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> age = <span class="hljs-number">37</span>;
</code></pre>
<p>We can use the <code>&amp;</code> operator to get the value of the address in memory of a variable:</p>
<pre><code class="lang-c"><span class="hljs-built_in">printf</span>(<span class="hljs-string">"%p"</span>, &amp;age); <span class="hljs-comment">/* 0x7ffeef7dcb9c */</span>
</code></pre>
<p>I used the <code>%p</code> format specified in <code>printf()</code> to print the address value.</p>
<p>We can assign the address to a variable:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> *address = &amp;age;
</code></pre>
<p>Using <code>int *address</code> in the declaration, we are not declaring an integer variable, but rather a <strong>pointer to an integer</strong>.</p>
<p>We can use the pointer operator <code>*</code> to get the value of the variable an address is pointing to:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> age = <span class="hljs-number">37</span>;
<span class="hljs-keyword">int</span> *address = &amp;age;
<span class="hljs-built_in">printf</span>(<span class="hljs-string">"%u"</span>, *address); <span class="hljs-comment">/* 37 */</span>
</code></pre>
<p>This time we are using the pointer operator again, but since it's not a declaration this time it means "the value of the variable this pointer points to".</p>
<p>In this example we declare an <code>age</code> variable, and we use a pointer to initialize the value:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> age;
<span class="hljs-keyword">int</span> *address = &amp;age;
*address = <span class="hljs-number">37</span>;
<span class="hljs-built_in">printf</span>(<span class="hljs-string">"%u"</span>, *address);
</code></pre>
<p>When working with C, you'll find that a lot of things are built on top of this simple concept. So make sure you familiarize with it a bit by running the above examples on your own.</p>
<p>Pointers are a great opportunity because they force us to think about memory addresses and how data is organized.</p>
<p>Arrays are one example. When you declare an array:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> prices[<span class="hljs-number">3</span>] = { <span class="hljs-number">5</span>, <span class="hljs-number">4</span>, <span class="hljs-number">3</span> };
</code></pre>
<p>The <code>prices</code> variable is actually a pointer to the first item of the array. You can get the value of the first item using this <code>printf()</code> function in this case:</p>
<pre><code class="lang-c"><span class="hljs-built_in">printf</span>(<span class="hljs-string">"%u"</span>, *prices); <span class="hljs-comment">/* 5 */</span>
</code></pre>
<p>The cool thing is that we can get the second item by adding 1 to the <code>prices</code> pointer:</p>
<pre><code class="lang-c"><span class="hljs-built_in">printf</span>(<span class="hljs-string">"%u"</span>, *(prices + <span class="hljs-number">1</span>)); <span class="hljs-comment">/* 4 */</span>
</code></pre>
<p>And so on for all the other values.</p>
<p>We can also do many nice string manipulation operations, since strings are arrays under the hood.</p>
<p>We also have many more applications, including passing the reference of an object or a function around to avoid consuming more resources to copy it.</p>
<h2 id="heading-functions">Functions</h2>
<p>Functions are the way we can structure our code into subroutines that we can:</p>
<ol>
<li>give a name to</li>
<li>call when we need them</li>
</ol>
<p>Starting from your very first program, a "Hello, World!", you immediately make use of C functions:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Hello, World!"</span>);
}
</code></pre>
<p>The <code>main()</code> function is a very important function, as it's the entry point for a C program.</p>
<p>Here's another function:</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">doSomething</span><span class="hljs-params">(<span class="hljs-keyword">int</span> value)</span> </span>{
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%u"</span>, value);
}
</code></pre>
<p>Functions have 4 important aspects:</p>
<ol>
<li>they have a name, so we can invoke ("call") them later</li>
<li>they specify a return value</li>
<li>they can have arguments</li>
<li>they have a body, wrapped in curly braces</li>
</ol>
<p>The function body is the set of instructions that are executed any time we invoke a function.</p>
<p>If the function has no return value, you can use the keyword <code>void</code> before the function name. Otherwise you specify the function return value type (<code>int</code> for an integer, <code>float</code> for a floating point value, <code>const char *</code> for a string, etc).</p>
<p>You cannot return more than one value from a function.</p>
<p>A function can have arguments. They are optional. If it does not have them, inside the parentheses we insert <code>void</code>, like this:</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">doSomething</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
   <span class="hljs-comment">/* ... */</span>
}
</code></pre>
<p>In this case, when we invoke the function we'll call it with nothing in the parentheses:</p>
<pre><code class="lang-c">doSomething();
</code></pre>
<p>If we have one parameter, we specify the type and the name of the parameter, like this:</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">doSomething</span><span class="hljs-params">(<span class="hljs-keyword">int</span> value)</span> </span>{
   <span class="hljs-comment">/* ... */</span>
}
</code></pre>
<p>When we invoke the function, we'll pass that parameter in the parentheses, like this:</p>
<pre><code class="lang-c">doSomething(<span class="hljs-number">3</span>);
</code></pre>
<p>We can have multiple parameters, and if so we separate them using a comma, both in the declaration and in the invocation:</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">doSomething</span><span class="hljs-params">(<span class="hljs-keyword">int</span> value1, <span class="hljs-keyword">int</span> value2)</span> </span>{
   <span class="hljs-comment">/* ... */</span>
}

doSomething(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>);
</code></pre>
<p>Parameters are passed by <strong>copy</strong>. This means that if you modify <code>value1</code>, its value is modified locally. The value outside of the function, where it was passed in the invocation, does not change.</p>
<p>If you pass a <strong>pointer</strong> as a parameter, you can modify that variable value because you can now access it directly using its memory address.</p>
<p>You can't define a default value for a parameter. C++ can do that (and so Arduino Language programs can), but C can't.</p>
<p>Make sure you define the function before calling it, or the compiler will raise a warning and an error:</p>
<pre><code>➜  ~ gcc hello.c -o hello; ./hello
hello.c:<span class="hljs-number">13</span>:<span class="hljs-number">3</span>: warning: implicit declaration <span class="hljs-keyword">of</span>
      <span class="hljs-function"><span class="hljs-keyword">function</span> '<span class="hljs-title">doSomething</span>' <span class="hljs-title">is</span> <span class="hljs-title">invalid</span> <span class="hljs-title">in</span> <span class="hljs-title">C99</span>
      [-<span class="hljs-title">Wimplicit</span>-<span class="hljs-title">function</span>-<span class="hljs-title">declaration</span>]
  <span class="hljs-title">doSomething</span>(<span class="hljs-params"><span class="hljs-number">3</span>, <span class="hljs-number">4</span></span>);
  ^
<span class="hljs-title">hello</span>.<span class="hljs-title">c</span>:17:6: <span class="hljs-title">error</span>: <span class="hljs-title">conflicting</span> <span class="hljs-title">types</span> <span class="hljs-title">for</span>
      '<span class="hljs-title">doSomething</span>'
<span class="hljs-title">void</span> <span class="hljs-title">doSomething</span>(<span class="hljs-params">int value1, char value2</span>) </span>{
     ^
hello.c:<span class="hljs-number">13</span>:<span class="hljs-number">3</span>: note: previous implicit declaration
      is here
  doSomething(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>);
  ^
<span class="hljs-number">1</span> warning and <span class="hljs-number">1</span> error generated.
</code></pre><p>The warning you get regards the ordering, which I already mentioned.</p>
<p>The error is about another thing, related. Since C does not "see" the function declaration before the invocation, it must make assumptions. And it assumes the function to return <code>int</code>. The function however returns <code>void</code>, hence the error.</p>
<p>If you change the function definition to:</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">doSomething</span><span class="hljs-params">(<span class="hljs-keyword">int</span> value1, <span class="hljs-keyword">int</span> value2)</span> </span>{
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%d %d\n"</span>, value1, value2);
  <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
}
</code></pre>
<p>you'd just get the warning, and not the error:</p>
<pre><code>➜  ~ gcc hello.c -o hello; ./hello
hello.c:<span class="hljs-number">14</span>:<span class="hljs-number">3</span>: warning: implicit declaration <span class="hljs-keyword">of</span>
      <span class="hljs-function"><span class="hljs-keyword">function</span> '<span class="hljs-title">doSomething</span>' <span class="hljs-title">is</span> <span class="hljs-title">invalid</span> <span class="hljs-title">in</span> <span class="hljs-title">C99</span>
      [-<span class="hljs-title">Wimplicit</span>-<span class="hljs-title">function</span>-<span class="hljs-title">declaration</span>]
  <span class="hljs-title">doSomething</span>(<span class="hljs-params"><span class="hljs-number">3</span>, <span class="hljs-number">4</span></span>);
  ^
1 <span class="hljs-title">warning</span> <span class="hljs-title">generated</span>.</span>
</code></pre><p>In any case, make sure you declare the function before using it. Either move the function up, or add the function prototype in a header file.</p>
<p>Inside a function, you can declare variables.</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">doSomething</span><span class="hljs-params">(<span class="hljs-keyword">int</span> value)</span> </span>{
  <span class="hljs-keyword">int</span> doubleValue = value * <span class="hljs-number">2</span>;
}
</code></pre>
<p>A variable is created at the point of invocation of the function and is destroyed when the function ends. It's not visible from the outside.</p>
<p>Inside a function, you can call the function itself. This is called <strong>recursion</strong> and it's something that offers peculiar opportunities.</p>
<h2 id="heading-input-and-output">Input and output</h2>
<p>C is a small language, and the "core" of C does not include any Input/Output (I/O) functionality.</p>
<p>This is not something unique to C, of course. It's common for the language core to be agnostic of I/O.</p>
<p>In the case of C, Input/Output is provided to us by the C Standard Library via a set of functions defined in the <code>stdio.h</code> header file.</p>
<p>You can import this library using:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
</code></pre>
<p>on top of your C file.</p>
<p>This library provides us with, among many other functions:</p>
<ul>
<li><code>printf()</code></li>
<li><code>scanf()</code></li>
<li><code>sscanf()</code></li>
<li><code>fgets()</code></li>
<li><code>fprintf()</code></li>
</ul>
<p>Before describing what those functions do, I want to take a minute to talk about <strong>I/O streams</strong>.</p>
<p>We have 3 kinds of I/O streams in C:</p>
<ul>
<li><code>stdin</code> (standard input)</li>
<li><code>stdout</code> (standard output)</li>
<li><code>stderr</code> (standard error)</li>
</ul>
<p>With I/O functions we always work with streams. A stream is a high level interface that can represent a device or a file. From the C standpoint, we don't have any difference in reading from a file or reading from the command line: it's an I/O stream in any case.</p>
<p>That's one thing to keep in mind.</p>
<p>Some functions are designed to work with a specific stream, like <code>printf()</code>, which we use to print characters to <code>stdout</code>. Using its more general counterpart <code>fprintf()</code>, we can specify which stream to write to.</p>
<p>Since I started talking about <code>printf()</code>, let's introduce it now.</p>
<p><code>printf()</code> is one of the first functions you'll use when learning C programming.</p>
<p>In its simplest usage form, you pass it a string literal:</p>
<pre><code class="lang-c"><span class="hljs-built_in">printf</span>(<span class="hljs-string">"hey!"</span>);
</code></pre>
<p>and the program will print the content of the string to the screen.</p>
<p>You can print the value of a variable. But it's a bit tricky because you need to add a special character, a placeholder, which changes depending on the type of the variable. For example we use <code>%d</code> for a signed decimal integer digit:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> age = <span class="hljs-number">37</span>;

<span class="hljs-built_in">printf</span>(<span class="hljs-string">"My age is %d"</span>, age);
</code></pre>
<p>We can print more than one variable by using commas:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> age_yesterday = <span class="hljs-number">37</span>;
<span class="hljs-keyword">int</span> age_today = <span class="hljs-number">36</span>;

<span class="hljs-built_in">printf</span>(<span class="hljs-string">"Yesterday my age was %d and today is %d"</span>, age_yesterday, age_today);
</code></pre>
<p>There are other format specifiers like <code>%d</code>:</p>
<ul>
<li><code>%c</code> for a char</li>
<li><code>%s</code> for a char</li>
<li><code>%f</code> for floating point numbers</li>
<li><code>%p</code> for pointers</li>
</ul>
<p>and many more.</p>
<p>We can use escape characters in <code>printf()</code>, like <code>\n</code> which we can use to make the output create a new line.</p>
<h3 id="heading-scanf"><code>scanf()</code></h3>
<p><code>printf()</code> is used as an output function. I want to introduce an input function now, so we can say we can do all the I/O thing: <code>scanf()</code>.</p>
<p>This function is used to get a value from the user running the program, from the command line.</p>
<p>We must first define a variable that will hold the value we get from the input:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> age;
</code></pre>
<p>Then we call <code>scanf()</code> with 2 arguments: the format (type) of the variable, and the address of the variable:</p>
<pre><code class="lang-c"><span class="hljs-built_in">scanf</span>(<span class="hljs-string">"%d"</span>, &amp;age);
</code></pre>
<p>If we want to get a string as input, remember that a string name is a pointer to the first character, so you don't need the <code>&amp;</code> character before it:</p>
<pre><code class="lang-c"><span class="hljs-keyword">char</span> name[<span class="hljs-number">20</span>];
<span class="hljs-built_in">scanf</span>(<span class="hljs-string">"%s"</span>, name);
</code></pre>
<p>Here's a little program that uses both <code>printf()</code> and <code>scanf()</code>:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
  <span class="hljs-keyword">char</span> name[<span class="hljs-number">20</span>];
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Enter your name: "</span>);
  <span class="hljs-built_in">scanf</span>(<span class="hljs-string">"%s"</span>, name);
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"you entered %s"</span>, name);
}
</code></pre>
<h2 id="heading-variable-scope">Variable scope</h2>
<p>When you define a variable in a C program, depending on where you declare it, it will have a different <strong>scope</strong>.</p>
<p>This means that it will be available in some places, but not in others.</p>
<p>The position determines 2 types of variables:</p>
<ul>
<li><strong>global variables</strong></li>
<li><strong>local variables</strong></li>
</ul>
<p>This is the difference: a variable declared inside a function is a local variable, like this:</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
  <span class="hljs-keyword">int</span> age = <span class="hljs-number">37</span>;
}
</code></pre>
<p>Local variables are only accessible from within the function, and when the function ends they stop their existence. They are cleared from the memory (with some exceptions).</p>
<p>A variable defined outside a function is a global variable, like in this example:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> age = <span class="hljs-number">37</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
  <span class="hljs-comment">/* ... */</span>
}
</code></pre>
<p>Global variables are accessible from any function of the program, and they are available for the whole execution of the program, until it ends.</p>
<p>I mentioned that local variables are not available any more after the function ends.</p>
<p>The reason is that local variables are declared on the <strong>stack</strong>, by default, unless you explicitly allocate them on the heap using pointers. But then you have to manage the memory yourself.</p>
<h2 id="heading-static-variables">Static variables</h2>
<p>Inside a function, you can initialize a <strong>static variable</strong> using the <code>static</code> keyword.</p>
<p>I said "inside a function" because global variables are static by default, so there's no need to add the keyword.</p>
<p>What's a static variable? A static variable is initialized to 0 if no initial value is specified, and it retains the value across function calls.</p>
<p>Consider this function:</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">incrementAge</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">int</span> age = <span class="hljs-number">0</span>;
  age++;
  <span class="hljs-keyword">return</span> age;
}
</code></pre>
<p>If we call <code>incrementAge()</code> once, we'll get <code>1</code> as the return value. If we call it more than once, we'll always get 1 back, because <code>age</code> is a local variable and it's re-initialized to <code>0</code> on every single function call.</p>
<p>If we change the function to:</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">incrementAge</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> age = <span class="hljs-number">0</span>;
  age++;
  <span class="hljs-keyword">return</span> age;
}
</code></pre>
<p>Now every time we call this function, we'll get an incremented value:</p>
<pre><code class="lang-c"><span class="hljs-built_in">printf</span>(<span class="hljs-string">"%d\n"</span>, incrementAge());
<span class="hljs-built_in">printf</span>(<span class="hljs-string">"%d\n"</span>, incrementAge());
<span class="hljs-built_in">printf</span>(<span class="hljs-string">"%d\n"</span>, incrementAge());
</code></pre>
<p>will give us</p>
<pre><code><span class="hljs-number">1</span>
<span class="hljs-number">2</span>
<span class="hljs-number">3</span>
</code></pre><p>We can also omit initializing <code>age</code> to 0 in <code>static int age = 0;</code>, and just write <code>static int age;</code> because static variables are automatically set to 0 when created.</p>
<p>We can also have static arrays. In this case, each single item in the array is initialized to 0:</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">incrementAge</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> ages[<span class="hljs-number">3</span>];
  ages[<span class="hljs-number">0</span>]++;
  <span class="hljs-keyword">return</span> ages[<span class="hljs-number">0</span>];
}
</code></pre>
<h2 id="heading-global-variables">Global variables</h2>
<p>In this section I want to talk more about the difference between <strong>global and local variables</strong>.</p>
<p>A <strong>local variable</strong> is defined inside a function, and it's only available inside that function.</p>
<p>Like this:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
  <span class="hljs-keyword">char</span> j = <span class="hljs-number">0</span>;
  j += <span class="hljs-number">10</span>;
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%u"</span>, j); <span class="hljs-comment">//10</span>
}
</code></pre>
<p><code>j</code> is not available anywhere outside the <code>main</code> function.</p>
<p>A <strong>global variable</strong> is defined outside of any function, like this:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-keyword">char</span> i = <span class="hljs-number">0</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
  i += <span class="hljs-number">10</span>;
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%u"</span>, i); <span class="hljs-comment">//10</span>
}
</code></pre>
<p>A global variable can be accessed by any function in the program.  Access is not limited to reading the value: the variable can be updated by any function.</p>
<p>Due to this, global variables are one way we have of sharing the same data between functions.</p>
<p>The main difference with local variables is that the memory allocated for variables is freed once the function ends.</p>
<p>Global variables are only freed when the program ends.</p>
<h2 id="heading-type-definitions">Type definitions</h2>
<p>The <code>typedef</code> keyword in C allows you to defined new types.</p>
<p>Starting from the built-in C types, we can create our own types, using this syntax:</p>
<pre><code class="lang-c"><span class="hljs-keyword">typedef</span> existingtype NEWTYPE
</code></pre>
<p>The new type we create is usually, by convention, uppercase.</p>
<p>This it to distinguish it more easily, and immediately recognize it as type.</p>
<p>For example we can define a new <code>NUMBER</code> type that is an <code>int</code>:</p>
<pre><code class="lang-c"><span class="hljs-keyword">typedef</span> <span class="hljs-keyword">int</span> NUMBER
</code></pre>
<p>and once you do so, you can define new <code>NUMBER</code> variables:</p>
<pre><code class="lang-c">NUMBER one = <span class="hljs-number">1</span>;
</code></pre>
<p>Now you might ask: why? Why not just use the built-in type <code>int</code> instead?</p>
<p>Well, <code>typedef</code> gets really useful when paired with two things: enumerated types and structures.</p>
<h2 id="heading-enumerated-types">Enumerated types</h2>
<p>Using the <code>typedef</code> and <code>enum</code> keywords we can define a type that can have either one value or another.</p>
<p>It's one of the most important uses of the <code>typedef</code> keyword.</p>
<p>This is the syntax of an enumerated type:</p>
<pre><code class="lang-c"><span class="hljs-keyword">typedef</span> <span class="hljs-keyword">enum</span> {
  <span class="hljs-comment">//...values</span>
} TYPENAME;
</code></pre>
<p>The enumerated type we create is usually, by convention, uppercase.</p>
<p>Here is a simple example:</p>
<pre><code class="lang-c"><span class="hljs-keyword">typedef</span> <span class="hljs-keyword">enum</span> {
  <span class="hljs-literal">true</span>,
  <span class="hljs-literal">false</span>
} BOOLEAN;
</code></pre>
<p>C comes with a <code>bool</code> type, so this example is not really practical, but you get the idea.</p>
<p>Another example is to define weekdays:</p>
<pre><code class="lang-c"><span class="hljs-keyword">typedef</span> <span class="hljs-keyword">enum</span> {
  monday,  
  tuesday,
  wednesday,
  thursday,
  friday,
  saturday,
  sunday
} WEEKDAY;
</code></pre>
<p>Here's a simple program that uses this enumerated type:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-keyword">typedef</span> <span class="hljs-keyword">enum</span> {
  monday,  
  tuesday,
  wednesday,
  thursday,
  friday,
  saturday,
  sunday
} WEEKDAY;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
  WEEKDAY day = monday;

  <span class="hljs-keyword">if</span> (day == monday) {
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"It's monday!"</span>); 
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"It's not monday"</span>); 
  }
}
</code></pre>
<p>Every item in the enum definition is paired to an integer, internally. So in this example <code>monday</code> is 0, <code>tuesday</code> is 1 and so on.</p>
<p>This means the conditional could have been <code>if (day == 0)</code> instead of <code>if (day == monday)</code>, but it's way simpler for us humans to reason with names rather than numbers, so it's a very convenient syntax.</p>
<h2 id="heading-structures">Structures</h2>
<p>Using the <code>struct</code> keyword we can create complex data structures using basic C types.</p>
<p>A structure is a collection of values of different types. Arrays in C are limited to a type, so structures can prove to be very interesting in a lot of use cases.</p>
<p>This is the syntax of a structure:</p>
<pre><code class="lang-c"><span class="hljs-class"><span class="hljs-keyword">struct</span> &lt;structname&gt; {</span>
  <span class="hljs-comment">//...variables</span>
};
</code></pre>
<p>Example:</p>
<pre><code class="lang-c"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">person</span> {</span>
  <span class="hljs-keyword">int</span> age;
  <span class="hljs-keyword">char</span> *name;
};
</code></pre>
<p>You can declare variables that have as type that structure by adding them after the closing curly bracket, before the semicolon, like this:</p>
<pre><code class="lang-c"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">person</span> {</span>
  <span class="hljs-keyword">int</span> age;
  <span class="hljs-keyword">char</span> *name;
} flavio;
</code></pre>
<p>Or multiple ones, like this:</p>
<pre><code class="lang-c"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">person</span> {</span>
  <span class="hljs-keyword">int</span> age;
  <span class="hljs-keyword">char</span> *name;
} flavio, people[<span class="hljs-number">20</span>];
</code></pre>
<p>In this case I declare a single <code>person</code> variable named <code>flavio</code>, and an array of 20 <code>person</code> named <code>people</code>.</p>
<p>We can also declare variables later on, using this syntax:</p>
<pre><code class="lang-c"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">person</span> {</span>
  <span class="hljs-keyword">int</span> age;
  <span class="hljs-keyword">char</span> *name;
};

<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">person</span> <span class="hljs-title">flavio</span>;</span>
</code></pre>
<p>We can initialize a structure at declaration time:</p>
<pre><code class="lang-c"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">person</span> {</span>
  <span class="hljs-keyword">int</span> age;
  <span class="hljs-keyword">char</span> *name;
};

<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">person</span> <span class="hljs-title">flavio</span> = {</span> <span class="hljs-number">37</span>, <span class="hljs-string">"Flavio"</span> };
</code></pre>
<p>and once we have a structure defined, we can access the values in it using a dot:</p>
<pre><code class="lang-c"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">person</span> {</span>
  <span class="hljs-keyword">int</span> age;
  <span class="hljs-keyword">char</span> *name;
};

<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">person</span> <span class="hljs-title">flavio</span> = {</span> <span class="hljs-number">37</span>, <span class="hljs-string">"Flavio"</span> };
<span class="hljs-built_in">printf</span>(<span class="hljs-string">"%s, age %u"</span>, flavio.name, flavio.age);
</code></pre>
<p>We can also change the values using the dot syntax:</p>
<pre><code class="lang-c"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">person</span> {</span>
  <span class="hljs-keyword">int</span> age;
  <span class="hljs-keyword">char</span> *name;
};

<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">person</span> <span class="hljs-title">flavio</span> = {</span> <span class="hljs-number">37</span>, <span class="hljs-string">"Flavio"</span> };

flavio.age = <span class="hljs-number">38</span>;
</code></pre>
<p>Structures are very useful because we can pass them around as function parameters, or return values, embedding various variables within them. Each variable has a label.</p>
<p>It's important to note that structures are <strong>passed by copy</strong>, unless of course you pass a pointer to a struct, in which case it's passed by reference.</p>
<p>Using <code>typedef</code> we can simplify the code when working with structures.</p>
<p>Let's look at an example:</p>
<pre><code class="lang-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> {</span>
  <span class="hljs-keyword">int</span> age;
  <span class="hljs-keyword">char</span> *name;
} PERSON;
</code></pre>
<p>The structure we create using <code>typedef</code> is usually, by convention, uppercase.</p>
<p>Now we can declare new <code>PERSON</code> variables like this:</p>
<pre><code class="lang-c">PERSON flavio;
</code></pre>
<p>and we can initialize them at declaration in this way:</p>
<pre><code class="lang-c">PERSON flavio = { <span class="hljs-number">37</span>, <span class="hljs-string">"Flavio"</span> };
</code></pre>
<h2 id="heading-command-line-parameters">Command line parameters</h2>
<p>In your C programs, you might need to accept parameters from the command line when the command launches.</p>
<p>For simple needs, all you need to do to do so is change the <code>main()</code> function signature from</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span></span>
</code></pre>
<p>to</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span> <span class="hljs-params">(<span class="hljs-keyword">int</span> argc, <span class="hljs-keyword">char</span> *argv[])</span></span>
</code></pre>
<p><code>argc</code> is an integer number that contains the number of parameters that were provided in the command line.</p>
<p><code>argv</code> is an array of strings.</p>
<p>When the program starts, we are provided the arguments in those 2 parameters.</p>
<p>Note that there's always at least one item in the <code>argv</code> array: the name of the program</p>
<p>Let's take the example of the C compiler we use to run our programs, like this:</p>
<pre><code class="lang-sh">gcc hello.c -o hello
</code></pre>
<p>If this was our program, we'd have <code>argc</code> being 4 and <code>argv</code> being an array containing</p>
<ul>
<li><code>gcc</code></li>
<li><code>hello.c</code></li>
<li><code>-o</code></li>
<li><code>hello</code></li>
</ul>
<p>Let's write a program that prints the arguments it receives:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span> <span class="hljs-params">(<span class="hljs-keyword">int</span> argc, <span class="hljs-keyword">char</span> *argv[])</span> </span>{
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; argc; i++) {
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%s\n"</span>, argv[i]);
  }
}
</code></pre>
<p>If the name of our program is <code>hello</code> and we run it like this: <code>./hello</code>, we'd get this as output:</p>
<pre><code>./hello
</code></pre><p>If we pass some random parameters, like this: <code>./hello a b c</code> we'd get this output to the terminal:</p>
<pre><code>./hello
a
b
c
</code></pre><p>This system works great for simple needs. For more complex needs, there are commonly used packages like <strong>getopt</strong>.</p>
<h2 id="heading-headers-files">Headers files</h2>
<p>Simple programs can be put in a single file. But when your program grows larger it's impossible to keep it all in just one file.</p>
<p>You can move parts of a program to a separate file. Then you create a <strong>header file</strong>.</p>
<p>A header file looks like a normal C file, except it ends with <code>.h</code> instead of <code>.c</code>. Instead of the implementations of your functions and the other parts of a program, it holds the <strong>declarations</strong>.</p>
<p>You already used header files when you first used the <code>printf()</code> function, or other I/O function, and you had to type:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
</code></pre>
<p>to use it.</p>
<p><code>#include</code> is a preprocessor directive.</p>
<p>The preprocessor goes and looks up the <code>stdio.h</code> file in the standard library because you used brackets around it. To include your own header files, you'll use quotes, like this:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"myfile.h"</span></span>
</code></pre>
<p>The above will look up <code>myfile.h</code> in the current folder.</p>
<p>You can also use a folder structure for libraries:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"myfolder/myfile.h"</span></span>
</code></pre>
<p>Let's look at an example. This program calculates the years since a given year:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">calculateAge</span><span class="hljs-params">(<span class="hljs-keyword">int</span> year)</span> </span>{
  <span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> CURRENT_YEAR = <span class="hljs-number">2020</span>;
  <span class="hljs-keyword">return</span> CURRENT_YEAR - year;
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%u"</span>, calculateAge(<span class="hljs-number">1983</span>));
}
</code></pre>
<p>Suppose I want to move the <code>calculateAge</code> function to a separate file.</p>
<p>I create a <code>calculate_age.c</code> file:</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">calculateAge</span><span class="hljs-params">(<span class="hljs-keyword">int</span> year)</span> </span>{
  <span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> CURRENT_YEAR = <span class="hljs-number">2020</span>;
  <span class="hljs-keyword">return</span> CURRENT_YEAR - year;
}
</code></pre>
<p>And a <code>calculate_age.h</code> file where I put the <em>function prototype</em>, which is the same as the function in the <code>.c</code> file, except the body:</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">calculateAge</span><span class="hljs-params">(<span class="hljs-keyword">int</span> year)</span></span>;
</code></pre>
<p>Now in the main <code>.c</code> file we can go and remove the <code>calculateAge()</code> function definition, and we can import <code>calculate_age.h</code>, which will make the <code>calculateAge()</code> function available:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"calculate_age.h"</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%u"</span>, calculateAge(<span class="hljs-number">1983</span>));
}
</code></pre>
<p>Don't forget that to compile a program composed by multiple files, you need to list them all in the command line, like this:</p>
<pre><code class="lang-sh">gcc -o main main.c calculate_age.c
</code></pre>
<p>And with more complex setups, a Makefile is necessary to tell the compiler how to compile the program.</p>
<h2 id="heading-the-preprocessor">The preprocessor</h2>
<p>The preprocessor is a tool that helps us a lot when programming with C. It is part of the C Standard, just like the language, the compiler, and the standard library.</p>
<p>It parses our program and makes sure that the compiler gets all the things it needs before going on with the process.</p>
<p>What does it do, in practice?</p>
<p>For example, it looks up all the header files you include with the <code>#include</code> directive.</p>
<p>It also looks at every constant you defined using <code>#define</code> and substitutes it with its actual value.</p>
<p>That's just the start. I mentioned those 2 operations because they are the most common ones. The preprocessor can do a lot more.</p>
<p>Did you notice <code>#include</code> and <code>#define</code> have a <code>#</code> at the beginning? That's common to all the preprocessor directives. If a line starts with <code>#</code>, that's taken care of by the preprocessor.</p>
<h3 id="heading-conditionals-1">Conditionals</h3>
<p>One of the things we can do is to use conditionals to change how our program will be compiled, depending on the value of an expression.</p>
<p>For example we can check if the <code>DEBUG</code> constant is 0:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> DEBUG = <span class="hljs-number">0</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
<span class="hljs-meta">#<span class="hljs-meta-keyword">if</span> DEBUG == 0</span>
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"I am NOT debugging\n"</span>);
<span class="hljs-meta">#<span class="hljs-meta-keyword">else</span></span>
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"I am debugging\n"</span>);
<span class="hljs-meta">#<span class="hljs-meta-keyword">endif</span></span>
}
</code></pre>
<h3 id="heading-symbolic-constants">Symbolic constants</h3>
<p>We can define a <strong>symbolic constant</strong>:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> VALUE 1</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> PI 3.14</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> NAME <span class="hljs-meta-string">"Flavio"</span></span>
</code></pre>
<p>When we use NAME or PI or VALUE in our program, the preprocessor replaces its name with the value before executing the program.</p>
<p>Symbolic constants are very useful because we can give names to values without creating variables at compilation time.</p>
<h3 id="heading-macros">Macros</h3>
<p>With <code>#define</code> we can also define a <strong>macro</strong>. The difference between a macro and a symbolic constant is that a macro can accept an argument and typically contains code, while a symbolic constant is a value:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> POWER(x) ((x) * (x))</span>
</code></pre>
<p>Notice the parentheses around the arguments: this is a good practice to avoid issues when the macro is replaced in the precompilation process.</p>
<p>Then we can use it in our code like this:</p>
<pre><code class="lang-c"><span class="hljs-built_in">printf</span>(<span class="hljs-string">"%u\n"</span>, POWER(<span class="hljs-number">4</span>)); <span class="hljs-comment">//16</span>
</code></pre>
<p>The big difference with functions is that macros do not specify the type of their arguments or return values, which might be handy in some cases.</p>
<p>Macros, however, are limited to one line definitions.</p>
<h3 id="heading-if-defined">If defined</h3>
<p>We can check if a symbolic constant or a macro is defined using <code>#ifdef</code>:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> VALUE 1</span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
<span class="hljs-meta">#<span class="hljs-meta-keyword">ifdef</span> VALUE</span>
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Value is defined\n"</span>);
<span class="hljs-meta">#<span class="hljs-meta-keyword">else</span></span>
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Value is not defined\n"</span>);
<span class="hljs-meta">#<span class="hljs-meta-keyword">endif</span></span>
}
</code></pre>
<p>We also have <code>#ifndev</code> to check for the opposite (macro not defined).</p>
<p>We can also use <code>#if defined</code> and <code>#if !defined</code> to do the same task.</p>
<p>It's common to wrap some block of code into a block like this:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">if</span> 0</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">endif</span></span>
</code></pre>
<p>to temporarily prevent it from running, or to use a DEBUG symbolic constant:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> DEBUG 0</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">if</span> DEBUG</span>
  <span class="hljs-comment">//code only sent to the compiler</span>
  <span class="hljs-comment">//if DEBUG is not 0</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">endif</span></span>
</code></pre>
<h3 id="heading-predefined-symbolic-constants-you-can-use">Predefined symbolic constants you can use</h3>
<p>The preprocessor also defines a number of symbolic constants you can use, identified by the 2 underscores before and after the name, including:</p>
<ul>
<li><code>__LINE__</code> translates to the current line in the source code file</li>
<li><code>__FILE__</code> translates to the name of the file</li>
<li><code>__DATE__</code> translates to the compilation date, in the <code>Mmm gg aaaa</code> format</li>
<li><code>__TIME__</code> translates to the compilation time, in the <code>hh:mm:ss</code> format</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Thanks a lot for reading this handbook!</p>
<p>I hope it will inspire you to know more about C.</p>
<p>For more tutorials, check out my blog <a target="_blank" href="https://flaviocopes.com">flaviocopes.com</a>.</p>
<p>Send any feedback, errata, or opinions at <a target="_blank" href="mailto:hey@flaviocopes.com">hey@flaviocopes.com</a></p>
<p>And remember: <a target="_blank" href="https://flaviocopes.com/page/c-handbook/">You can get a PDF and ePub version of this C Beginner's Handbook</a></p>
<p>You can reach me on Twitter <a target="_blank" href="https://twitter.com/flaviocopes">@flaviocopes</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The JavaScript Beginner's Handbook ]]>
                </title>
                <description>
                    <![CDATA[ JavaScript is one of the most popular programming languages in the world. I believe it's a great choice for your first programming language ever. We mainly use JavaScript to create websites web applications server-side applications using Node.js ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-complete-javascript-handbook-f26b2c71719c/</link>
                <guid isPermaLink="false">66bb5a97e326dc37a9d68ef6</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Flavio Copes ]]>
                </dc:creator>
                <pubDate>Sun, 01 Mar 2020 16:59:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/03/cover-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JavaScript is one of the most popular programming languages in the world.</p>
<p>I believe it's a great choice for your first programming language ever.</p>
<p>We mainly use JavaScript to create</p>
<ul>
<li><p>websites</p>
</li>
<li><p>web applications</p>
</li>
<li><p>server-side applications using Node.js</p>
</li>
</ul>
<p>but JavaScript is not limited to these things, and it can also be used to</p>
<ul>
<li><p>create mobile applications using tools like React Native</p>
</li>
<li><p>create programs for microcontrollers and the internet of things</p>
</li>
<li><p>create smartwatch applications</p>
</li>
</ul>
<p>It can basically do anything. It's so popular that everything new that shows up is going to have some kind of JavaScript integration at some point.</p>
<p>JavaScript is a programming language that is:</p>
<ul>
<li><p><strong>high level</strong>: it provides abstractions that allow you to ignore the details of the machine where it's running on. It manages memory automatically with a garbage collector, so you can focus on the code instead of managing memory like other languages like C would need, and provides many constructs which allow you to deal with highly powerful variables and objects.</p>
</li>
<li><p><strong>dynamic</strong>: opposed to static programming languages, a dynamic language executes at runtime many of the things that a static language does at compile time. This has pros and cons, and it gives us powerful features like dynamic typing, late binding, reflection, functional programming, object runtime alteration, closures and much more. Don't worry if those things are unknown to you - you'll know all of them by the end of the course.</p>
</li>
<li><p><strong>dynamically typed</strong>: a variable does not enforce a type. You can reassign any type to a variable, for example, assigning an integer to a variable that holds a string.</p>
</li>
<li><p><strong>loosely typed</strong>: as opposed to strong typing, loosely (or weakly) typed languages do not enforce the type of an object, allowing more flexibility but denying us type safety and type checking (something that TypeScript - which builds on top of JavaScript - provides)</p>
</li>
<li><p><strong>interpreted</strong>: it's commonly known as an interpreted language, which means that it does not need a compilation stage before a program can run, as opposed to C, Java or Go for example. In practice, browsers do compile JavaScript before executing it, for performance reasons, but this is transparent to you - there is no additional step involved.</p>
</li>
<li><p><strong>multi-paradigm</strong>: the language does not enforce any particular programming paradigm, unlike Java for example, which forces the use of object-oriented programming, or C that forces imperative programming. You can write JavaScript using an object-oriented paradigm, using prototypes and the new (as of ES6) classes syntax. You can write JavaScript in a functional programming style, with its first-class functions, or even in an imperative style (C-like).</p>
</li>
</ul>
<p>In case you're wondering, <em>JavaScript has nothing to do with Java</em>, it's a poor name choice but we have to live with it.</p>
<h2 id="heading-summary-of-the-handbook">Summary of the handbook</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-a-little-bit-of-history">A little bit of history</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-just-javascript">Just JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-a-brief-intro-to-the-syntax-of-javascript">A brief intro to the syntax of JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-semicolons">Semicolons</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-values">Values</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-variables">Variables</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-types">Types</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-expressions">Expressions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-operators">Operators</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-precedence-rules">Precedence rules</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-comparison-operators">Comparison operators</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conditionals">Conditionals</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-arrays">Arrays</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-strings">Strings</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-loops">Loops</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-functions">Functions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-arrow-functions">Arrow functions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-objects">Objects</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-object-properties">Object Properties</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-object-methods">Object Methods</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-classes">Classes</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-inheritance">Inheritance</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-asynchonous-programming-and-callbacks">Asynchonous Programming and Callbacks</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-promises">Promises</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-async-and-await">Async and Await</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-variable-scope">Variable scope</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ol>
<blockquote>
<p>Update: <a target="_blank" href="https://flaviocopes.com/page/javascript-handbook/">You can now get a PDF and ePub version of this JavaScript Beginner's Handbook</a>.</p>
</blockquote>
<h2 id="heading-a-little-bit-of-history">A little bit of history</h2>
<p>Created in 1995, JavaScript has gone a very long way since its humble beginnings.</p>
<p>It was the first scripting language that was supported natively by web browsers, and thanks to this it gained a competitive advantage over any other language and today it's still the only scripting language that we can use to build Web Applications.</p>
<p>Other languages exist, but all must compile to JavaScript - or more recently to WebAssembly, but this is another story.</p>
<p>In the begining, JavaScript was not nearly powerful as it is today, and it was mainly used for fancy animations and the marvel known at the time as <em>Dynamic HTML</em>.</p>
<p>With the growing needs that the web platform demanded (and continues to demand), JavaScript <em>had</em> the responsibility to grow as well, to accommodate the needs of one of the most widely used ecosystems of the world.</p>
<p>JavaScript is also now widely used outside of the browser. The rise of Node.js in the last few years unlocked backend development, once the domain of Java, Ruby, Python, PHP, and more traditional server-side languages.</p>
<p>JavaScript is now also the language powering databases and many more applications, and it's even possible to develop embedded applications, mobile apps, TV apps, and much more. What started as a tiny language inside the browser is now the most popular language in the world.</p>
<h2 id="heading-just-javascript">Just JavaScript</h2>
<p>Sometimes it's hard to separate JavaScript from the features of the environment it is used in.</p>
<p>For example, the <code>console.log()</code> line you can find in many code examples is not JavaScript. Instead, it's part of the vast library of APIs provided to us in the browser.</p>
<p>In the same way, on the server it can be sometimes hard to separate the JavaScript language features from the APIs provided by Node.js.</p>
<p>Is a particular feature provided by React or Vue? Or is it "plain JavaScript", or "vanilla JavaScript" as it's often called?</p>
<p>In this book I talk about JavaScript, the language.</p>
<p>Without complicating your learning process with things that are outside of it, and provided by external ecosystems.</p>
<h2 id="heading-a-brief-intro-to-the-syntax-of-javascript">A brief intro to the syntax of JavaScript</h2>
<p>In this little introduction I want to tell you about 5 concepts:</p>
<ul>
<li><p>white space</p>
</li>
<li><p>case sensitivity</p>
</li>
<li><p>literals</p>
</li>
<li><p>identifiers</p>
</li>
<li><p>comments</p>
</li>
</ul>
<h3 id="heading-white-space">White space</h3>
<p>JavaScript does not consider white space meaningful. Spaces and line breaks can be added in any fashion you might like, at least <em>in theory</em>.</p>
<p>In practice, you will most likely keep a well defined style and adhere to what people commonly use, and enforce this using a linter or a style tool such as <em>Prettier</em>.</p>
<p>For example, I always use 2 space characters for each indentation.</p>
<h4 id="heading-case-sensitive">Case sensitive</h4>
<p>JavaScript is case sensitive. A variable named <code>something</code> is different than <code>Something</code>.</p>
<p>The same goes for any identifier.</p>
<h3 id="heading-literals">Literals</h3>
<p>We define <strong>literal</strong> as a value that is written in the source code, for example, a number, a string, a boolean or also more advanced constructs, like Object Literals or Array Literals:</p>
<pre><code class="lang-js"><span class="hljs-number">5</span>
<span class="hljs-string">'Test'</span>
<span class="hljs-literal">true</span>
[<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>]
{<span class="hljs-attr">color</span>: <span class="hljs-string">'red'</span>, <span class="hljs-attr">shape</span>: <span class="hljs-string">'Rectangle'</span>}
</code></pre>
<h3 id="heading-identifiers">Identifiers</h3>
<p>An <strong>identifier</strong> is a sequence of characters that can be used to identify a variable, a function, or an object. It can start with a letter, the dollar sign <code>$</code> or an underscore <code>_</code>, and it can contain digits. Using Unicode, a letter can be any allowed character, for example, an emoji ?.</p>
<pre><code class="lang-js">Test
test
TEST
_test
Test1
$test
</code></pre>
<p>The dollar sign is commonly used to reference DOM elements.</p>
<p>Some names are reserved for JavaScript internal use, and we can't use them as identifiers.</p>
<h3 id="heading-comments">Comments</h3>
<p>Comments are one of the most important parts of any program, in any programming language. They are important because they let us annotate the code and add important information that otherwise would not be available to other people (or ourselves) reading the code.</p>
<p>In JavaScript, we can write a comment on a single line using <code>//</code>. Everything after <code>//</code> is not considered as code by the JavaScript interpreter.</p>
<p>Like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// a comment</span>
<span class="hljs-literal">true</span> <span class="hljs-comment">//another comment</span>
</code></pre>
<p>Another type of comment is a multi-line comment. It starts with <code>/*</code> and ends with <code>*/</code>.</p>
<p>Everything in between is not considered as code:</p>
<pre><code class="lang-js"><span class="hljs-comment">/* some kind
of 
comment 

*/</span>
</code></pre>
<h2 id="heading-semicolons">Semicolons</h2>
<p>Every line in a JavaScript program is optionally terminated using semicolons.</p>
<p>I said optionally, because the JavaScript interpreter is smart enough to introduce semicolons for you.</p>
<p>In most cases, you can omit semicolons altogether from your programs without even thinking about it.</p>
<p>This fact is very controversial. Some developers will always use semicolons, some others will never use semicolons, and you'll always find code that uses semicolons and code that does not.</p>
<p>My personal preference is to avoid semicolons, so my examples in the book will not include them.</p>
<h2 id="heading-values">Values</h2>
<p>A <code>hello</code> string is a <strong>value</strong>. A number like <code>12</code> is a <strong>value</strong>.</p>
<p><code>hello</code> and <code>12</code> are values. <code>string</code> and <code>number</code> are the <strong>types</strong> of those values.</p>
<p>The <strong>type</strong> is the kind of value, its category. We have many different types in JavaScript, and we'll talk about them in detail later on. Each type has its own characteristics.</p>
<p>When we need to have a reference to a value, we assign it to a <strong>variable</strong>. The variable can have a name, and the value is what's stored in a variable, so we can later access that value through the variable name.</p>
<h2 id="heading-variables">Variables</h2>
<p>A variable is a value assigned to an identifier, so you can reference and use it later in the program.</p>
<p>This is because JavaScript is <strong>loosely typed</strong>, a concept you'll frequently hear about.</p>
<p>A variable must be declared before you can use it.</p>
<p>We have 2 main ways to declare variables. The first is to use <code>const</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> a = <span class="hljs-number">0</span>
</code></pre>
<p>The second way is to use <code>let</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> a = <span class="hljs-number">0</span>
</code></pre>
<p>What's the difference?</p>
<p><code>const</code> defines a constant reference to a value. This means the reference cannot be changed. You cannot reassign a new value to it.</p>
<p>Using <code>let</code> you can assign a new value to it.</p>
<p>For example, you cannot do this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> a = <span class="hljs-number">0</span>
a = <span class="hljs-number">1</span>
</code></pre>
<p>Because you'll get an error: <code>TypeError: Assignment to constant variable.</code>.</p>
<p>On the other hand, you can do it using <code>let</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> a = <span class="hljs-number">0</span>
a = <span class="hljs-number">1</span>
</code></pre>
<p><code>const</code> does not mean "constant" in the way some other languages like C mean. In particular, it does not mean the value cannot change - it means it cannot be reassigned. If the variable points to an object or an array (we'll see more about objects and arrays later) the content of the object or the array can freely change.</p>
<p><code>const</code> variables must be initialized at the declaration time:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> a = <span class="hljs-number">0</span>
</code></pre>
<p>but <code>let</code> values can be initialized later:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> a
a = <span class="hljs-number">0</span>
</code></pre>
<p>You can declare multiple variables at once in the same statement:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> a = <span class="hljs-number">1</span>, b = <span class="hljs-number">2</span>
<span class="hljs-keyword">let</span> c = <span class="hljs-number">1</span>, d = <span class="hljs-number">2</span>
</code></pre>
<p>But you cannot redeclare the same variable more than one time:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> a = <span class="hljs-number">1</span>
<span class="hljs-keyword">let</span> a = <span class="hljs-number">2</span>
</code></pre>
<p>or you'd get a "duplicate declaration" error.</p>
<p>My advice is to always use <code>const</code> and only use <code>let</code> when you know you'll need to reassign a value to that variable. Why? Because the less power our code has, the better. If we know a value cannot be reassigned, it's one less source for bugs.</p>
<p>Now that we saw how to work with <code>const</code> and <code>let</code>, I want to mention <code>var</code>.</p>
<p>Until 2015, <code>var</code> was the only way we could declare a variable in JavaScript. Today, a modern codebase will most likely just use <code>const</code> and <code>let</code>. There are some fundamental differences which I detail <a target="_blank" href="https://flaviocopes.com/javascript-difference-let-var/">in this post</a> but if you're just starting out, you might not care about them. Just use <code>const</code> and <code>let</code>.</p>
<h2 id="heading-types">Types</h2>
<p>Variables in JavaScript do not have any type attached.</p>
<p>They are <em>untyped</em>.</p>
<p>Once you assign a value with some type to a variable, you can later reassign the variable to host a value of any other type without any issues.</p>
<p>In JavaScript we have 2 main kinds of types: <strong>primitive types</strong> and <strong>object types</strong>.</p>
<h3 id="heading-primitive-types">Primitive types</h3>
<p>Primitive types are</p>
<ul>
<li><p>numbers</p>
</li>
<li><p>strings</p>
</li>
<li><p>booleans</p>
</li>
<li><p>symbols</p>
</li>
</ul>
<p>And two special types: <code>null</code> and <code>undefined</code>.</p>
<h3 id="heading-object-types">Object types</h3>
<p>Any value that's not of a primitive type (a string, a number, a boolean, null or undefined) is an <strong>object</strong>.</p>
<p>Object types have <strong>properties</strong> and also have <strong>methods</strong> that can act on those properties.</p>
<p>We'll talk more about objects later on.</p>
<h2 id="heading-expressions">Expressions</h2>
<p>An expression is a single unit of JavaScript code that the JavaScript engine can evaluate, and return a value.</p>
<p>Expressions can vary in complexity.</p>
<p>We start from the very simple ones, called primary expressions:</p>
<pre><code class="lang-js"><span class="hljs-number">2</span>
<span class="hljs-number">0.02</span>
<span class="hljs-string">'something'</span>
<span class="hljs-literal">true</span>
<span class="hljs-literal">false</span>
<span class="hljs-built_in">this</span> <span class="hljs-comment">//the current scope</span>
<span class="hljs-literal">undefined</span>
i <span class="hljs-comment">//where i is a variable or a constant</span>
</code></pre>
<p>Arithmetic expressions are expressions that take a variable and an operator (more on operators soon), and result in a number:</p>
<pre><code class="lang-js"><span class="hljs-number">1</span> / <span class="hljs-number">2</span>
i++
i -= <span class="hljs-number">2</span>
i * <span class="hljs-number">2</span>
</code></pre>
<p>String expressions are expressions that result in a string:</p>
<pre><code class="lang-js"><span class="hljs-string">'A '</span> + <span class="hljs-string">'string'</span>
</code></pre>
<p>Logical expressions make use of logical operators and resolve to a boolean value:</p>
<pre><code class="lang-js">a &amp;&amp; b
a || b
!a
</code></pre>
<p>More advanced expressions involve objects, functions, and arrays, and I'll introduce them later.</p>
<h2 id="heading-operators">Operators</h2>
<p>Operators allow you to get two simple expressions and combine them to form a more complex expression.</p>
<p>We can classify operators based on the operands they work with. Some operators work with 1 operand. Most work with 2 operands. Just one operator works with 3 operands.</p>
<p>In this first introduction to operators, we'll introduce the operators you are most likely familiar with: operators with 2 operands.</p>
<p>I already introduced one when talking about variables: the assignment operator <code>=</code>. You use <code>=</code> to assign a value to a variable:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> b = <span class="hljs-number">2</span>
</code></pre>
<p>Let's now introduce another set of binary operators that you're already familiar with from basic math.</p>
<h3 id="heading-the-addition-operator">The addition operator (+)</h3>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> three = <span class="hljs-number">1</span> + <span class="hljs-number">2</span>
<span class="hljs-keyword">const</span> four = three + <span class="hljs-number">1</span>
</code></pre>
<p>The <code>+</code> operator also does string concatenation if you use strings, so pay attention:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> three = <span class="hljs-number">1</span> + <span class="hljs-number">2</span>
three + <span class="hljs-number">1</span> <span class="hljs-comment">// 4</span>
<span class="hljs-string">'three'</span> + <span class="hljs-number">1</span> <span class="hljs-comment">// three1</span>
</code></pre>
<h3 id="heading-the-subtraction-operator">The subtraction operator (-)</h3>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> two = <span class="hljs-number">4</span> - <span class="hljs-number">2</span>
</code></pre>
<h3 id="heading-the-division-operator">The division operator (/)</h3>
<p>Returns the quotient of the first operator and the second:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> result = <span class="hljs-number">20</span> / <span class="hljs-number">5</span> <span class="hljs-comment">//result === 4</span>
<span class="hljs-keyword">const</span> result = <span class="hljs-number">20</span> / <span class="hljs-number">7</span> <span class="hljs-comment">//result === 2.857142857142857</span>
</code></pre>
<p>If you divide by zero, JavaScript does not raise any error but returns the <code>Infinity</code> value (or <code>-Infinity</code> if the value is negative).</p>
<pre><code class="lang-js"><span class="hljs-number">1</span> / <span class="hljs-number">0</span> <span class="hljs-comment">//Infinity</span>
<span class="hljs-number">-1</span> / <span class="hljs-number">0</span> <span class="hljs-comment">//-Infinity</span>
</code></pre>
<h3 id="heading-the-remainder-operator">The remainder operator (%)</h3>
<p>The remainder is a very useful calculation in many use cases:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> result = <span class="hljs-number">20</span> % <span class="hljs-number">5</span> <span class="hljs-comment">//result === 0</span>
<span class="hljs-keyword">const</span> result = <span class="hljs-number">20</span> % <span class="hljs-number">7</span> <span class="hljs-comment">//result === 6</span>
</code></pre>
<p>A remainder by zero is always <code>NaN</code>, a special value that means "Not a Number":</p>
<pre><code class="lang-js"><span class="hljs-number">1</span> % <span class="hljs-number">0</span> <span class="hljs-comment">//NaN</span>
<span class="hljs-number">-1</span> % <span class="hljs-number">0</span> <span class="hljs-comment">//NaN</span>
</code></pre>
<h3 id="heading-the-multiplication-operator">The multiplication operator (*)</h3>
<p>Multiply two numbers</p>
<pre><code class="lang-js"><span class="hljs-number">1</span> * <span class="hljs-number">2</span> <span class="hljs-comment">//2</span>
<span class="hljs-number">-1</span> * <span class="hljs-number">2</span> <span class="hljs-comment">//-2</span>
</code></pre>
<h3 id="heading-the-exponentiation-operator">The exponentiation operator (**)</h3>
<p>Raise the first operand to the power of the second operand</p>
<pre><code class="lang-js"><span class="hljs-number">1</span> ** <span class="hljs-number">2</span> <span class="hljs-comment">//1</span>
<span class="hljs-number">2</span> ** <span class="hljs-number">1</span> <span class="hljs-comment">//2</span>
<span class="hljs-number">2</span> ** <span class="hljs-number">2</span> <span class="hljs-comment">//4</span>
<span class="hljs-number">2</span> ** <span class="hljs-number">8</span> <span class="hljs-comment">//256</span>
<span class="hljs-number">8</span> ** <span class="hljs-number">2</span> <span class="hljs-comment">//64</span>
</code></pre>
<h2 id="heading-precedence-rules">Precedence rules</h2>
<p>Every complex statement with multiple operators in the same line will introduce precedence problems.</p>
<p>Take this example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> a = <span class="hljs-number">1</span> * <span class="hljs-number">2</span> + <span class="hljs-number">5</span> / <span class="hljs-number">2</span> % <span class="hljs-number">2</span>
</code></pre>
<p>The result is 2.5, but why?</p>
<p>What operations are executed first, and which need to wait?</p>
<p>Some operations have more precedence than the others. The precedence rules are listed in this table:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Operator</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>*</code> <code>/</code> <code>%</code></td><td>multiplication/division</td></tr>
<tr>
<td><code>+</code> <code>-</code></td><td>addition/subtraction</td></tr>
<tr>
<td><code>=</code></td><td>assignment</td></tr>
</tbody>
</table>
</div><p>Operations on the same level (like <code>+</code> and <code>-</code>) are executed in the order they are found, from left to right.</p>
<p>Following these rules, the operation above can be solved in this way:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> a = <span class="hljs-number">1</span> * <span class="hljs-number">2</span> + <span class="hljs-number">5</span> / <span class="hljs-number">2</span> % <span class="hljs-number">2</span>
<span class="hljs-keyword">let</span> a = <span class="hljs-number">2</span> + <span class="hljs-number">5</span> / <span class="hljs-number">2</span> % <span class="hljs-number">2</span>
<span class="hljs-keyword">let</span> a = <span class="hljs-number">2</span> + <span class="hljs-number">2.5</span> % <span class="hljs-number">2</span>
<span class="hljs-keyword">let</span> a = <span class="hljs-number">2</span> + <span class="hljs-number">0.5</span>
<span class="hljs-keyword">let</span> a = <span class="hljs-number">2.5</span>
</code></pre>
<h2 id="heading-comparison-operators">Comparison operators</h2>
<p>After assignment and math operators, the third set of operators I want to introduce is conditional operators.</p>
<p>You can use the following operators to compare two numbers, or two strings.</p>
<p>Comparison operators always return a boolean, a value that's <code>true</code> or <code>false</code>).</p>
<p>Those are <strong>disequality comparison operators</strong>:</p>
<ul>
<li><p><code>&lt;</code> means "less than"</p>
</li>
<li><p><code>&lt;=</code> means "less than or equal to"</p>
</li>
<li><p><code>&gt;</code> means "greater than"</p>
</li>
<li><p><code>&gt;=</code> means "greater than or equal to"</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> a = <span class="hljs-number">2</span>
a &gt;= <span class="hljs-number">1</span> <span class="hljs-comment">//true</span>
</code></pre>
<p>In addition to those, we have 4 <strong>equality operators</strong>. They accept two values, and return a boolean:</p>
<ul>
<li><p><code>===</code> checks for equality</p>
</li>
<li><p><code>!==</code> checks for inequality</p>
</li>
</ul>
<p>Note that we also have <code>==</code> and <code>!=</code> in JavaScript, but I highly suggest to only use <code>===</code> and <code>!==</code> because they can prevent some subtle problems.</p>
<h2 id="heading-conditionals">Conditionals</h2>
<p>With the comparison operators in place, we can talk about conditionals.</p>
<p>An <code>if</code> statement is used to make the program take a route, or another, depending on the result of an expression evaluation.</p>
<p>This is the simplest example, which always executes:</p>
<pre><code class="lang-js"><span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
  <span class="hljs-comment">//do something</span>
}
</code></pre>
<p>on the contrary, this is never executed:</p>
<pre><code class="lang-js"><span class="hljs-keyword">if</span> (<span class="hljs-literal">false</span>) {
  <span class="hljs-comment">//do something (? never ?)</span>
}
</code></pre>
<p>The conditional checks the expression you pass to it for a true or false value. If you pass a number, that always evaluates to true unless it's 0. If you pass a string, it always evaluates to true unless it's an empty string. Those are general rules of casting types to a boolean.</p>
<p>Did you notice the curly braces? That is called a <strong>block</strong>, and it is used to group a list of different statements.</p>
<p>A block can be put wherever you can have a single statement. And if you have a single statement to execute after the conditionals, you can omit the block, and just write the statement:</p>
<pre><code class="lang-js"><span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) doSomething()
</code></pre>
<p>But I always like to use curly braces to be more clear.</p>
<p>You can provide a second part to the <code>if</code> statement: <code>else</code>.</p>
<p>You attach a statement that is going to be executed if the <code>if</code> condition is false:</p>
<pre><code class="lang-js"><span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
  <span class="hljs-comment">//do something</span>
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">//do something else</span>
}
</code></pre>
<p>Since <code>else</code> accepts a statement, you can nest another if/else statement inside it:</p>
<pre><code class="lang-js"><span class="hljs-keyword">if</span> (a === <span class="hljs-literal">true</span>) {
  <span class="hljs-comment">//do something</span>
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (b === <span class="hljs-literal">true</span>) {
  <span class="hljs-comment">//do something else</span>
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">//fallback</span>
}
</code></pre>
<h2 id="heading-arrays">Arrays</h2>
<p>An array is a collection of elements.</p>
<p>Arrays in JavaScript are not a <em>type</em> on their own.</p>
<p>Arrays are <strong>objects</strong>.</p>
<p>We can initialize an empty array in these 2 different ways:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> a = []
<span class="hljs-keyword">const</span> a = <span class="hljs-built_in">Array</span>()
</code></pre>
<p>The first is using the <strong>array literal syntax</strong>. The second uses the Array built-in function.</p>
<p>You can pre-fill the array using this syntax:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> a = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
<span class="hljs-keyword">const</span> a = <span class="hljs-built_in">Array</span>.of(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
</code></pre>
<p>An array can hold any value, even values of different types:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> a = [<span class="hljs-number">1</span>, <span class="hljs-string">'Flavio'</span>, [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>]]
</code></pre>
<p>Since we can add an array into an array, we can create multi-dimensional arrays, which have very useful applications (e.g. a matrix):</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> matrix = [
  [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>],
  [<span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>],
  [<span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>]
]

matrix[<span class="hljs-number">0</span>][<span class="hljs-number">0</span>] <span class="hljs-comment">//1</span>
matrix[<span class="hljs-number">2</span>][<span class="hljs-number">0</span>] <span class="hljs-comment">//7</span>
</code></pre>
<p>You can access any element of the array by referencing its index, which starts from zero:</p>
<pre><code class="lang-js">a[<span class="hljs-number">0</span>] <span class="hljs-comment">//1</span>
a[<span class="hljs-number">1</span>] <span class="hljs-comment">//2</span>
a[<span class="hljs-number">2</span>] <span class="hljs-comment">//3</span>
</code></pre>
<p>You can initialize a new array with a set of values using this syntax, which first initializes an array of 12 elements, and fills each element with the number <code>0</code>:</p>
<pre><code class="lang-js"><span class="hljs-built_in">Array</span>(<span class="hljs-number">12</span>).fill(<span class="hljs-number">0</span>)
</code></pre>
<p>You can get the number of elements in the array by checking its <code>length</code> property:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> a = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
a.length <span class="hljs-comment">//3</span>
</code></pre>
<p>Note that you can set the length of the array. If you assign a bigger number than the arrays current capacity, nothing happens. If you assign a smaller number, the array is cut at that position:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> a = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
a <span class="hljs-comment">//[ 1, 2, 3 ]</span>
a.length = <span class="hljs-number">2</span>
a <span class="hljs-comment">//[ 1, 2 ]</span>
</code></pre>
<h3 id="heading-how-to-add-an-item-to-an-array">How to add an item to an array</h3>
<p>We can add an element at the end of an array using the <code>push()</code> method:</p>
<pre><code class="lang-js">a.push(<span class="hljs-number">4</span>)
</code></pre>
<p>We can add an element at the beginning of an array using the <code>unshift()</code> method:</p>
<pre><code class="lang-js">a.unshift(<span class="hljs-number">0</span>)
a.unshift(<span class="hljs-number">-2</span>, <span class="hljs-number">-1</span>)
</code></pre>
<h3 id="heading-how-to-remove-an-item-from-an-array">How to remove an item from an array</h3>
<p>We can remove an item from the end of an array using the <code>pop()</code> method:</p>
<pre><code class="lang-js">a.pop()
</code></pre>
<p>We can remove an item from the beginning of an array using the <code>shift()</code> method:</p>
<pre><code class="lang-js">a.shift()
</code></pre>
<h3 id="heading-how-to-join-two-or-more-arrays">How to join two or more arrays</h3>
<p>You can join multiple arrays by using <code>concat()</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> a = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
<span class="hljs-keyword">const</span> b = [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
<span class="hljs-keyword">const</span> c = a.concat(b) <span class="hljs-comment">//[1,2,3,4]</span>
a <span class="hljs-comment">//[1,2]</span>
b <span class="hljs-comment">//[3,4]</span>
</code></pre>
<p>You can also use the <strong>spread</strong> operator (<code>...</code>) in this way:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> a = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
<span class="hljs-keyword">const</span> b = [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
<span class="hljs-keyword">const</span> c = [...a, ...b]
c <span class="hljs-comment">//[1,2,3,4]</span>
</code></pre>
<h3 id="heading-how-to-find-a-specific-item-in-the-array">How to find a specific item in the array</h3>
<p>You can use the <code>find()</code> method of an array:</p>
<pre><code class="lang-js">a.find(<span class="hljs-function">(<span class="hljs-params">element, index, array</span>) =&gt;</span> {
  <span class="hljs-comment">//return true or false</span>
})
</code></pre>
<p>Returns the first item that returns true, and returns <code>undefined</code> if the element is not found.</p>
<p>A commonly used syntax is:</p>
<pre><code class="lang-js">a.find(<span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> x.id === my_id)
</code></pre>
<p>The above line will return the first element in the array that has <code>id === my_id</code>.</p>
<p><code>findIndex()</code> works similarly to <code>find()</code>, but returns the index of the first item that returns true, and if not found, it returns <code>undefined</code>:</p>
<pre><code class="lang-js">a.findIndex(<span class="hljs-function">(<span class="hljs-params">element, index, array</span>) =&gt;</span> {
  <span class="hljs-comment">//return true or false</span>
})
</code></pre>
<p>Another method is <code>includes()</code>:</p>
<pre><code class="lang-js">a.includes(value)
</code></pre>
<p>Returns true if <code>a</code> contains <code>value</code>.</p>
<pre><code class="lang-js">a.includes(value, i)
</code></pre>
<p>Returns true if <code>a</code> contains <code>value</code> after the position <code>i</code>.</p>
<h2 id="heading-strings">Strings</h2>
<p>A string is a sequence of characters.</p>
<p>It can be also defined as a string literal, which is enclosed in quotes or double quotes:</p>
<pre><code class="lang-js"><span class="hljs-string">'A string'</span>
<span class="hljs-string">"Another string"</span>
</code></pre>
<p>I personally prefer single quotes all the time, and use double quotes only in HTML to define attributes.</p>
<p>You assign a string value to a variable like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> name = <span class="hljs-string">'Flavio'</span>
</code></pre>
<p>You can determine the length of a string using the <code>length</code> property of it:</p>
<pre><code class="lang-js"><span class="hljs-string">'Flavio'</span>.length <span class="hljs-comment">//6</span>
<span class="hljs-keyword">const</span> name = <span class="hljs-string">'Flavio'</span>
name.length <span class="hljs-comment">//6</span>
</code></pre>
<p>This is an empty string: <code>''</code>. Its length property is 0:</p>
<pre><code class="lang-js"><span class="hljs-string">''</span>.length <span class="hljs-comment">//0</span>
</code></pre>
<p>Two strings can be joined using the <code>+</code> operator:</p>
<pre><code class="lang-js"><span class="hljs-string">"A "</span> + <span class="hljs-string">"string"</span>
</code></pre>
<p>You can use the <code>+</code> operator to <em>interpolate</em> variables:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> name = <span class="hljs-string">'Flavio'</span>
<span class="hljs-string">"My name is "</span> + name <span class="hljs-comment">//My name is Flavio</span>
</code></pre>
<p>Another way to define strings is to use template literals, defined inside backticks. They are especially useful to make multiline strings much simpler. With single or double quotes you can't define a multiline string easily - you'd need to use escaping characters.</p>
<p>Once a template literal is opened with the backtick, you just press enter to create a new line, with no special characters, and it's rendered as-is:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> string = <span class="hljs-string">`Hey
this

string
is awesome!`</span>
</code></pre>
<p>Template literals are also great because they provide an easy way to interpolate variables and expressions into strings.</p>
<p>You do so by using the <code>${...}</code> syntax:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> <span class="hljs-keyword">var</span> = <span class="hljs-string">'test'</span>
<span class="hljs-keyword">const</span> string = <span class="hljs-string">`something <span class="hljs-subst">${<span class="hljs-keyword">var</span>}</span>`</span> 
<span class="hljs-comment">//something test</span>
</code></pre>
<p>inside the <code>${}</code> you can add anything, even expressions:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> string = <span class="hljs-string">`something <span class="hljs-subst">${<span class="hljs-number">1</span> + <span class="hljs-number">2</span> + <span class="hljs-number">3</span>}</span>`</span>
<span class="hljs-keyword">const</span> string2 = <span class="hljs-string">`something 
  <span class="hljs-subst">${foo() ? <span class="hljs-string">'x'</span> : <span class="hljs-string">'y'</span>}</span>`</span>
</code></pre>
<h2 id="heading-loops">Loops</h2>
<p>Loops are one of the main control structures of JavaScript.</p>
<p>With a loop we can automate and repeat a block of code however many times we want it to run, even indefinitely.</p>
<p>JavaScript provides many way to iterate through loops.</p>
<p>I want to focus on 3 ways:</p>
<ul>
<li><p>while loops</p>
</li>
<li><p>for loops</p>
</li>
<li><p>for..of loops</p>
</li>
</ul>
<h3 id="heading-while"><code>while</code></h3>
<p>The while loop is the simplest looping structure that JavaScript provides us.</p>
<p>We add a condition after the <code>while</code> keyword, and we provide a block that is run until the condition evaluates to <code>true</code>.</p>
<p>Example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> list = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>]
<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>
<span class="hljs-keyword">while</span> (i &lt; list.length) {
  <span class="hljs-built_in">console</span>.log(list[i]) <span class="hljs-comment">//value</span>
  <span class="hljs-built_in">console</span>.log(i) <span class="hljs-comment">//index</span>
  i = i + <span class="hljs-number">1</span>
}
</code></pre>
<p>You can interrupt a <code>while</code> loop using the <code>break</code> keyword, like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) {
  <span class="hljs-keyword">if</span> (somethingIsTrue) <span class="hljs-keyword">break</span>
}
</code></pre>
<p>and if you decide that in the middle of a loop you want to skip the current iteration, you can jump to the next iteration using <code>continue</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) {
  <span class="hljs-keyword">if</span> (somethingIsTrue) <span class="hljs-keyword">continue</span>

  <span class="hljs-comment">//do something else</span>
}
</code></pre>
<p>Very similar to <code>while</code>, we have <code>do..while</code> loops. It's basically the same as <code>while</code>, except the condition is evaluated <em>after</em> the code block is executed.</p>
<p>This means the block is always executed <em>at least once</em>.</p>
<p>Example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> list = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>]
<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>
<span class="hljs-keyword">do</span> {
  <span class="hljs-built_in">console</span>.log(list[i]) <span class="hljs-comment">//value</span>
  <span class="hljs-built_in">console</span>.log(i) <span class="hljs-comment">//index</span>
  i = i + <span class="hljs-number">1</span>
} <span class="hljs-keyword">while</span> (i &lt; list.length)
</code></pre>
<h3 id="heading-for"><code>for</code></h3>
<p>The second very important looping structure in JavaScript is the <strong>for loop</strong>.</p>
<p>We use the <code>for</code> keyword and we pass a set of 3 instructions: the initialization, the condition, and the increment part.</p>
<p>Example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> list = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>]

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; list.length; i++) {
  <span class="hljs-built_in">console</span>.log(list[i]) <span class="hljs-comment">//value</span>
  <span class="hljs-built_in">console</span>.log(i) <span class="hljs-comment">//index</span>
}
</code></pre>
<p>Just like with <code>while</code> loops, you can interrupt a <code>for</code> loop using <code>break</code> and you can fast forward to the next iteration of a <code>for</code> loop using <code>continue</code>.</p>
<h3 id="heading-forof"><code>for...of</code></h3>
<p>This loop is relatively recent (introduced in 2015) and it's a simplified version of the <code>for</code> loop:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> list = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>]

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> value <span class="hljs-keyword">of</span> list) {
  <span class="hljs-built_in">console</span>.log(value) <span class="hljs-comment">//value</span>
}
</code></pre>
<h2 id="heading-functions">Functions</h2>
<p>In any moderately complex JavaScript program, everything happens inside functions.</p>
<p>Functions are a core, essential part of JavaScript.</p>
<p>What is a function?</p>
<p>A function is a block of code, self contained.</p>
<p>Here's a <strong>function declaration</strong>:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// do something</span>
}
</code></pre>
<p>A function can be run any time you want by invoking it, like this:</p>
<pre><code class="lang-js">getData()
</code></pre>
<p>A function can have one or more argument:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">//do something</span>
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params">color</span>) </span>{
  <span class="hljs-comment">//do something</span>
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params">color, age</span>) </span>{
  <span class="hljs-comment">//do something</span>
}
</code></pre>
<p>When we can pass an argument, we invoke the function passing parameters:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params">color, age</span>) </span>{
  <span class="hljs-comment">//do something</span>
}

getData(<span class="hljs-string">'green'</span>, <span class="hljs-number">24</span>)
getData(<span class="hljs-string">'black'</span>)
</code></pre>
<p>Note that in the second invokation I passed the <code>black</code> string parameter as the <code>color</code> argument, but no <code>age</code>. In this case, <code>age</code> inside the function is <code>undefined</code>.</p>
<p>We can check if a value is not undefined using this conditional:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params">color, age</span>) </span>{
  <span class="hljs-comment">//do something</span>
  <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> age !== <span class="hljs-string">'undefined'</span>) {
    <span class="hljs-comment">//...</span>
  }
}
</code></pre>
<p><code>typeof</code> is a unary operator that allows us to check the type of a variable.</p>
<p>You can also check in this way:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params">color, age</span>) </span>{
  <span class="hljs-comment">//do something</span>
  <span class="hljs-keyword">if</span> (age) {
    <span class="hljs-comment">//...</span>
  }
}
</code></pre>
<p>Although the conditional will also be true if <code>age</code> is <code>null</code>, <code>0</code> or an empty string.</p>
<p>You can have default values for parameters, in case they are not passed:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params">color = <span class="hljs-string">'black'</span>, age = <span class="hljs-number">25</span></span>) </span>{
  <span class="hljs-comment">//do something</span>
}
</code></pre>
<p>You can pass any value as a parameter: numbers, strings, booleans, arrays, objects, and also functions.</p>
<p>A function has a return value. By default a function returns <code>undefined</code>, unless you add a <code>return</code> keyword with a value:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// do something</span>
  <span class="hljs-keyword">return</span> <span class="hljs-string">'hi!'</span>
}
</code></pre>
<p>We can assign this return value to a variable when we invoke the function:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// do something</span>
  <span class="hljs-keyword">return</span> <span class="hljs-string">'hi!'</span>
}

<span class="hljs-keyword">let</span> result = getData()
</code></pre>
<p><code>result</code> now holds a string with the the <code>hi!</code> value.</p>
<p>You can only return one value.</p>
<p>To return multiple values, you can return an object, or an array, like this:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> [<span class="hljs-string">'Flavio'</span>, <span class="hljs-number">37</span>]
}

<span class="hljs-keyword">let</span> [name, age] = getData()
</code></pre>
<p>Functions can be defined inside other functions:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> getData = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> dosomething = <span class="hljs-function">() =&gt;</span> {}
  dosomething()
  <span class="hljs-keyword">return</span> <span class="hljs-string">'test'</span>
}
</code></pre>
<p>The nested function cannot be called from the outside of the enclosing function.</p>
<p>You can return a function from a function, too.</p>
<h2 id="heading-arrow-functions">Arrow functions</h2>
<p>Arrow functions are a recent introduction to JavaScript.</p>
<p>They are very often used instead of "regular" functions, the ones I described in the previous chapter. You'll find both forms used everywhere.</p>
<p>Visually, they allows you to write functions with a shorter syntax, from:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">//...</span>
}
</code></pre>
<p>to</p>
<pre><code class="lang-js">() =&gt; {
  <span class="hljs-comment">//...</span>
}
</code></pre>
<p>But.. notice that we don't have a name here.</p>
<p>Arrow functions are anonymous. We must assign them to a variable.</p>
<p>We can assign a regular function to a variable, like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> getData = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">//...</span>
}
</code></pre>
<p>When we do so, we can remove the name from the function:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> getData = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">//...</span>
}
</code></pre>
<p>and invoke the function using the variable name:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> getData = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">//...</span>
}
getData()
</code></pre>
<p>That's the same thing we do with arrow functions:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> getData = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">//...</span>
}
getData()
</code></pre>
<p>If the function body contains just a single statement, you can omit the parentheses and write everything on a single line:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> getData = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'hi!'</span>)
</code></pre>
<p>Parameters are passed in the parentheses:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> getData = <span class="hljs-function">(<span class="hljs-params">param1, param2</span>) =&gt;</span> 
  <span class="hljs-built_in">console</span>.log(param1, param2)
</code></pre>
<p>If you have one (and just one) parameter, you could omit the parentheses completely:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> getData = <span class="hljs-function"><span class="hljs-params">param</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(param)
</code></pre>
<p>Arrow functions allow you to have an implicit return - values are returned without having to use the <code>return</code> keyword.</p>
<p>It works when there is a one-line statement in the function body:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> getData = <span class="hljs-function">() =&gt;</span> <span class="hljs-string">'test'</span>

getData() <span class="hljs-comment">//'test'</span>
</code></pre>
<p>Like with regular functions, we can have default values for parameters in case they are not passed:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> getData = <span class="hljs-function">(<span class="hljs-params">color = <span class="hljs-string">'black'</span>, 
                 age = <span class="hljs-number">2</span></span>) =&gt;</span> {
  <span class="hljs-comment">//do something</span>
}
</code></pre>
<p>And like regular functions, we can only return one value.</p>
<p>Arrow functions can also contain other arrow functions, or even regular functions.</p>
<p>The two types of functions are very similar, so you might ask why arrow functions were introduced. The big difference with regular functions is when they are used as object methods. This is something we'll soon look into.</p>
<h2 id="heading-objects">Objects</h2>
<p>Any value that's not of a primitive type (a string, a number, a boolean, a symbol, null, or undefined) is an <strong>object</strong>.</p>
<p>Here's how we define an object:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> car = {

}
</code></pre>
<p>This is the <strong>object literal</strong> syntax, which is one of the nicest things in JavaScript.</p>
<p>You can also use the <code>new Object</code> syntax:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> car = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Object</span>()
</code></pre>
<p>Another syntax is to use <code>Object.create()</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> car = <span class="hljs-built_in">Object</span>.create()
</code></pre>
<p>You can also initialize an object using the <code>new</code> keyword before a function with a capital letter. This function serves as a constructor for that object. In there, we can initialize the arguments we receive as parameters, to setup the initial state of the object:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Car</span>(<span class="hljs-params">brand, model</span>) </span>{
  <span class="hljs-built_in">this</span>.brand = brand
  <span class="hljs-built_in">this</span>.model = model
}
</code></pre>
<p>We initialize a new object using:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myCar = <span class="hljs-keyword">new</span> Car(<span class="hljs-string">'Ford'</span>, <span class="hljs-string">'Fiesta'</span>)
myCar.brand <span class="hljs-comment">//'Ford'</span>
myCar.model <span class="hljs-comment">//'Fiesta'</span>
</code></pre>
<p>Objects are <strong>always passed by reference</strong>.</p>
<p>If you assign a variable the same value of another, if it's a primitive type like a number or a string, they are passed by value:</p>
<p>Take this example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> age = <span class="hljs-number">36</span>
<span class="hljs-keyword">let</span> myAge = age
myAge = <span class="hljs-number">37</span>
age <span class="hljs-comment">//36</span>
</code></pre>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> car = {
  <span class="hljs-attr">color</span>: <span class="hljs-string">'blue'</span>
}
<span class="hljs-keyword">const</span> anotherCar = car
anotherCar.color = <span class="hljs-string">'yellow'</span>
car.color <span class="hljs-comment">//'yellow'</span>
</code></pre>
<p>Even arrays or functions are, under the hood, objects, so it's very important to understand how they work.</p>
<h2 id="heading-object-properties">Object Properties</h2>
<p>Objects have <strong>properties</strong>, which are composed by a label associated with a value.</p>
<p>The value of a property can be of any type, which means that it can be an array, a function, and it can even be an object, as objects can nest other objects.</p>
<p>This is the object literal syntax we saw in the previous chapter:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> car = {

}
</code></pre>
<p>We can define a <code>color</code> property in this way:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> car = {
  <span class="hljs-attr">color</span>: <span class="hljs-string">'blue'</span>
}
</code></pre>
<p>Here we have a <code>car</code> object with a property named <code>color</code>, with value <code>blue</code>.</p>
<p>Labels can be any string, but beware of special characters - if I wanted to include a character not valid as a variable name in the property name, I would have had to use quotes around it:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> car = {
  <span class="hljs-attr">color</span>: <span class="hljs-string">'blue'</span>,
  <span class="hljs-string">'the color'</span>: <span class="hljs-string">'blue'</span>
}
</code></pre>
<p>Invalid variable name characters include spaces, hyphens, and other special characters.</p>
<p>As you can see, when we have multiple properties, we separate each property with a comma.</p>
<p>We can retrieve the value of a property using 2 different syntaxes.</p>
<p>The first is <strong>dot notation</strong>:</p>
<pre><code class="lang-js">car.color <span class="hljs-comment">//'blue'</span>
</code></pre>
<p>The second (which is the only one we can use for properties with invalid names), is to use square brackets:</p>
<pre><code class="lang-js">car[<span class="hljs-string">'the color'</span>] <span class="hljs-comment">//'blue'</span>
</code></pre>
<p>If you access a nonexistant property, you'll get the <code>undefined</code> value:</p>
<pre><code class="lang-js">car.brand <span class="hljs-comment">//undefined</span>
</code></pre>
<p>As mentioned before, objects can have nested objects as properties:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> car = {
  <span class="hljs-attr">brand</span>: {
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Ford'</span>
  },
  <span class="hljs-attr">color</span>: <span class="hljs-string">'blue'</span>
}
</code></pre>
<p>In this example, you can access the brand name using</p>
<pre><code class="lang-js">car.brand.name
</code></pre>
<p>or</p>
<pre><code class="lang-js">car[<span class="hljs-string">'brand'</span>][<span class="hljs-string">'name'</span>]
</code></pre>
<p>You can set the value of a property when you define the object.</p>
<p>But you can always update it later on:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> car = {
  <span class="hljs-attr">color</span>: <span class="hljs-string">'blue'</span>
}

car.color = <span class="hljs-string">'yellow'</span>
car[<span class="hljs-string">'color'</span>] = <span class="hljs-string">'red'</span>
</code></pre>
<p>And you can also add new properties to an object:</p>
<pre><code class="lang-js">car.model = <span class="hljs-string">'Fiesta'</span>

car.model <span class="hljs-comment">//'Fiesta'</span>
</code></pre>
<p>Given the object</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> car = {
  <span class="hljs-attr">color</span>: <span class="hljs-string">'blue'</span>,
  <span class="hljs-attr">brand</span>: <span class="hljs-string">'Ford'</span>
}
</code></pre>
<p>you can delete a property from this object using</p>
<pre><code class="lang-js"><span class="hljs-keyword">delete</span> car.brand
</code></pre>
<h2 id="heading-object-methods">Object Methods</h2>
<p>I talked about functions in a previous chapter.</p>
<p>Functions can be assigned to a function property, and in this case they are called <strong>methods</strong>.</p>
<p>In this example, the <code>start</code> property has a function assigned, and we can invoke it by using the dot syntax we used for properties, with the parentheses at the end:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> car = {
  <span class="hljs-attr">brand</span>: <span class="hljs-string">'Ford'</span>,
  <span class="hljs-attr">model</span>: <span class="hljs-string">'Fiesta'</span>,
  <span class="hljs-attr">start</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Started'</span>)
  }
}

car.start()
</code></pre>
<p>Inside a method defined using a <code>function() {}</code> syntax we have access to the object instance by referencing <code>this</code>.</p>
<p>In the following example, we have access to the <code>brand</code> and <code>model</code> properties values using <code>this.brand</code> and <code>this.model</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> car = {
  <span class="hljs-attr">brand</span>: <span class="hljs-string">'Ford'</span>,
  <span class="hljs-attr">model</span>: <span class="hljs-string">'Fiesta'</span>,
  <span class="hljs-attr">start</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Started 
      <span class="hljs-subst">${<span class="hljs-built_in">this</span>.brand}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.model}</span>`</span>)
  }
}

car.start()
</code></pre>
<p>It's important to note this distinction between regular functions and arrow functions - we don't have access to <code>this</code> if we use an arrow function:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> car = {
  <span class="hljs-attr">brand</span>: <span class="hljs-string">'Ford'</span>,
  <span class="hljs-attr">model</span>: <span class="hljs-string">'Fiesta'</span>,
  <span class="hljs-attr">start</span>: <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Started 
      <span class="hljs-subst">${<span class="hljs-built_in">this</span>.brand}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.model}</span>`</span>) <span class="hljs-comment">//not going to work</span>
  }
}

car.start()
</code></pre>
<p>This is because <strong>arrow functions are not bound to the object</strong>.</p>
<p>This is the reason why regular functions are often used as object methods.</p>
<p>Methods can accept parameters, like regular functions:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> car = {
  <span class="hljs-attr">brand</span>: <span class="hljs-string">'Ford'</span>,
  <span class="hljs-attr">model</span>: <span class="hljs-string">'Fiesta'</span>,
  <span class="hljs-attr">goTo</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">destination</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Going to <span class="hljs-subst">${destination}</span>`</span>)
  }
}

car.goTo(<span class="hljs-string">'Rome'</span>)
</code></pre>
<h2 id="heading-classes">Classes</h2>
<p>We talked about objects, which are one of the most interesting parts of JavaScript.</p>
<p>In this chapter we'll go up one level by introducing classes.</p>
<p>What are classes? They are a way to define a common pattern for multiple objects.</p>
<p>Let's take a person object:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> person = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">'Flavio'</span>
}
</code></pre>
<p>We can create a class named <code>Person</code> (note the capital <code>P</code>, a convention when using classes), that has a <code>name</code> property:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
  name
}
</code></pre>
<p>Now from this class, we initialize a <code>flavio</code> object like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> flavio = <span class="hljs-keyword">new</span> Person()
</code></pre>
<p><code>flavio</code> is called an <em>instance</em> of the Person class.</p>
<p>We can set the value of the <code>name</code> property:</p>
<pre><code class="lang-js">flavio.name = <span class="hljs-string">'Flavio'</span>
</code></pre>
<p>and we can access it using</p>
<pre><code class="lang-js">flavio.name
</code></pre>
<p>like we do for object properties.</p>
<p>Classes can hold properties, like <code>name</code>, and methods.</p>
<p>Methods are defined in this way:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
  hello() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Hello, I am Flavio'</span>
  }
}
</code></pre>
<p>and we can invoke methods on an instance of the class:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
  hello() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Hello, I am Flavio'</span>
  }
}
<span class="hljs-keyword">const</span> flavio = <span class="hljs-keyword">new</span> Person()
flavio.hello()
</code></pre>
<p>There is a special method called <code>constructor()</code> that we can use to initialize the class properties when we create a new object instance.</p>
<p>It works like this:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
  <span class="hljs-keyword">constructor</span>(name) {
    <span class="hljs-built_in">this</span>.name = name
  }

  hello() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Hello, I am '</span> + <span class="hljs-built_in">this</span>.name + <span class="hljs-string">'.'</span>
  }
}
</code></pre>
<p>Note how we use <code>this</code> to access the object instance.</p>
<p>Now we can instantiate a new object from the class, pass in a string, and when we call <code>hello</code> we'll get a personalized message:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> flavio = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">'flavio'</span>)
flavio.hello() <span class="hljs-comment">//'Hello, I am flavio.'</span>
</code></pre>
<p>When the object is initialized, the <code>constructor</code> method is called with any parameters passed.</p>
<p>Normally methods are defined on the object instance, not on the class.</p>
<p>You can define a method as <code>static</code> to allow it to be executed on the class instead:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
  <span class="hljs-keyword">static</span> genericHello() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Hello'</span>
  }
}

Person.genericHello() <span class="hljs-comment">//Hello</span>
</code></pre>
<p>This is very useful, at times.</p>
<h2 id="heading-inheritance">Inheritance</h2>
<p>A class can <strong>extend</strong> another class, and objects initialized using that class inherit all the methods of both classes.</p>
<p>Suppose we have a class <code>Person</code>:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
  hello() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Hello, I am a Person'</span>
  }
}
</code></pre>
<p>We can define a new class, <code>Programmer</code>, that extends <code>Person</code>:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Programmer</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Person</span> </span>{

}
</code></pre>
<p>Now if we instantiate a new object with the class <code>Programmer</code>, it has access to the <code>hello()</code> method:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> flavio = <span class="hljs-keyword">new</span> Programmer()
flavio.hello() <span class="hljs-comment">//'Hello, I am a Person'</span>
</code></pre>
<p>Inside a child class, you can reference the parent class by calling <code>super()</code>:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Programmer</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Person</span> </span>{
  hello() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">super</span>.hello() + 
      <span class="hljs-string">'. I am also a programmer.'</span>
  }
}

<span class="hljs-keyword">const</span> flavio = <span class="hljs-keyword">new</span> Programmer()
flavio.hello()
</code></pre>
<p>The above program prints <em>Hello, I am a Person. I am also a programmer.</em>.</p>
<h2 id="heading-asynchonous-programming-and-callbacks">Asynchonous Programming and Callbacks</h2>
<p>Most of the time, JavaScript code is run synchronously.</p>
<p>This means that a line of code is executed, then the next one is executed, and so on.</p>
<p>Everything is as you expect, and how it works in most programming languages.</p>
<p>However, there are times when you cannot just wait for a line of code to execute.</p>
<p>You can't just wait 2 seconds for a big file to load, and halt the program completely.</p>
<p>You can't just wait for a network resource to be downloaded before doing something else.</p>
<p>JavaScript solves this problem by using <strong>callbacks</strong>.</p>
<p>One of the simplest examples of how to use callbacks is with timers. Timers are not part of JavaScript, but they are provided by the browser and Node.js. Let me talk about one of the timers we have: <code>setTimeout()</code>.</p>
<p>The <code>setTimeout()</code> function accepts 2 arguments: a function, and a number. The number is the milliseconds that must pass before the function is ran.</p>
<p>Example:</p>
<pre><code class="lang-js"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// runs after 2 seconds</span>
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'inside the function'</span>)
}, <span class="hljs-number">2000</span>)
</code></pre>
<p>The function containing the <code>console.log('inside the function')</code> line will be executed after 2 seconds.</p>
<p>If you add a <code>console.log('before')</code> prior to the function, and <code>console.log('after')</code> after it:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'before'</span>)
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// runs after 2 seconds</span>
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'inside the function'</span>)
}, <span class="hljs-number">2000</span>)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'after'</span>)
</code></pre>
<p>You will see this happening in your console:</p>
<pre><code class="lang-js">before
after
inside the <span class="hljs-function"><span class="hljs-keyword">function</span></span>
</code></pre>
<p>The callback function is executed asynchronously.</p>
<p>This is a very common pattern when working with the file system, the network, events, or the DOM in the browser.</p>
<p>All of the things I mentioned are not "core" JavaScript, so they are not explained in this handbook, but you'll find lots of examples in my other handbooks available at <a target="_blank" href="https://flaviocopes.com">https://flaviocopes.com</a>.</p>
<p>Here's how we can implement callbacks in our code.</p>
<p>We define a function that accepts a <code>callback</code> parameter, which is a function.</p>
<p>When the code is ready to invoke the callback, we invoke it by passing the result:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> doSomething = <span class="hljs-function"><span class="hljs-params">callback</span> =&gt;</span> {
  <span class="hljs-comment">//do things</span>
  <span class="hljs-comment">//do things</span>
  <span class="hljs-keyword">const</span> result = <span class="hljs-comment">/* .. */</span>
  callback(result)
}
</code></pre>
<p>Code using this function would use it like this:</p>
<pre><code class="lang-js">doSomething(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(result)
})
</code></pre>
<h2 id="heading-promises">Promises</h2>
<p>Promises are an alternative way to deal with asynchronous code.</p>
<p>As we saw in the previous chapter, with callbacks we'd be passing a function to another function call that would be called when the function has finished processing.</p>
<p>Like this:</p>
<pre><code class="lang-js">doSomething(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(result)
})
</code></pre>
<p>When the <code>doSomething()</code> code ends, it calls the function received as a parameter:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> doSomething = <span class="hljs-function"><span class="hljs-params">callback</span> =&gt;</span> {
  <span class="hljs-comment">//do things</span>
  <span class="hljs-comment">//do things</span>
  <span class="hljs-keyword">const</span> result = <span class="hljs-comment">/* .. */</span>
  callback(result)
}
</code></pre>
<p>The main problem with this approach is that if we need to use the result of this function in the rest of our code, all our code must be nested inside the callback, and if we have to do 2-3 callbacks we enter in what is usually defined "callback hell" with many levels of functions indented into other functions:</p>
<pre><code class="lang-js">doSomething(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> {
  doSomethingElse(<span class="hljs-function"><span class="hljs-params">anotherResult</span> =&gt;</span> {
    doSomethingElseAgain(<span class="hljs-function"><span class="hljs-params">yetAnotherResult</span> =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(result)
    })
  }) 
})
</code></pre>
<p>Promises are one way to deal with this.</p>
<p>Instead of doing:</p>
<pre><code class="lang-js">doSomething(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(result)
})
</code></pre>
<p>We call a promise-based function in this way:</p>
<pre><code class="lang-js">doSomething()
  .then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(result)
  })
</code></pre>
<p>We first call the function, then we have a <code>then()</code> method that is called when the function ends.</p>
<p>The indentation does not matter, but you'll often use this style for clarity.</p>
<p>It's common to detect errors using a <code>catch()</code> method:</p>
<pre><code class="lang-js">doSomething()
  .then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(result)
  })
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(error)
  })
</code></pre>
<p>Now, to be able to use this syntax, the <code>doSomething()</code> function implementation must be a little bit special. It must use the Promises API.</p>
<p>Instead of declaring it as a normal function:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> doSomething = <span class="hljs-function">() =&gt;</span> {

}
</code></pre>
<p>We declare it as a promise object:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> doSomething = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>()
</code></pre>
<p>and we pass a function in the Promise constructor:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> doSomething = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">() =&gt;</span> {

})
</code></pre>
<p>This function receives 2 parameters. The first is a function we call to resolve the promise, the second a function we call to reject the promise.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> doSomething = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(
  <span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {

})
</code></pre>
<p>Resolving a promise means to complete it successfully (which results in calling the <code>then()</code> method in whatever uses it).</p>
<p>Rejecting a promise means ending it with an error (which results in calling the <code>catch()</code> method in whatever uses it).</p>
<p>Here's how:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> doSomething = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(
  <span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
    <span class="hljs-comment">//some code</span>
    <span class="hljs-keyword">const</span> success = <span class="hljs-comment">/* ... */</span>
    <span class="hljs-keyword">if</span> (success) {
      resolve(<span class="hljs-string">'ok'</span>)
    } <span class="hljs-keyword">else</span> {
      reject(<span class="hljs-string">'this error occurred'</span>)
    }
  }
)
</code></pre>
<p>We can pass a parameter to the resolve and reject functions, of any type we want.</p>
<h2 id="heading-async-and-await">Async and Await</h2>
<p>Async functions are a higher level abstraction of promises.</p>
<p>An async function returns a promise, like in this example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> getData = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> 
      resolve(<span class="hljs-string">'some data'</span>), <span class="hljs-number">2000</span>)
  })
}
</code></pre>
<p>Any code that wants to use this function will use the <code>await</code> keyword right before the function:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> getData()
</code></pre>
<p>and doing so, any data returned by the promise is going to be assigned to the <code>data</code> variable.</p>
<p>In our case, the data is the "some data" string.</p>
<p>With one particular caveat: whenever we use the <code>await</code> keyword, we must do so inside a function defined as <code>async</code>.</p>
<p>Like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> doSomething = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> getData()
  <span class="hljs-built_in">console</span>.log(data)
}
</code></pre>
<p>The async/await duo allows us to have a cleaner code and a simple mental model to work with asynchronous code.</p>
<p>As you can see in the example above, our code looks very simple. Compare it to code using promises, or callback functions.</p>
<p>And this is a very simple example, the major benefits will arise when the code is much more complex.</p>
<p>As an example, here's how you would get a JSON resource using the Fetch API, and parse it, using promises:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> getFirstUserData = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// get users list</span>
  <span class="hljs-keyword">return</span> fetch(<span class="hljs-string">'/users.json'</span>) 
    <span class="hljs-comment">// parse JSON</span>
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json()) 
    <span class="hljs-comment">// pick first user</span>
    .then(<span class="hljs-function"><span class="hljs-params">users</span> =&gt;</span> users[<span class="hljs-number">0</span>]) 
    <span class="hljs-comment">// get user data</span>
    .then(<span class="hljs-function"><span class="hljs-params">user</span> =&gt;</span> 
      fetch(<span class="hljs-string">`/users/<span class="hljs-subst">${user.name}</span>`</span>)) 
    <span class="hljs-comment">// parse JSON</span>
    .then(<span class="hljs-function"><span class="hljs-params">userResponse</span> =&gt;</span> response.json()) 
}

getFirstUserData()
</code></pre>
<p>And here is the same functionality provided using await/async:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> getFirstUserData = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-comment">// get users list</span>
  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'/users.json'</span>) 
  <span class="hljs-comment">// parse JSON</span>
  <span class="hljs-keyword">const</span> users = <span class="hljs-keyword">await</span> response.json() 
  <span class="hljs-comment">// pick first user</span>
  <span class="hljs-keyword">const</span> user = users[<span class="hljs-number">0</span>] 
  <span class="hljs-comment">// get user data</span>
  <span class="hljs-keyword">const</span> userResponse = 
    <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`/users/<span class="hljs-subst">${user.name}</span>`</span>)
  <span class="hljs-comment">// parse JSON</span>
  <span class="hljs-keyword">const</span> userData = <span class="hljs-keyword">await</span> user.json() 
  <span class="hljs-keyword">return</span> userData
}

getFirstUserData()
</code></pre>
<h2 id="heading-variable-scope">Variable scope</h2>
<p>When I introduced variables, I talked about using <code>const</code>, <code>let</code>, and <code>var</code>.</p>
<p>Scope is the set of variables that's visible to a part of the program.</p>
<p>In JavaScript we have a global scope, block scope and function scope.</p>
<p>If a variable is defined outside of a function or block, it's attached to the global object and it has a global scope, which mean it's available in every part of a program.</p>
<p>There is a very important difference between <code>var</code>, <code>let</code> and <code>const</code> declarations.</p>
<p>A variable defined as <code>var</code> inside a function is only visible inside that function, similar to a function's arguments.</p>
<p>A variable defined as <code>const</code> or <code>let</code> on the other hand is only visible inside the <strong>block</strong> where it is defined.</p>
<p>A block is a set of instructions grouped into a pair of curly braces, like the ones we can find inside an <code>if</code> statement, a <code>for</code> loop, or a function.</p>
<p>It's important to understand that a block does not define a new scope for <code>var</code>, but it does for <code>let</code> and <code>const</code>.</p>
<p>This has very practical implications.</p>
<p>Suppose you define a <code>var</code> variable inside an <code>if</code> conditional in a function</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
    <span class="hljs-keyword">var</span> data = <span class="hljs-string">'some data'</span>
    <span class="hljs-built_in">console</span>.log(data) 
  }
}
</code></pre>
<p>If you call this function, you'll get <code>some data</code> printed to the console.</p>
<p>If you try to move console.log(data) after the <code>if</code>, it still works:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
    <span class="hljs-keyword">var</span> data = <span class="hljs-string">'some data'</span>
  }
  <span class="hljs-built_in">console</span>.log(data) 
}
</code></pre>
<p>But if you switch <code>var data</code> to <code>let data</code>:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
    <span class="hljs-keyword">let</span> data = <span class="hljs-string">'some data'</span>
  }
  <span class="hljs-built_in">console</span>.log(data) 
}
</code></pre>
<p>You'll get an error: <code>ReferenceError: data is not defined</code>.</p>
<p>This is because <code>var</code> is function scoped, and there's a special thing happening here called hoisting. In short, the <code>var</code> declaration is moved to the top of the closest function by JavaScript before it runs the code. This is what the function looks like to JS internally, more or less:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> data
  <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
    data = <span class="hljs-string">'some data'</span>
  }
  <span class="hljs-built_in">console</span>.log(data) 
}
</code></pre>
<p>This is why you can also <code>console.log(data)</code> at the top of a function, even before it's declared, and you'll get <code>undefined</code> as a value for that variable:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(data) 
  <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
    <span class="hljs-keyword">var</span> data = <span class="hljs-string">'some data'</span>
  }
}
</code></pre>
<p>but if you switch to <code>let</code>, you'll get an error <code>ReferenceError: data is not defined</code>, because hoisting does not happen to <code>let</code> declarations.</p>
<p><code>const</code> follows the same rules as <code>let</code>: it's block scoped.</p>
<p>It can be tricky at first, but once you realize this difference, then you'll see why <code>var</code> is considered a bad practice nowadays compared to <code>let</code> - they have less moving parts, and their scope is limited to the block, which also makes them very good as loop variables because they cease to exist after a loop has ended:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doLoop</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++) {
    <span class="hljs-built_in">console</span>.log(i)
  }
  <span class="hljs-built_in">console</span>.log(i)
}

doLoop()
</code></pre>
<p>When you exit the loop, <code>i</code> will be a valid variable with value 10.</p>
<p>If you switch to <code>let</code>, when you try to <code>console.log(i)</code> will result in an error <code>ReferenceError: i is not defined</code>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Thanks a lot for reading this book.</p>
<p>I hope it will inspire you to learn more about JavaScript.</p>
<p>For more on JavaScript, check out my blog <a target="_blank" href="https://flaviocopes.com">flaviocopes.com</a>.</p>
<blockquote>
<p>Note: <a target="_blank" href="https://flaviocopes.com/page/javascript-handbook/">You can get a PDF and ePub version of this JavaScript Beginner's Handbook</a></p>
</blockquote>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Create Your First Hugo Blog: a Practical Guide ]]>
                </title>
                <description>
                    <![CDATA[ Hugo is a great tool to use if you want to start a blog. I use Hugo myself for my blog, flaviocopes.com, and I've been using it for more than two years. I have a few reasons for loving Hugo. First of all, it is simple, boring, flexible, and fast. ]]>
                </description>
                <link>https://www.freecodecamp.org/news/your-first-hugo-blog-a-practical-guide/</link>
                <guid isPermaLink="false">66bb5ad3965d5c9ed5487bb7</guid>
                
                    <category>
                        <![CDATA[ blog ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Hugo ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technical writing ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Flavio Copes ]]>
                </dc:creator>
                <pubDate>Wed, 08 Jan 2020 08:44:58 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/01/Screen-Shot-2020-01-03-at-20.05.40.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hugo is a great tool to use if you want to start a blog.</p>
<p>I use Hugo myself for my blog, <a target="_blank" href="https://flaviocopes.com/">flaviocopes.com</a>, and I've been using it for more than two years. I have a few reasons for loving Hugo.</p>
<p>First of all, it is <strong>simple</strong>, <strong>boring</strong>, <strong>flexible</strong>, and <strong>fast</strong>.</p>
<p>The main reason is that it is <strong>simple</strong>. There’s not much you have to learn to get started.</p>
<p>You write content in Markdown, a format that lets me use my favorite editor (Bear) to write posts.</p>
<p>Hugo is <strong>boring</strong>. Don’t get me wrong, this is a very positive thing. As a developer I am tempted to tweak things here and there all the time. There’s no fancy technology underlying Hugo. It’s built using Go, one of the languages I love the most, but that does not mean I want to dive into the internals of Hugo and change how it works.</p>
<p>And it does not surface any cool or next-generation stuff like many JavaScript frameworks tend to do.</p>
<p>Hence it is boring, which gives me a lot of time to do what is really useful when working on a blog: <strong>writing content</strong>. I focus on the content, not on the content container.</p>
<p>That said, Hugo is pretty darn <strong>flexible</strong>. I started my own blog with an open source theme, then changed it completely over time. Sometimes I want to do things in my website that are out of the scope of a simple blog, and Hugo allows me to create those things.</p>
<p>Finally, another reason I love Hugo is that it is <strong>fast</strong>. Why? First, it has Go at the core, which is known to be a very fast language. And in the Go ecosystem, there’s no concept of 100 megabytes dependencies. Things are made to be as fast as possible. Plus, Hugo does not need to do some of the fancy stuff that is needed when using fancy technology. This is a by-product of being boring.</p>
<p>Anyway, enough with words.</p>
<p>Hugo is amazing, especially if you are a developer and you’re willing to write in Markdown. Non-tech people might just refuse to use Markdown, and it’s perfectly understandable.</p>
<p>Also, you have to be prepared for a Git-centric workflow to make things really click.</p>
<p>This is the process for writing a blog: </p>
<ul>
<li>write a post using Markdown, </li>
<li>then commit your changes to a Git repository, most commonly on GitHub, </li>
<li>and then some glue technology deploys the changes on the server that hosts the site.</li>
</ul>
<h2 id="heading-hosting-a-hugo-website">Hosting a Hugo website</h2>
<p>A Hugo blog is completely <strong>static</strong>. This means you don’t need to host your own server, or use a special service for it.</p>
<p>Netlify, Now and GitHub Pages are three great places where you can host a Hugo blog, for free.</p>
<p>The only cost is the one you have to sustain for the domain name. I can’t stress enough the importance of having your own domain name. No <code>.github.io</code> or <code>.netlify.com</code> or <code>.now.sh</code> sites, please.</p>
<p>My own Hugo sites are hosted on Netlify.</p>
<h2 id="heading-choose-a-domain">Choose a domain</h2>
<p>Put your blog under your own domain. Pick one. Use your own name. And use <code>.com</code> or <code>.blog</code>. Don’t try to be clever by using a localized domain - for example, don’t use <code>.io</code>. <code>.com</code> just gives a better impression and it’s reusable for all your future projects, not just to host your blog. I picked that one.</p>
<p>Oh and if you have an old domain lying around, just use that. Why? The older your domain is, the better.</p>
<p>Note on subdomains: every subdomain, to Google, is a different website. So if your domain is <code>flaviocopes.com</code>, and you create your blog in <code>blog.flaviocopes.com</code>, then that’s a completely new website to Google, and it will have its own ranking separate from the main domain.</p>
<p>My suggestion is to avoid subdomains completely.</p>
<h2 id="heading-install-hugo">Install Hugo</h2>
<p>To install Hugo on macOS, from your terminal run</p>
<pre><code class="lang-bash">brew install hugo
</code></pre>
<p><em>The <code>brew</code> command does not exist on your Mac? Check the <a target="_blank" href="https://flaviocopes.com/homebrew/">Homebrew guide</a></em>.</p>
<p>For Windows and Linux, check the <a target="_blank" href="https://gohugo.io/getting-started/installing/">official installation guide</a>.</p>
<h2 id="heading-create-a-hugo-site">Create a Hugo site</h2>
<p>Once Hugo is installed, you can create a Hugo site by running</p>
<pre><code class="lang-bash">hugo new site myblog
</code></pre>
<p>I suggest that you run this into a <code>www</code> folder in your Home directory, because the command will create a new <code>myblog</code> folder where you run it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/hugo-cmd-tool.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-pick-a-theme">Pick a theme</h2>
<p>Now before you can start you need to pick a theme. I wish Hugo included a default theme to make things straightforward, but it does not.</p>
<p>There are a lot of choices on <a target="_blank" href="https://themes.gohugo.io/">https://themes.gohugo.io</a>. My personal recommendation is to start with <a target="_blank" href="https://themes.gohugo.io/ghostwriter/">https://themes.gohugo.io/ghostwriter/</a> and tweak it later.</p>
<p>I also recommend that you avoid the <code>git clone</code> workflow they suggest on that page. You’ll surely be tweaking the theme in the future, and I find it best to have a single repository for both content and theme. It simplifies deployment.</p>
<p>So, go to <a target="_blank" href="https://github.com/jbub/ghostwriter/archive/master.zip">https://github.com/jbub/ghostwriter/archive/master.zip</a> to download the current version of the theme.</p>
<p>Then unpackage it in the <code>themes/ghostwriter</code> folder in your newly created Hugo website:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/ghostwriter-theme.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Notice there is an <code>exampleSite</code> folder in the <code>themes/ghostwriter</code>. Open it, and open its <code>content</code> subfolder. In there, you can see the <code>page</code>, <code>post</code> and <code>project</code> subfolders.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/page-post-and-projects-subfolders.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Copy <code>page</code> and <code>post</code> in the <code>content</code> folder of the site:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/copy-page-and-post-directories.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-the-configuration">The configuration</h2>
<p>The sample data also provide a sample <code>config.toml</code> file in <code>themes/ghostwriter/exampleSite/config.toml</code>. This is the Hugo configuration file, which tells Hugo some details of the configuration without you having to hardcode information in the theme.</p>
<p>I recommend that you not copy that, because it has too many things, and instead use this:</p>
<pre><code class="lang-toml"><span class="hljs-attr">baseurl</span> = <span class="hljs-string">"/"</span>
<span class="hljs-attr">title</span> = <span class="hljs-string">"My blog"</span>
<span class="hljs-attr">theme</span> = <span class="hljs-string">"ghostwriter"</span>

<span class="hljs-section">[Params]</span>
    <span class="hljs-attr">mainSections</span> = [<span class="hljs-string">"post"</span>]
    <span class="hljs-attr">intro</span> = <span class="hljs-literal">true</span>
    <span class="hljs-attr">headline</span> = <span class="hljs-string">"My headline"</span>
    <span class="hljs-attr">description</span> = <span class="hljs-string">"My description"</span>
    <span class="hljs-attr">github</span> = <span class="hljs-string">"https://github.com/XXX"</span>
    <span class="hljs-attr">twitter</span> = <span class="hljs-string">"https://twitter.com/XXX"</span>
    <span class="hljs-attr">email</span> = <span class="hljs-string">"XXX@example.com"</span>
    <span class="hljs-attr">opengraph</span> = <span class="hljs-literal">true</span>
    <span class="hljs-attr">shareTwitter</span> = <span class="hljs-literal">true</span>
    <span class="hljs-attr">dateFormat</span> = <span class="hljs-string">"Mon, Jan 2, 2006"</span>

<span class="hljs-section">[Permalinks]</span>
    <span class="hljs-attr">post</span> = <span class="hljs-string">"/:filename/"</span>
</code></pre>
<p>You can freely customize the information in this file later.</p>
<p>Now from the command line, run:</p>
<pre><code class="lang-bash">hugo serve
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/hugo-serve-output.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Open <code>http://localhost:1313</code> in your browser, and you should be able to see the site live!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/live-site-localhost.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This is the site home page.</p>
<p>There is a list of posts that is taken from the <code>content/post</code> folder of your website:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/content-post-samples.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Click the first, called “Creating a New Theme”:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/creating-a-new-theme-post.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You can open the file <code>content/post/creating-a-new-theme.md</code> to change anything in the post.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/updating-markdown-of-post.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If you save, the website will automatically update with the new content.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/updated-post-live.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This is pretty awesome, right?</p>
<p>You can create a new post by creating a new <code>.md</code> file, prefixing it with anything you want. You can use incremental numbers, if you prefer. Or use a date.</p>
<p>If something doesn't look the way you want, you can open the <code>themes/ghostwriter/layouts</code> folder and tweak it.</p>
<p>The “post” template is defined in <code>themes/ghostwriter/layouts/post/single.html</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/post-template.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Hugo uses Go templates. The syntax can be pretty unfamiliar but the Hugo website does a very good job at explaining them in this <a target="_blank" href="https://gohugo.io/templates/introduction/">Go templates introduction</a>.</p>
<p>However, try to not look at customizing your template now.</p>
<p>If you want to tweak the colors, add a <code>&lt;style&gt;</code> tag with some CSS in the <code>themes/ghostwriter/layouts/partials/header.html</code>.</p>
<p>For example, make links black:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
<span class="hljs-selector-class">.site-title</span> <span class="hljs-selector-tag">a</span>, <span class="hljs-selector-class">.button-square</span> {
    <span class="hljs-attribute">background</span>: black;
}
<span class="hljs-selector-tag">a</span> {
    <span class="hljs-attribute">color</span>: black;
}
</span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
</code></pre>
<p>Focus on the content instead.</p>
<p>Remove the existing files, and write 2-3 posts to start with.</p>
<p>It’s too easy to get trapped in making things perfectly the way you want, but the important thing is the content.</p>
<p>And the cleaner your site is, the better for your readers.</p>
<p>Let me now write a little about deployment.</p>
<h2 id="heading-deploy-the-hugo-site-to-netlify">Deploy the Hugo site to Netlify</h2>
<p>I want to showcase how to deploy a Hugo site in 2 of the services I enjoy the most: Netlify and Now.</p>
<p>First, I’m going to create a GitHub repository to host the site.</p>
<p>I open GitHub Desktop, an app I use every day and that is part of my workflow. It’s the simplest way to use Git.</p>
<p>From the File menu, I pressed the “New Repository” option:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/netlify-new-repository.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The same screen can be generated by simply dragging the <code>myblog</code> folder into the app.</p>
<p>I gave the <code>myblog</code> name to the repository, and picked the correct path for the repo.</p>
<p>The process automatically makes the first commit:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/netlify-first-commit.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now we can click the “Publish repository” button to push the repo to GitHub:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/publish-repo.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You can keep the repo private, of course.</p>
<p>Once the repo is in GitHub:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/private-repo-on-github.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>we can move to Netlify.</p>
<p>From my Netlify dashboard I pressed the “New site from Git” button:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/new-site-from-git.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>I pressed GitHub, authorized Netlify to access my private repositories, then I picked the repo I just created:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/access-to-private-repos.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Netlify automatically identified it as a Hugo repo, and entered the build command automatically:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/netlify-enter-build-command.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Clicking “Deploy site” starts the deploy process:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/netlify-deploy-site.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>On a real site, I would set up a custom domain. Netlify has the option to purchase a domain through them, and it’s a very (VERY) straightforward process. I highly recommend it. The site can be live in just a few minutes after purchasing the domain.</p>
<p>A random <code>.netlify.com</code> subdomain is attached to the site, in this case <code>pedantic-engelbart-500c9a.netlify.com</code>, and HTTPS is automatically enabled.</p>
<p>We can therefore immediately see the site live:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/preview-netlify-subdomain.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now if you try to edit something in your local version, you just push the changes to GitHub, and Netlify will automatically update the site. You can see it building the site in the “Overview” panel of the site:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/automatic-build.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>To learn more about Netlify I recommend that you check out my <a target="_blank" href="https://flaviocopes.com/netlify/">Netlify tutorial</a>.</p>
<h2 id="heading-deploy-the-hugo-site-to-zeit-now">Deploy the Hugo site to Zeit Now</h2>
<p>Another awesome platform you can use for your Hugo blog is Zeit Now.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/zeit-now.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Once you sign up, from the dashboard you press the <strong>New Project</strong> button.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/zeit-now-new-project.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The first time you deploy from GitHub you have to first install the GitHub app by clicking “Install Now For GitHub”:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/zeit-now-install-now-from-github.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This brings you to the GitHub page for the app, where you can authorize it for all your repos, or just for some:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/zeit-now-authorize.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Once you get back, click the “New Project From GitHub” button:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/zeit-now-new-project-from-github.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Select the project and click “Import”:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/zeit-now-import.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In the meantime, go into the main folder of <code>mysite</code> and add a <code>package.json</code> file with this content:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"build"</span>: <span class="hljs-string">"hugo"</span>
  }
}
</code></pre>
<p>This tells Now how to deploy the site.</p>
<p>When you get back to the dashboard, the new deploy should start soon, and you will see the site working live:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/zeit-now-deployed.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/zeit-now-live-site.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Note that in Now you have three URLs you can use to access the site:</p>
<ul>
<li><code>myblog.flaviocopes.now.sh</code></li>
<li><code>myblog-alpha-swart.now.sh</code></li>
<li><code>myblog-git-master.flaviocopes.now.sh</code></li>
</ul>
<p>You can choose the one you prefer.</p>
<p>Plus, each deployment has its own URL, too. In this case I had <code>myblog-h8xks5jhn.now.sh</code> but it changes with every deployment.</p>
<p>And of course you can add your domain, too. Zeit has a great service to purchase your domain directly from them, available at <a target="_blank" href="https://zeit.co/domains">https://zeit.co/domains</a>.</p>
<p>And if you prefer working with the command line, the <code>now</code> command lets you purchase domains from there, as well.</p>
<p>I highly recommend that you check out my <a target="_blank" href="https://flaviocopes.com/zeit-now/">Zeit Now tutorial</a> to learn more about this platform.</p>
<h2 id="heading-wrapping-up">Wrapping up</h2>
<p>I hope this tutorial can give you a little guidance if you are planning to start a new blog. Hugo is my favorite platform, but it's not unique of course. Ghost (the platform powering freeCodeCamp) is great too, along with WordPress of course, and Gatsby.</p>
<p>Pick your favorite. In my opinion the platform does not matter as much as your content does. So, choose one and start writing!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Next.js Handbook – Learn Next.js for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ I wrote this tutorial to help you quickly learn Next.js and get familiar with how it works. It's ideal for you if you have zero to little knowledge of Next.js, you have used React in the past, and you are looking forward diving more into the React ec... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-next-js-handbook/</link>
                <guid isPermaLink="false">66bb5ab1074d8d7b12eae3ad</guid>
                
                    <category>
                        <![CDATA[ frontend ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Next.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Flavio Copes ]]>
                </dc:creator>
                <pubDate>Tue, 19 Nov 2019 08:15:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/11/Group-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>I wrote this tutorial to help you quickly learn Next.js and get familiar with how it works.</p>
<p>It's ideal for you if you have zero to little knowledge of Next.js, you have used React in the past, and you are looking forward diving more into the React ecosystem, in particular server-side rendering.</p>
<p>I find Next.js an awesome tool to create Web Applications, and at the end of this post I hope you'll be as excited about it as I am. And I hope it will help you learn Next.js!</p>
<p><a target="_blank" href="https://flaviocopes.com/page/nextjs-handbook/">Note: you can download a PDF / ePub / Mobi version of this tutorial so you can read it offline</a>!</p>
<h2 id="heading-index">Index</h2>
<ol>
<li><a class="post-section-overview" href="#heading-introduction">Introduction</a></li>
<li><a class="post-section-overview" href="#heading-the-main-features-provided-by-nextjs">The main features provided by Next.js</a></li>
<li><a class="post-section-overview" href="#heading-nextjs-vs-gatsby-vs-create-react-app">Next.js vs Gatsby vs <code>create-react-app</code></a></li>
<li><a class="post-section-overview" href="#heading-how-to-install-nextjs">How to install Next.js</a></li>
<li><a class="post-section-overview" href="#heading-view-source-to-confirm-ssr-is-working">View source to confirm SSR is working</a></li>
<li><a class="post-section-overview" href="#heading-the-app-bundles">The app bundles</a></li>
<li><a class="post-section-overview" href="#heading-whats-that-icon-on-the-bottom-right">What's that icon in the bottom right?</a></li>
<li><a class="post-section-overview" href="#heading-install-the-react-developer-tools">Install the React DevTools</a></li>
<li><a class="post-section-overview" href="#heading-other-debugging-techniques-you-can-use">Other debugging techniques you can use</a></li>
<li><a class="post-section-overview" href="#heading-adding-a-second-page-to-the-site">Adding a second page to the site</a></li>
<li><a class="post-section-overview" href="#heading-linking-the-two-pages">Linking the two pages</a></li>
<li><a class="post-section-overview" href="#heading-dynamic-content-with-the-router">Dynamic content with the router</a></li>
<li><a class="post-section-overview" href="#heading-prefetching">Prefetching</a></li>
<li><a class="post-section-overview" href="#heading-using-the-router-to-detect-the-active-link">Using the router to detect the active link</a></li>
<li><a class="post-section-overview" href="#heading-using-nextrouter">Using <code>next/router</code></a></li>
<li><a class="post-section-overview" href="#heading-feed-data-to-the-components-using-getinitialprops">Feed data to the components using <code>getInitialProps()</code></a></li>
<li><a class="post-section-overview" href="#heading-css">CSS</a></li>
<li><a class="post-section-overview" href="#heading-populating-the-head-tag-with-custom-tags">Populating the head tag with custom tags</a></li>
<li><a class="post-section-overview" href="#heading-adding-a-wrapper-component">Adding a wrapper component</a></li>
<li><a class="post-section-overview" href="#heading-api-routes">API routes</a></li>
<li><a class="post-section-overview" href="#heading-run-code-only-on-the-server-side-or-client-side">Run code on the server side, or on the client side</a></li>
<li><a class="post-section-overview" href="#heading-deploying-the-production-version">Deploying the production version</a></li>
<li><a class="post-section-overview" href="#heading-deploying-on-now">Deploying on Now</a></li>
<li><a class="post-section-overview" href="#heading-analyzing-the-app-bundles">Analyzing the app bundles</a></li>
<li><a class="post-section-overview" href="#heading-lazy-loading-modules">Lazy loading modules</a></li>
<li><a class="post-section-overview" href="#heading-where-to-go-from-here">Where to go from here</a></li>
</ol>
<h2 id="heading-introduction">Introduction</h2>
<p>Working on a modern JavaScript application powered by React is awesome until you realize that there are a couple problems related to rendering all the content on the client-side.</p>
<p>First, the page takes longer to become visible to the user, because before the content loads, all the JavaScript must load, and your application needs to run to determine what to show on the page.</p>
<p>Second, if you are building a publicly available website, you have a content SEO issue. Search engines are getting better at running and indexing JavaScript apps, but it's much better if we can send them content instead of letting them figure it out.</p>
<p>The solution to both of those problems is <strong>server rendering</strong>, also called <strong>static pre-rendering</strong>.</p>
<p><a target="_blank" href="https://nextjs.org">Next.js</a> is one React framework to do all of this in a very simple way, but it's not limited to this. It's advertised by its creators as a <strong>zero-configuration, single-command toolchain for React apps</strong>.</p>
<p>It provides a common structure that allows you to easily build a frontend React application, and transparently handles server-side rendering for you.</p>
<h2 id="heading-the-main-features-provided-by-nextjs">The main features provided by Next.js</h2>
<p>Here is a non-exhaustive list of the main Next.js features:</p>
<h3 id="heading-hot-code-reloading">Hot Code Reloading</h3>
<p>Next.js reloads the page when it detects any change saved to disk.</p>
<h3 id="heading-automatic-routing">Automatic Routing</h3>
<p>Any URL is mapped to the filesystem, to files put in the <code>pages</code> folder, and you don't need any configuration (you have customization options of course).</p>
<h3 id="heading-single-file-components">Single File Components</h3>
<p>Using <code>styled-jsx</code>, completely integrated as built by the same team, it's trivial to add styles scoped to the component.</p>
<h3 id="heading-server-rendering">Server Rendering</h3>
<p>You can render React components on the server side, before sending the HTML to the client.</p>
<h3 id="heading-ecosystem-compatibility">Ecosystem Compatibility</h3>
<p>Next.js plays well with the rest of the JavaScript, Node, and React ecosystem.</p>
<h3 id="heading-automatic-code-splitting">Automatic Code Splitting</h3>
<p>Pages are rendered with just the libraries and JavaScript that they need, no more. Instead of generating one single JavaScript file containing all the app code, the app is broken up automatically by Next.js in several different resources.</p>
<p>Loading a page only loads the JavaScript necessary for that particular page.</p>
<p>Next.js does that by analyzing the resources imported.</p>
<p>If only one of your pages imports the Axios library, for example, that specific page will include the library in its bundle.</p>
<p>This ensures your first page load is as fast as it can be, and only future page loads (if they will ever be triggered) will send the JavaScript needed to the client.</p>
<p>There is one notable exception. Frequently used imports are moved into the main JavaScript bundle if they are used in at least half of the site pages.</p>
<h3 id="heading-prefetching">Prefetching</h3>
<p>The <code>Link</code> component, used to link together different pages, supports a <code>prefetch</code> prop which automatically prefetches page resources (including code missing due to code splitting) in the background.</p>
<h3 id="heading-dynamic-components">Dynamic Components</h3>
<p>You can import JavaScript modules and React Components dynamically.</p>
<h3 id="heading-static-exports">Static Exports</h3>
<p>Using the <code>next export</code> command, Next.js allows you to export a fully static site from your app.</p>
<h3 id="heading-typescript-support">TypeScript Support</h3>
<p>Next.js is written in TypeScript and as such comes with an excellent TypeScript support.</p>
<h2 id="heading-nextjs-vs-gatsby-vs-create-react-app">Next.js vs Gatsby vs <code>create-react-app</code></h2>
<p>Next.js, <a target="_blank" href="https://flaviocopes.com/gatsby/">Gatsby</a>, and <a target="_blank" href="https://flaviocopes.com/react-create-react-app/"><code>create-react-app</code></a> are amazing tools we can use to power our applications.</p>
<p>Let's first say what they have in common. They all have React under the hood, powering the entire development experience. They also abstract <a target="_blank" href="https://flaviocopes.com/webpack/">webpack</a> and all those low level things that we used to configure manually in the good old days.</p>
<p><code>create-react-app</code> does not help you generate a server-side-rendered app easily. Anything that comes with it (SEO, speed...) is only provided by tools like Next.js and Gatsby.</p>
<p><strong>When is Next.js better than Gatsby?</strong></p>
<p>They can both help with <strong>server-side rendering</strong>, but in 2 different ways.</p>
<p>The end result using Gatsby is a static site generator, without a server. You build the site, and then you deploy the result of the build process statically on Netlify or another static hosting site.</p>
<p>Next.js provides a backend that can server side render a response to request, allowing you to create a dynamic website, which means you will deploy it on a platform that can run Node.js.</p>
<p>Next.js <em>can</em> generate a static site too, but I would not say it's its main use case.</p>
<p>If my goal was to build a static site, I'd have a hard time choosing and perhaps Gatsby has a better ecosystem of plugins, including many for blogging in particular.</p>
<p>Gatsby is also heavily based on <a target="_blank" href="https://flaviocopes.com/graphql/">GraphQL</a>, something you might really like or dislike depending on your opinions and needs.</p>
<h2 id="heading-how-to-install-nextjs">How to install Next.js</h2>
<p>To install Next.js, you need to have Node.js installed.</p>
<p>Make sure that you have the latest version of Node. Check with running <code>node -v</code> in your terminal, and compare it to the latest LTS version listed on <a target="_blank" href="https://nodejs.org/">https://nodejs.org/</a>.</p>
<p>After you install Node.js, you will have the <code>npm</code> command available into your command line.</p>
<p>If you have any trouble at this stage, I recommend the following tutorials I wrote for you:</p>
<ul>
<li><a target="_blank" href="https://flaviocopes.com/node-installation/">How to install Node.js</a></li>
<li><a target="_blank" href="https://flaviocopes.com/how-to-update-node/">How to update Node.js</a></li>
<li><a target="_blank" href="https://flaviocopes.com/npm/">An introduction to the npm package manager</a></li>
<li><a target="_blank" href="https://flaviocopes.com/shells/">Unix Shells Tutorial</a></li>
<li><a target="_blank" href="https://flaviocopes.com/macos-terminal/">How to use the macOS terminal</a></li>
<li><a target="_blank" href="https://flaviocopes.com/bash/">The Bash Shell</a></li>
</ul>
<p>Now that you have Node, updated to the latest version, and <code>npm</code>, we're set!</p>
<p>We can choose 2 routes now: using <code>create-next-app</code> or the classic approach which involves installing and setting up a Next app manually.</p>
<h3 id="heading-using-create-next-app">Using create-next-app</h3>
<p>If you're familiar with <a target="_blank" href="https://flaviocopes.com/react-create-react-app/"><code>create-react-app</code></a>, <code>create-next-app</code> is the same thing - except it creates a Next app instead of a React app, as the name implies.</p>
<p>I assume you have already installed Node.js, which, from version 5.2 (2+ years ago at the time of writing), comes with the <a target="_blank" href="https://flaviocopes.com/npx/"><code>npx</code> command</a> bundled. This handy tool lets us download and execute a JavaScript command, and we'll use it like this:</p>
<pre><code class="lang-bash">npx create-next-app
</code></pre>
<p>The command asks the application name (and creates a new folder for you with that name), then downloads all the packages it needs (<code>react</code>, <code>react-dom</code>, <code>next</code>), sets the <code>package.json</code> to:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-14-at-16.46.47.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>and you can immediately run the sample app by running <code>npm run dev</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-14-at-16.46.32.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>And here's the result on <a target="_blank" href="http://localhost:3000">http://localhost:3000</a>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-14-at-16.47.17.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This is the recommended way to start a Next.js application, as it gives you structure and sample code to play with. There's more than just that default sample application; you can use any of the examples stored at <a target="_blank" href="https://github.com/zeit/next.js/tree/canary/examples">https://github.com/zeit/next.js/tree/canary/examples</a> using the <code>--example</code> option. For example try:</p>
<pre><code class="lang-bash">npx create-next-app --example blog-starter
</code></pre>
<p>Which gives you an immediately usable blog instance with syntax highlighting too:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-14-at-17.13.29.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-manually-create-a-nextjs-app">Manually create a Next.js app</h3>
<p>You can avoid <code>create-next-app</code> if you feel like creating a Next app from scratch. Here's how: create an empty folder anywhere you like, for example in your home folder, and go into it:</p>
<pre><code class="lang-sh">mkdir nextjs
<span class="hljs-built_in">cd</span> nextjs
</code></pre>
<p>and create your first Next project directory:</p>
<pre><code class="lang-sh">mkdir firstproject
<span class="hljs-built_in">cd</span> firstproject
</code></pre>
<p>Now use the <code>npm</code> command to initialize it as a Node project:</p>
<pre><code class="lang-sh">npm init -y
</code></pre>
<p>The <code>-y</code> option tells <code>npm</code> to use the default settings for a project, populating a sample <code>package.json</code> file.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-04-at-16.59.21.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now install Next and React:</p>
<pre><code class="lang-sh">npm install next react react-dom
</code></pre>
<p>Your project folder should now have 2 files:</p>
<ul>
<li><code>package.json</code> (<a target="_blank" href="https://flaviocopes.com/package-json/">see my tutorial on it</a>)</li>
<li><code>package-lock.json</code> (<a target="_blank" href="https://flaviocopes.com/package-lock-json/">see my tutorial on package-lock</a>)</li>
</ul>
<p>and the <code>node_modules</code> folder.</p>
<p>Open the project folder using your favorite editor. My favorite editor is <a target="_blank" href="https://flaviocopes.com/vscode/">VS Code</a>. If you have that installed, you can run <code>code .</code> in your terminal to open the current folder in the editor (if the command does not work for you, see <a target="_blank" href="https://code.visualstudio.com/docs/setup/mac#_launching-from-the-command-line">this</a>)</p>
<p>Open <code>package.json</code>, which now has this content:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"firstproject"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"description"</span>: <span class="hljs-string">""</span>,
  <span class="hljs-attr">"main"</span>: <span class="hljs-string">"index.js"</span>,
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"test"</span>: <span class="hljs-string">"echo \"Error: no test specified\" &amp;&amp; exit 1"</span>
  },
  <span class="hljs-attr">"keywords"</span>: [],
  <span class="hljs-attr">"author"</span>: <span class="hljs-string">""</span>,
  <span class="hljs-attr">"license"</span>: <span class="hljs-string">"ISC"</span>,
  <span class="hljs-attr">"dependencies"</span>:  {
    <span class="hljs-attr">"next"</span>: <span class="hljs-string">"^9.1.2"</span>,
    <span class="hljs-attr">"react"</span>: <span class="hljs-string">"^16.11.0"</span>,
    <span class="hljs-attr">"react-dom"</span>: <span class="hljs-string">"^16.11.0"</span>
  }
}
</code></pre>
<p>and replace the <code>scripts</code> section with:</p>
<pre><code class="lang-json"><span class="hljs-string">"scripts"</span>: {
  <span class="hljs-attr">"dev"</span>: <span class="hljs-string">"next"</span>,
  <span class="hljs-attr">"build"</span>: <span class="hljs-string">"next build"</span>,
  <span class="hljs-attr">"start"</span>: <span class="hljs-string">"next start"</span>
}
</code></pre>
<p>to add the Next.js build commands, which we're going to use soon.</p>
<p>Tip: use <code>"dev": "next -p 3001",</code> to change the port and run, in this example, on port 3001.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-04-at-17.01.03.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now create a <code>pages</code> folder, and add an <code>index.js</code> file.</p>
<p>In this file, let's create our first React component.</p>
<p>We're going to use it as the default export:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Index = <span class="hljs-function">() =&gt;</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Home page<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
)

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Index
</code></pre>
<p>Now using the terminal, run <code>npm run dev</code> to start the Next development server.</p>
<p>This will make the app available on port 3000, on localhost.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-04-at-11.24.02.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Open <a target="_blank" href="http://localhost:3000">http://localhost:3000</a> in your browser to see it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-04-at-11.24.23.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-view-source-to-confirm-ssr-is-working">View source to confirm SSR is working</h2>
<p>Let's now check the application is working as we expect it to work. It's a Next.js app, so it should be <strong>server side rendered</strong>.</p>
<p>It's one of the main selling points of Next.js: if we create a site using Next.js, the site pages are rendered on the server, which delivers HTML to the browser.</p>
<p>This has 3 major benefits:</p>
<ul>
<li>The client does not need to instantiate React to render, which makes the site faster to your users.</li>
<li>Search engines will index the pages without needing to run the client-side JavaScript. Something Google started doing, but openly admitted to be a slower process (and you should help Google as much as possible, if you want to rank well).</li>
<li>You can have social media meta tags, useful to add preview images, customize title and description for any of your pages shared on Facebook, Twitter and so on.</li>
</ul>
<p>Let's view the source of the app.<br>Using Chrome you can right-click anywhere in the page, and press <strong>View Page Source</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-04-at-11.33.10.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If you view the source of the page, you'll see the <code>&lt;div&gt;&lt;h1&gt;Home page&lt;/h1&gt;&lt;/div&gt;</code> snippet in the HTML <code>body</code>, along with a bunch of JavaScript files - the app bundles.</p>
<p>We don't need to set up anything, SSR (server-side rendering) is already working for us.</p>
<p>The React app will be launched on the client, and will be the one powering interactions like clicking a link, using client-side rendering. But reloading a page will re-load it from the server. And using Next.js there should be no difference in the result inside the browser - a server-rendered page should look exactly like a client-rendered page.</p>
<h2 id="heading-the-app-bundles">The app bundles</h2>
<p>When we viewed the page source, we saw a bunch of JavaScript files being loaded:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-04-at-11.34.41.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Let's start by putting the code in an <a target="_blank" href="https://htmlformatter.com/">HTML formatter</a> to get it formatted better, so we humans can get a better chance at understanding it:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charSet</span>=<span class="hljs-string">"utf-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width,minimum-scale=1,initial-scale=1"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"next-head-count"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"2"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"preload"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/_next/static/development/pages/index.js?ts=1572863116051"</span> <span class="hljs-attr">as</span>=<span class="hljs-string">"script"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"preload"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/_next/static/development/pages/_app.js?ts=1572863116051"</span> <span class="hljs-attr">as</span>=<span class="hljs-string">"script"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"preload"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/_next/static/runtime/webpack.js?ts=1572863116051"</span> <span class="hljs-attr">as</span>=<span class="hljs-string">"script"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"preload"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/_next/static/runtime/main.js?ts=1572863116051"</span> <span class="hljs-attr">as</span>=<span class="hljs-string">"script"</span> /&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"__next"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Home page<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/_next/static/development/dll/dll_01ec57fc9b90d43b98a8.js?ts=1572863116051"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"__NEXT_DATA__"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"application/json"</span>&gt;</span><span class="javascript">{<span class="hljs-string">"dataManager"</span>:<span class="hljs-string">"[]"</span>,<span class="hljs-string">"props"</span>:{<span class="hljs-string">"pageProps"</span>:{}},<span class="hljs-string">"page"</span>:<span class="hljs-string">"/"</span>,<span class="hljs-string">"query"</span>:{},<span class="hljs-string">"buildId"</span>:<span class="hljs-string">"development"</span>,<span class="hljs-string">"nextExport"</span>:<span class="hljs-literal">true</span>,<span class="hljs-string">"autoExport"</span>:<span class="hljs-literal">true</span>}</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">async</span>=<span class="hljs-string">""</span> <span class="hljs-attr">data-next-page</span>=<span class="hljs-string">"/"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/_next/static/development/pages/index.js?ts=1572863116051"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">async</span>=<span class="hljs-string">""</span> <span class="hljs-attr">data-next-page</span>=<span class="hljs-string">"/_app"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/_next/static/development/pages/_app.js?ts=1572863116051"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/_next/static/runtime/webpack.js?ts=1572863116051"</span> <span class="hljs-attr">async</span>=<span class="hljs-string">""</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/_next/static/runtime/main.js?ts=1572863116051"</span> <span class="hljs-attr">async</span>=<span class="hljs-string">""</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>We have 4 JavaScript files being declared to be preloaded in the <code>head</code>, using <code>rel="preload" as="script"</code>:</p>
<ul>
<li><code>/_next/static/development/pages/index.js</code> (96 LOC)</li>
<li><code>/_next/static/development/pages/_app.js</code> (5900 LOC)</li>
<li><code>/_next/static/runtime/webpack.js</code> (939 LOC)</li>
<li><code>/_next/static/runtime/main.js</code> (12k LOC)</li>
</ul>
<p>This tells the browser to start loading those files as soon as possible, before the normal rendering flow starts. Without those, scripts would be loaded with an additional delay, and this improves the page loading performance.</p>
<p>Then those 4 files are loaded at the end of the <code>body</code>, along with <code>/_next/static/development/dll/dll_01ec57fc9b90d43b98a8.js</code> (31k LOC), and a JSON snippet that sets some defaults for the page data:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"__NEXT_DATA__"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"application/json"</span>&gt;</span><span class="javascript">
{
  <span class="hljs-string">"dataManager"</span>: <span class="hljs-string">"[]"</span>,
  <span class="hljs-string">"props"</span>: {
    <span class="hljs-string">"pageProps"</span>:  {}
  },
  <span class="hljs-string">"page"</span>: <span class="hljs-string">"/"</span>,
  <span class="hljs-string">"query"</span>: {},
  <span class="hljs-string">"buildId"</span>: <span class="hljs-string">"development"</span>,
  <span class="hljs-string">"nextExport"</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-string">"autoExport"</span>: <span class="hljs-literal">true</span>
}
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>The 4 bundle files loaded are already implementing one feature called code splitting. The <code>index.js</code> file provides the code needed for the <code>index</code> component, which serves the <code>/</code> route, and if we had more pages we'd have more bundles for each page, which will then only be loaded if needed - to provide a more performant load time for the page.</p>
<h2 id="heading-whats-that-icon-on-the-bottom-right">What's that icon on the bottom right?</h2>
<p>Did you see that little icon at the bottom right of the page, which looks like a lightning?</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-04-at-13.21.42.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If you hover it, it's going to say "Prerendered Page":</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-04-at-13.21.46.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This icon, which is <em>only visible in development mode</em> of course, tells you the page qualifies for automatic static optimization, which basically means that it does not depend on data that needs to be fetched at invokation time, and it can be prerendered and built as a static HTML file at build time (when we run <code>npm run build</code>).</p>
<p>Next can determine this by the absence of the <code>getInitialProps()</code> method attached to the page component.</p>
<p>When this is the case, our page can be even faster because it will be served statically as an HTML file rather than going through the Node.js server that generates the HTML output.</p>
<p>Another useful icon that might appear next to it, or instead of it on non-prerendered pages, is a little animated triangle:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-14-at-14.56.21.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This is a compilation indicator, and appears when you save a page and Next.js is compiling the application before hot code reloading kicks in to reload the code in the application automatically.</p>
<p>It's a really nice way to immediately determine if the app has already been compiled and you can test a part of it you're working on.</p>
<h2 id="heading-install-the-react-developer-tools">Install the React Developer Tools</h2>
<p>Next.js is based on React, so one very useful tool we absolutely need to install (if you haven't already) is the React Developer Tools.</p>
<p>Available for both <a target="_blank" href="https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en">Chrome</a> and <a target="_blank" href="https://addons.mozilla.org/en-US/firefox/addon/react-devtools/">Firefox</a>, the React Developer Tools are an essential instrument you can use to inspect a React application.</p>
<p>Now, the React Developer Tools are not specific to Next.js but I want to introduce them because you might not be 100% familiar with all the tools React provides. It's best to go a little into debugging tooling than assuming you already know them.</p>
<p>They provide an inspector that reveals the React components tree that builds your page, and for each component you can go and check the props, the state, hooks, and lots more.</p>
<p>Once you have installed the React Developer Tools, you can open the regular browser devtools (in Chrome, it's right-click in the page, then click <code>Inspect</code>) and you'll find 2 new panels: <strong>Components</strong> and <strong>Profiler</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-04-at-14.26.12.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If you move the mouse over the components, you'll see that in the page, the browser will select the parts that are rendered by that component.</p>
<p>If you select any component in the tree, the right panel will show you a reference to <strong>the parent component</strong>, and the props passed to it:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-04-at-14.27.05.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You can easily navigate by clicking around the component names.</p>
<p>You can click the eye icon in the Developer Tools toolbar   to inspect the DOM element, and also if you use the first icon, the one with the mouse icon (which conveniently sits under the similar regular DevTools icon), you can hover an element in the browser UI to directly select the React component that renders it.</p>
<p>You can use the <code>bug</code> icon to log a component data to the console.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-04-at-14.31.25.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This is pretty awesome because once you have the data printed there, you can right-click any element and press "Store as a global variable". For example here I did it with the <code>url</code> prop, and I was able to inspect it in the console using the temporary variable assigned to it, <code>temp1</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-04-at-14.40.22.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Using <strong>Source Maps</strong>, which are loaded by Next.js automatically in development mode, from the Components panel we can click the <code>&lt;&gt;</code> code and the DevTools will switch to the Source panel, showing us the component source code:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-04-at-14.41.33.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The <strong>Profiler</strong> tab is even more awesome, if possible. It allows us to <strong>record an interaction</strong> in the app, and see what happens. I cannot show an example yet, because it needs at least 2 components to create an interaction, and we have just one now. I'll talk about this later.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-04-at-14.42.24.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>I showed all screenshots using Chrome, but the React Developer Tools works in the same way in Firefox:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-04-at-14.45.20.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-other-debugging-techniques-you-can-use">Other debugging techniques you can use</h2>
<p>In addition to the React Developer Tools, which are essential to building a Next.js application, I want to emphasize 2 ways to debug Next.js apps.</p>
<p>The first is obviously <code>console.log()</code> and all the <a target="_blank" href="https://flaviocopes.com/console-api/">other Console API</a> tools. The way Next apps work will make a log statement work in the browser console OR in the terminal where you started Next using <code>npm run dev</code>.</p>
<p>In particular, if the page loads from the server, when you point the URL to it, or you hit the refresh button / cmd/ctrl-R, any console logging happens in the terminal.</p>
<p>Subsequent page transitions that happen by clicking the mouse will make all console logging happen inside the browser.</p>
<p>Just remember if you are surprised by missing logging.</p>
<p>Another tool that is essential is the <code>debugger</code> statement. Adding this statement to a component will pause the browser rendering the page:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-04-at-15.10.32.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Really awesome because now you can use the browser debugger to inspect values and run your app one line at a time.</p>
<p>You can also use the VS Code debugger to debug server-side code. I mention this technique and <a target="_blank" href="https://github.com/Microsoft/vscode-recipes/tree/master/Next-js">this tutorial</a> to set this up.</p>
<h2 id="heading-adding-a-second-page-to-the-site">Adding a second page to the site</h2>
<p>Now that we have a good grasp of the tools we can use to help us develop Next.js apps, let's continue from where we left our first app:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-04-at-13.21.42-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>I want to add a second page to this website, a blog. It's going to be served into <code>/blog</code>, and for the time being it will just contain a simple static page, just like our first <code>index.js</code> component:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-04-at-15.39.40.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>After saving the new file, the <code>npm run dev</code> process already running is already capable of rendering the page, without the need to restart it.</p>
<p>When we hit the URL <a target="_blank" href="http://localhost:3000/blog">http://localhost:3000/blog</a> we have the new page:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-04-at-15.41.39.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>and here's what the terminal told us:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-04-at-15.41.03.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now the fact that the URL is <code>/blog</code> depends on just the filename, and its position under the <code>pages</code> folder.</p>
<p>You can create a <code>pages/hey/ho</code> page, and that page will show up on the URL <a target="_blank" href="http://localhost:3000/hey/ho">http://localhost:3000/hey/ho</a>.</p>
<p>What does not matter, for the URL purposes, is the component name inside the file.</p>
<p>Try going and viewing the source of the page, when loaded from the server it will list <code>/_next/static/development/pages/blog.js</code> as one of the bundles loaded, and not <code>/_next/static/development/pages/index.js</code> like in the home page. This is because thanks to automatic code splitting we don't need the bundle that serves the home page. Just the bundle that serves the blog page.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-04-at-16.24.53.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>We can also just export an anonymous function from <code>blog.js</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> () =&gt; (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Blog<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
)
</code></pre>
<p>or if you prefer the non-arrow function syntax:</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Blog<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}
</code></pre>
<h2 id="heading-linking-the-two-pages">Linking the two pages</h2>
<p>Now that we have 2 pages, defined by <code>index.js</code> and <code>blog.js</code>, we can introduce links.</p>
<p>Normal HTML links within pages are done using the <code>a</code> tag:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/blog"</span>&gt;</span>Blog<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
</code></pre>
<p>We can't do do that in Next.js.</p>
<p>Why? We technically <em>can</em>, of course, because this is the Web and <em>on the Web things never break</em> (that's why we can still use the <code>&lt;marquee&gt;</code> tag. But one of the main benefits of using Next is that once a page is loaded, transitions to other page are very fast thanks to client-side rendering.</p>
<p>If you use a plain <code>a</code> link:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Index = <span class="hljs-function">() =&gt;</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Home page<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">'/blog'</span>&gt;</span>Blog<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
)

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Index
</code></pre>
<p>Now open the <strong>DevTools</strong>, and the <strong>Network panel</strong> in particular. The first time we load <code>http://localhost:3000/</code> we get all the page bundles loaded:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-04-at-16.26.00.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now if you click the "Preserve log" button (to avoid clearing the Network panel), and click the "Blog" link, this is what happens:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-04-at-16.27.16.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>We got all that JavaScript from the server, again! But.. we don't need all that JavaScript if we already got it. We'd just need the <code>blog.js</code> page bundle, the only one that's new to the page.</p>
<p>To fix this problem, we use a component provided by Next, called Link.</p>
<p>We import it:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> Link <span class="hljs-keyword">from</span> <span class="hljs-string">'next/link'</span>
</code></pre>
<p>and then we use it to wrap our link, like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> Link <span class="hljs-keyword">from</span> <span class="hljs-string">'next/link'</span>

<span class="hljs-keyword">const</span> Index = <span class="hljs-function">() =&gt;</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Home page<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">href</span>=<span class="hljs-string">'/blog'</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">a</span>&gt;</span>Blog<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
)

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Index
</code></pre>
<p>Now if you retry the thing we did previously, you'll be able to see that only the <code>blog.js</code> bundle is loaded when we move to the blog page:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-04-at-16.35.18.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>and the page loaded so faster than before, the browser usual spinner on the tab didn't even appear. Yet the URL changed, as you can see. This is working seamlessly with the browser <a target="_blank" href="https://flaviocopes.com/history-api/">History API</a>.</p>
<p>This is client-side rendering in action.</p>
<p>What if you now press the back button? Nothing is being loaded, because the browser still has the old <code>index.js</code> bundle in place, ready to load the <code>/index</code> route. It's all automatic!</p>
<h2 id="heading-dynamic-content-with-the-router">Dynamic content with the router</h2>
<p>In the previous chapter we saw how to link the home to the blog page.</p>
<p>A blog is a great use case for Next.js, one we'll continue to explore in this chapter by adding <strong>blog posts</strong>.</p>
<p>Blog posts have a dynamic URL. For example a post titled "Hello World" might have the URL <code>/blog/hello-world</code>. A post titled "My second post" might have the URL <code>/blog/my-second-post</code>.</p>
<p>This content is dynamic, and might be taken from a database, markdown files or more.</p>
<p>Next.js can serve dynamic content based on a <strong>dynamic URL</strong>.</p>
<p>We create a dynamic URL by creating a dynamic page with the <code>[]</code> syntax.</p>
<p>How? We add a <code>pages/blog/[id].js</code> file. This file will handle all the dynamic URLs under the <code>/blog/</code> route, like the ones we mentioned above: <code>/blog/hello-world</code>, <code>/blog/my-second-post</code> and more.</p>
<p>In the file name, <code>[id]</code> inside the square brackets means that anything that's dynamic will be put inside the <code>id</code> parameter of the <strong>query property</strong> of the <strong>router</strong>.</p>
<p>Ok, that's a bit too many things at once.</p>
<p>What's the <strong>router</strong>?</p>
<p>The router is a library provided by Next.js.</p>
<p>We import it from <code>next/router</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useRouter } <span class="hljs-keyword">from</span> <span class="hljs-string">'next/router'</span>
</code></pre>
<p>and once we have <code>useRouter</code>, we instantiate the router object using:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> router = useRouter()
</code></pre>
<p>Once we have this router object, we can extract information from it.</p>
<p>In particular we can get the dynamic part of the URL in the <code>[id].js</code> file by accessing <code>router.query.id</code>.</p>
<p>The dynamic part can also just be a portion of the URL, like <code>post-[id].js</code>.</p>
<p>So let's go on and apply all those things in practice.</p>
<p>Create the file <code>pages/blog/[id].js</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useRouter } <span class="hljs-keyword">from</span> <span class="hljs-string">'next/router'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> () =&gt; {
  <span class="hljs-keyword">const</span> router = useRouter()

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Blog post<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Post id: {router.query.id}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>Now if you go to the <code>http://localhost:3000/blog/test</code> router, you should see this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-05-at-16.41.32.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>We can use this <code>id</code> parameter to gather the post from a list of posts. From a database, for example. To keep things simple we'll add a <code>posts.json</code> file in the project root folder:</p>
<pre><code class="lang-js">{
  <span class="hljs-string">"test"</span>: {
    <span class="hljs-string">"title"</span>: <span class="hljs-string">"test post"</span>,
    <span class="hljs-string">"content"</span>: <span class="hljs-string">"Hey some post content"</span>
  },
  <span class="hljs-string">"second"</span>: {
    <span class="hljs-string">"title"</span>: <span class="hljs-string">"second post"</span>,
    <span class="hljs-string">"content"</span>: <span class="hljs-string">"Hey this is the second post content"</span>
  }
}
</code></pre>
<p>Now we can import it and lookup the post from the <code>id</code> key:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useRouter } <span class="hljs-keyword">from</span> <span class="hljs-string">'next/router'</span>
<span class="hljs-keyword">import</span> posts <span class="hljs-keyword">from</span> <span class="hljs-string">'../../posts.json'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> () =&gt; {
  <span class="hljs-keyword">const</span> router = useRouter()

  <span class="hljs-keyword">const</span> post = posts[router.query.id]

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{post.title}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{post.content}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>Reloading the page should show us this result:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-05-at-16.44.07.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>But it's not! Instead, we get an error in the console, and an error in the browser, too:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-05-at-18.18.17.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Why? Because.. during rendering, when the component is initialized, the data is not there yet. We'll see how to provide the data to the component with getInitialProps in the next lesson.</p>
<p>For now, add a little <code>if (!post) return &lt;p&gt;&lt;/p&gt;</code> check before returning the JSX:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useRouter } <span class="hljs-keyword">from</span> <span class="hljs-string">'next/router'</span>
<span class="hljs-keyword">import</span> posts <span class="hljs-keyword">from</span> <span class="hljs-string">'../../posts.json'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> () =&gt; {
  <span class="hljs-keyword">const</span> router = useRouter()

  <span class="hljs-keyword">const</span> post = posts[router.query.id]
  <span class="hljs-keyword">if</span> (!post) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{post.title}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{post.content}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>Now things should work. Initially the component is rendered without the dynamic <code>router.query.id</code> information. After rendering, Next.js triggers an update with the query value and the page displays the correct information.</p>
<p>And if you view source, there is that empty <code>&lt;p&gt;</code> tag in the HTML:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-05-at-18.20.58.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>We'll soon fix this issue that fails to implement SSR and this harms both loading times for our users, SEO and social sharing as we already discussed.</p>
<p>We can complete the blog example by listing those posts in <code>pages/blog.js</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> posts <span class="hljs-keyword">from</span> <span class="hljs-string">'../posts.json'</span>

<span class="hljs-keyword">const</span> Blog = <span class="hljs-function">() =&gt;</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Blog<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
      {Object.entries(posts).map((value, index) =&gt; {
        return <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{index}</span>&gt;</span>{value[1].title}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
      })}
    <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
)

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Blog
</code></pre>
<p>And we can link them to the individual post pages, by importing <code>Link</code> from <code>next/link</code> and using it inside the posts loop:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> Link <span class="hljs-keyword">from</span> <span class="hljs-string">'next/link'</span>
<span class="hljs-keyword">import</span> posts <span class="hljs-keyword">from</span> <span class="hljs-string">'../posts.json'</span>

<span class="hljs-keyword">const</span> Blog = <span class="hljs-function">() =&gt;</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Blog<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
      {Object.entries(posts).map((value, index) =&gt; {
        return (
          <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{index}</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">href</span>=<span class="hljs-string">'/blog/[id]'</span> <span class="hljs-attr">as</span>=<span class="hljs-string">{</span>'/<span class="hljs-attr">blog</span>/' + <span class="hljs-attr">value</span>[<span class="hljs-attr">0</span>]}&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">a</span>&gt;</span>{value[1].title}<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
        )
      })}
    <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
)

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Blog
</code></pre>
<h2 id="heading-prefetching-1">Prefetching</h2>
<p>I mentioned previously how the <code>Link</code> Next.js component can be used to create links between 2 pages, and when you use it, Next.js <strong>transparently handles frontend routing</strong> for us, so when a user clicks a link, frontend takes care of showing the new page without triggering a new client/server request and response cycle, as it normally happens with web pages.</p>
<p>There's another thing that Next.js does for you when you use <code>Link</code>.</p>
<p>As soon as an element wrapped within <code>&lt;Link&gt;</code> appears in the viewport (which means it's visible to the website user), Next.js prefetches the URL it points to, as long as it's a local link (on your website), making the application super fast to the viewer.</p>
<p>This behavior is only being triggered in <strong>production mode</strong> (we'll talk about this in-depth later), which means you have to stop the application if you are running it with <code>npm run dev</code>, compile your production bundle with <code>npm run build</code> and run it with  <code>npm run start</code> instead.</p>
<p>Using the Network inspector in the DevTools you'll notice that any links above the fold, at page load, start the prefetching as soon as the <code>load</code> event has been fired on your page (triggered when the page is fully loaded, and happens after the <code>DOMContentLoaded</code> event).</p>
<p>Any other <code>Link</code> tag not in the viewport will be prefetched when the user scrolls and it</p>
<p>Prefetching is automatic on high speed connections (Wifi and 3g+ connections, unless the browser sends the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Save-Data"><code>Save-Data</code> HTTP Header</a>.</p>
<p>You can opt out from prefetching individual <code>Link</code> instances by setting the <code>prefetch</code> prop to <code>false</code>:</p>
<pre><code class="lang-jsx">&lt;Link href=<span class="hljs-string">"/a-link"</span> prefetch={<span class="hljs-literal">false</span>}&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">a</span>&gt;</span>A link<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span></span>
&lt;/Link&gt;
</code></pre>
<h2 id="heading-using-the-router-to-detect-the-active-link">Using the router to detect the active link</h2>
<p>One very important feature when working with links is determining what is the current URL, and in particular assigning a class to the active link, so we can style it differently from the other ones.</p>
<p>This is especially useful in your site header, for example.</p>
<p>The Next.js default <code>Link</code> component offered in <code>next/link</code> does not do this automatically for us.</p>
<p>We can create a Link component ourselves, and we store it in a file <code>Link.js</code> in the Components folder, and import that instead of the default <code>next/link</code>.</p>
<p>In this component, we'll first import React from <code>react</code>, Link from <code>next/link</code> and the <code>useRouter</code> hook from <code>next/router</code>.</p>
<p>Inside the component we determine if the current path name matches the <code>href</code> prop of the component, and if so we append the <code>selected</code> class to the children.</p>
<p>We finally return this children with the updated class, using <code>React.cloneElement()</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> Link <span class="hljs-keyword">from</span> <span class="hljs-string">'next/link'</span>
<span class="hljs-keyword">import</span> { useRouter } <span class="hljs-keyword">from</span> <span class="hljs-string">'next/router'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ({ href, children }) =&gt; {
  <span class="hljs-keyword">const</span> router = useRouter()

  <span class="hljs-keyword">let</span> className = children.props.className || <span class="hljs-string">''</span>
  <span class="hljs-keyword">if</span> (router.pathname === href) {
    className = <span class="hljs-string">`<span class="hljs-subst">${className}</span> selected`</span>
  }

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">href</span>=<span class="hljs-string">{href}</span>&gt;</span>{React.cloneElement(children, { className })}<span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span></span>
}
</code></pre>
<h2 id="heading-using-nextrouter">Using <code>next/router</code></h2>
<p>We already saw how to use the Link component to declaratively handle routing in Next.js apps.</p>
<p>It's really handy to manage routing in JSX, but sometimes you need to trigger a routing change programmatically.</p>
<p>In this case, you can access the Next.js Router directly, provided in the <code>next/router</code> package, and call its <code>push()</code> method.</p>
<p>Here's an example of accessing the router:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useRouter } <span class="hljs-keyword">from</span> <span class="hljs-string">'next/router'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> () =&gt; {
  <span class="hljs-keyword">const</span> router = useRouter()
  <span class="hljs-comment">//...</span>
}
</code></pre>
<p>Once we get the router object by invoking <code>useRouter()</code>, we can use its methods.</p>
<p>This is the client side router, so methods should only be used in frontend facing code. The easiest way to ensure this is to wrap calls in the <code>useEffect()</code> React hook, or inside <code>componentDidMount()</code> in React stateful components.</p>
<p>The ones you'll likely use the most are <code>push()</code> and <code>prefetch()</code>.</p>
<p><code>push()</code> allows us to programmatically trigger a URL change, in the frontend:</p>
<pre><code class="lang-js">router.push(<span class="hljs-string">'/login'</span>)
</code></pre>
<p><code>prefetch()</code> allows us to programmatically prefetch a URL, useful when we don't have a <code>Link</code> tag which automatically handles prefetching for us:</p>
<pre><code class="lang-js">router.prefetch(<span class="hljs-string">'/login'</span>)
</code></pre>
<p>Full example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useRouter } <span class="hljs-keyword">from</span> <span class="hljs-string">'next/router'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> () =&gt; {
  <span class="hljs-keyword">const</span> router = useRouter()

  useEffect(<span class="hljs-function">() =&gt;</span> {
    router.prefetch(<span class="hljs-string">'/login'</span>)
  })
}
</code></pre>
<p>You can also use the router to listen for <a target="_blank" href="https://nextjs.org/docs#router-events">route change events</a>.</p>
<h2 id="heading-feed-data-to-the-components-using-getinitialprops">Feed data to the components using getInitialProps</h2>
<p>In the previous chapter we had an issue with dynamically generating the post page, because the component required some data up front, and when we tried to get the data from the JSON file:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useRouter } <span class="hljs-keyword">from</span> <span class="hljs-string">'next/router'</span>
<span class="hljs-keyword">import</span> posts <span class="hljs-keyword">from</span> <span class="hljs-string">'../../posts.json'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> () =&gt; {
  <span class="hljs-keyword">const</span> router = useRouter()

  <span class="hljs-keyword">const</span> post = posts[router.query.id]

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{post.title}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{post.content}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>we got this error:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-05-at-18.18.17-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>How do we solve this? And how do we make SSR work for dynamic routes?</p>
<p>We must provide the component with props, using a special function called <code>getInitialProps()</code> which is attached to the component.</p>
<p>To do so, first we name the component:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Post = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">//...</span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Post
</code></pre>
<p>then we add the function to it:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Post = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">//...</span>
}

Post.getInitialProps = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">//...</span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Post
</code></pre>
<p>This function gets an object as its argument, which contains several properties. In particular, the thing we are interested into now is that we get the <code>query</code> object, the one we used previously to get the post id.</p>
<p>So we can get it using the <em>object destructuring</em> syntax:</p>
<pre><code class="lang-js">Post.getInitialProps = <span class="hljs-function">(<span class="hljs-params">{ query }</span>) =&gt;</span> {
  <span class="hljs-comment">//...</span>
}
</code></pre>
<p>Now we can return the post from this function:</p>
<pre><code class="lang-js">Post.getInitialProps = <span class="hljs-function">(<span class="hljs-params">{ query }</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">post</span>: posts[query.id]
  }
}
</code></pre>
<p>And we can also remove the import of <code>useRouter</code>, and we get the post from the <code>props</code> property passed to the <code>Post</code> component:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> posts <span class="hljs-keyword">from</span> <span class="hljs-string">'../../posts.json'</span>

<span class="hljs-keyword">const</span> Post = <span class="hljs-function"><span class="hljs-params">props</span> =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{props.post.title}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{props.post.content}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}

Post.getInitialProps = <span class="hljs-function">(<span class="hljs-params">{ query }</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">post</span>: posts[query.id]
  }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Post
</code></pre>
<p>Now there will be no error, and SSR will be working as expected, as you can see checking view source:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-05-at-18.53.02.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The <code>getInitialProps</code> function will be executed on the server side, but also on the client side, when we navigate to a new page using the <code>Link</code> component as we did.</p>
<p>It's important to note that <code>getInitialProps</code> gets, in the context object it receives, in addition to the <code>query</code> object these other properties:</p>
<ul>
<li><code>pathname</code>: the <code>path</code> section of URL</li>
<li><code>asPath</code> - String of the actual path (including the query) shows in the browser</li>
</ul>
<p>which in the case of calling <code>http://localhost:3000/blog/test</code> will respectively result to:</p>
<ul>
<li><code>/blog/[id]</code></li>
<li><code>/blog/test</code></li>
</ul>
<p>And in the case of server side rendering, it will also receive:</p>
<ul>
<li><code>req</code>: the HTTP request object</li>
<li><code>res</code>: the HTTP response object</li>
<li><code>err</code>: an error object</li>
</ul>
<p><code>req</code> and <code>res</code> will be familiar to you if you've done any Node.js coding.</p>
<h2 id="heading-css">CSS</h2>
<p>How do we style React components in Next.js?</p>
<p>We have a lot of freedom, because we can use whatever library we prefer.</p>
<p>But Next.js comes with <a target="_blank" href="https://github.com/zeit/styled-jsx"><code>styled-jsx</code></a> built-in, because that's a library built by the same people working on Next.js.</p>
<p>And it's a pretty cool library that provides us scoped CSS, which is great for maintainability because the CSS is only affecting the component it's applied to.</p>
<p>I think this is a great approach at writing CSS, without the need to apply additional libraries or preprocessors that add complexity.</p>
<p>To add CSS to a React component in Next.js we insert it inside a snippet in the JSX, which start with</p>
<pre><code class="lang-js">&lt;style jsx&gt;{<span class="hljs-string">`</span>
</code></pre>
<p>and ends with</p>
<pre><code class="lang-js"><span class="hljs-string">`}&lt;/style&gt;</span>
</code></pre>
<p>Inside this weird blocks we write plain CSS, as we'd do in a <code>.css</code> file:</p>
<pre><code class="lang-js">&lt;style jsx&gt;{<span class="hljs-string">`
  h1 {
    font-size: 3rem;
  }
`</span>}&lt;/style&gt;
</code></pre>
<p>You write it inside the JSX, like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Index = <span class="hljs-function">() =&gt;</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Home page<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">style</span> <span class="hljs-attr">jsx</span>&gt;</span>{`
          h1 {
            font-size: 3rem;
          }
        `}<span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
)

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Index
</code></pre>
<p>Inside the block we can use interpolation to dynamically change the values. For example here we assume a <code>size</code> prop is being passed by the parent component, and we use it in the <code>styled-jsx</code> block:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Index = <span class="hljs-function"><span class="hljs-params">props</span> =&gt;</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Home page<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">style</span> <span class="hljs-attr">jsx</span>&gt;</span>{`
          h1 {
            font-size: ${props.size}rem;
          }
        `}<span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
)
</code></pre>
<p>If you want to apply some CSS globally, not scoped to a component, you add the <code>global</code> keyword to the <code>style</code> tag:</p>
<pre><code class="lang-jsx">&lt;style jsx <span class="hljs-built_in">global</span>&gt;{<span class="hljs-string">`
body {
  margin: 0;
}
`</span>}&lt;/style&gt;
</code></pre>
<p>If you want to import an external CSS file in a Next.js component, you have to first install <code>@zeit/next-css</code>:</p>
<pre><code class="lang-bash">npm install @zeit/next-css
</code></pre>
<p>and then create a configuration file in the root of the project, called <code>next.config.js</code>, with this content:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> withCSS = <span class="hljs-built_in">require</span>(<span class="hljs-string">'@zeit/next-css'</span>)
<span class="hljs-built_in">module</span>.exports = withCSS()
</code></pre>
<p>After restarting the Next app, you can now import CSS like you normally do with JavaScript libraries or components:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> <span class="hljs-string">'../style.css'</span>
</code></pre>
<p>You can also import a SASS file directly, using the <a target="_blank" href="https://github.com/zeit/next-plugins/tree/master/packages/next-sass"><code>@zeit/next-sass</code></a> library instead.</p>
<h2 id="heading-populating-the-head-tag-with-custom-tags">Populating the head tag with custom tags</h2>
<p>From any Next.js page component, you can add information to the page header.</p>
<p>This is handy when:</p>
<ul>
<li>you want to customize the page title</li>
<li>you want to change a meta tag</li>
</ul>
<p>How can you do so?</p>
<p>Inside every component you can import the <code>Head</code> component from <code>next/head</code> and include it in your component JSX output:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> Head <span class="hljs-keyword">from</span> <span class="hljs-string">'next/head'</span>

<span class="hljs-keyword">const</span> House = <span class="hljs-function"><span class="hljs-params">props</span> =&gt;</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">Head</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>The page title<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Head</span>&gt;</span>
    {/* the rest of the JSX */}
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
)

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> House
</code></pre>
<p>You can add any HTML tag you'd like to appear in the <code>&lt;head&gt;</code> section of the page.</p>
<p>When mounting the component, Next.js will make sure the tags inside <code>Head</code> are added to the heading of the page. Same when unmounting the component, Next.js will take care of removing those tags.</p>
<h2 id="heading-adding-a-wrapper-component">Adding a wrapper component</h2>
<p>All the pages on your site look more or less the same. There's a chrome window, a common base layer, and you just want to change what's inside.</p>
<p>There's a nav bar, a sidebar, and then the actual content.</p>
<p>How do you build such system in Next.js?</p>
<p>There are 2 ways. One is using a <a target="_blank" href="https://flaviocopes.com/react-higher-order-components/">Higher Order Component</a>, by creating a <code>components/Layout.js</code> component:</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Page =&gt; {
  <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">nav</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>....<span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">hav</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">main</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Page</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}
</code></pre>
<p>In there we can import separate components for heading and/or sidebar, and we can also add all the CSS we need.</p>
<p>And you use it in every page like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> withLayout <span class="hljs-keyword">from</span> <span class="hljs-string">'../components/Layout.js'</span>

<span class="hljs-keyword">const</span> Page = <span class="hljs-function">() =&gt;</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Here's a page!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> withLayout(Page)
</code></pre>
<p>But I found this works only for simple cases, where you don't need to call <code>getInitialProps()</code> on a page.</p>
<p>Why?</p>
<p>Because <code>getInitialProps()</code> gets only called on the page component. But if we export the Higher Order Component withLayout() from a page, <code>Page.getInitialProps()</code> is not called. <code>withLayout.getInitialProps()</code> would.</p>
<p>To avoid unnecessarily complicating our codebase, the alternative approach is to use props:</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> props =&gt; (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">nav</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>....<span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">hav</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">main</span>&gt;</span>
      {props.content}
    <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
)
</code></pre>
<p>and in our pages now we use it like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> Layout <span class="hljs-keyword">from</span> <span class="hljs-string">'../components/Layout.js'</span>

<span class="hljs-keyword">const</span> Page = <span class="hljs-function">() =&gt;</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Layout</span> <span class="hljs-attr">content</span>=<span class="hljs-string">{(</span>
    &lt;<span class="hljs-attr">p</span>&gt;</span>Here's a page!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  )} /&gt;</span>
)
</code></pre>
<p>This approach lets us use <code>getInitialProps()</code> from within our page component, with the only downside of having to write the component JSX inside the <code>content</code> prop:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> Layout <span class="hljs-keyword">from</span> <span class="hljs-string">'../components/Layout.js'</span>

<span class="hljs-keyword">const</span> Page = <span class="hljs-function">() =&gt;</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Layout</span> <span class="hljs-attr">content</span>=<span class="hljs-string">{(</span>
    &lt;<span class="hljs-attr">p</span>&gt;</span>Here's a page!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  )} /&gt;</span>
)

Page.getInitialProps = <span class="hljs-function">(<span class="hljs-params">{ query }</span>) =&gt;</span> {
  <span class="hljs-comment">//...</span>
}
</code></pre>
<h2 id="heading-api-routes">API Routes</h2>
<p>In addition to creating <strong>page routes</strong>, which means pages are served to the browser as Web pages, Next.js can create <strong>API routes</strong>.</p>
<p>This is a very interesting feature because it means that Next.js can be used to create a frontend for data that is stored and retrieved by Next.js itself, transferring JSON via fetch requests.</p>
<p>API routes live under the <code>/pages/api/</code> folder and are mapped to the <code>/api</code> endpoint.</p>
<p>This feature is <em>very</em> useful when creating applications.</p>
<p>In those routes, we write Node.js code (rather than React code). It's a paradigm shift, you move from the frontend to the backend, but very seamlessly.</p>
<p>Say you have a <code>/pages/api/comments.js</code> file, whose goal is to return the comments of a blog post as JSON.</p>
<p>Say you have a list of comments stored in a <code>comments.json</code> file:</p>
<pre><code class="lang-json">[
  {
    <span class="hljs-attr">"comment"</span>: <span class="hljs-string">"First"</span>
  },
  {
    <span class="hljs-attr">"comment"</span>: <span class="hljs-string">"Nice post"</span>
  }
]
</code></pre>
<p>Here's a sample code, which returns to the client the list of comments:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> comments <span class="hljs-keyword">from</span> <span class="hljs-string">'./comments.json'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> (req, res) =&gt; {
  res.status(<span class="hljs-number">200</span>).json(comments)
}
</code></pre>
<p>It will listen on the <code>/api/comments</code> URL for GET requests, and you can try calling it using your browser:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-07-at-11.14.42.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>API routes can also use <strong>dynamic routing</strong> like pages, use the <code>[]</code> syntax to create a dynamic API route, like <code>/pages/api/comments/[id].js</code> which will retrieve the comments specific to a post id.</p>
<p>Inside the <code>[id].js</code> you can retrieve the <code>id</code> value by looking it up inside the <code>req.query</code> object:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> comments <span class="hljs-keyword">from</span> <span class="hljs-string">'../comments.json'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> (req, res) =&gt; {
  res.status(<span class="hljs-number">200</span>).json({ <span class="hljs-attr">post</span>: req.query.id, comments })
}
</code></pre>
<p>Heres you can see the above code in action:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-07-at-11.59.53.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In dynamic pages, you'd need to import <code>useRouter</code> from <code>next/router</code>, then get the router object using <code>const router = useRouter()</code>, and then we'd be able to get the <code>id</code> value using <code>router.query.id</code>.</p>
<p>In the server-side it's all easier, as the query is attached to the request object.</p>
<p>If you do a POST request, all works in the same way - it all goes through that default export.</p>
<p>To separate POST from GET and other HTTP methods (PUT, DELETE), lookup the <code>req.method</code> value:</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> (req, res) =&gt; {
  <span class="hljs-keyword">switch</span> (req.method) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">'GET'</span>:
      <span class="hljs-comment">//...</span>
      <span class="hljs-keyword">break</span>
    <span class="hljs-keyword">case</span> <span class="hljs-string">'POST'</span>:
      <span class="hljs-comment">//...</span>
      <span class="hljs-keyword">break</span>
    <span class="hljs-attr">default</span>:
      res.status(<span class="hljs-number">405</span>).end() <span class="hljs-comment">//Method Not Allowed</span>
      <span class="hljs-keyword">break</span>
  }
}
</code></pre>
<p>In addition to <code>req.query</code> and <code>req.method</code> we already saw, we have access to cookies by referencing <code>req.cookies</code>, the request body in <code>req.body</code>.</p>
<p>Under the hoods, this is all powered by <a target="_blank" href="https://github.com/zeit/micro">Micro</a>, a library that powers asynchronous HTTP microservices, made by the same team that built Next.js.</p>
<p>You can make use of any Micro middleware in our API routes to add more functionality.</p>
<h2 id="heading-run-code-only-on-the-server-side-or-client-side">Run code only on the server side or client side</h2>
<p>In your page components, you can execute code only in the server-side or on the client-side, by checking the <code>window</code> property.</p>
<p>This property is only existing inside the browser, so you can check</p>
<pre><code class="lang-js"><span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> <span class="hljs-built_in">window</span> === <span class="hljs-string">'undefined'</span>) {

}
</code></pre>
<p>and add the server-side code in that block.</p>
<p>Similarly, you can execute client-side code only by checking</p>
<pre><code class="lang-js"><span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> <span class="hljs-built_in">window</span> !== <span class="hljs-string">'undefined'</span>) {

}
</code></pre>
<p>JS Tip: We use the <code>typeof</code> operator here because we can't detect a value to be undefined in other ways. We can't do <code>if (window === undefined)</code> because we'd get a "window is not defined" runtime error</p>
<p>Next.js, as a build-time optimization, also removes the code that uses those checks from bundles. A client-side bundle will not include the content wrapped into a <code>if (typeof window === 'undefined') {}</code> block.</p>
<h2 id="heading-deploying-the-production-version">Deploying the production version</h2>
<p>Deploying an app is always left last in tutorials.</p>
<p>Here I want to introduce it early, just because it's so easy to deploy a Next.js app that we can dive into it now, and then move on to other more complex topics later on.</p>
<p>Remember in the "How to install Next.js" chapter I told you to add those 3 lines to the <code>package.json</code> <code>script</code> section:</p>
<pre><code class="lang-json"><span class="hljs-string">"scripts"</span>: {
  <span class="hljs-attr">"dev"</span>: <span class="hljs-string">"next"</span>,
  <span class="hljs-attr">"build"</span>: <span class="hljs-string">"next build"</span>,
  <span class="hljs-attr">"start"</span>: <span class="hljs-string">"next start"</span>
}
</code></pre>
<p>We used <code>npm run dev</code> up to now, to call the <code>next</code> command installed locally in <code>node_modules/next/dist/bin/next</code>. This started the development server, which provided us <strong>source maps</strong> and <strong>hot code reloading</strong>, two very useful features while debugging.</p>
<p>The same command can be invoked to build the website passing the <code>build</code> flag, by running <code>npm run build</code>. Then, the same command can be used to start the production app passing the <code>start</code> flag, by running <code>npm run start</code>.</p>
<p>Those 2 commands are the ones we must invoke to successfully deploy the production version of our site locally. The production version is highly optimized and does not come with source maps and other things like hot code reloading that would not be beneficial to our end users.</p>
<p>So, let's create a production deploy of our app. Build it using:</p>
<pre><code class="lang-bash">npm run build
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-06-at-13.46.31.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The output of the command tells us that some routes (<code>/</code> and <code>/blog</code> are now prerendered as static HTML, while <code>/blog/[id]</code> will be served by the Node.js backend.</p>
<p>Then you can run <code>npm run start</code> to start the production server locally:</p>
<pre><code class="lang-bash">npm run start
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-06-at-13.47.01.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Visiting <a target="_blank" href="http://localhost:3000">http://localhost:3000</a> will show us the production version of the app, locally.</p>
<h2 id="heading-deploying-on-now">Deploying on Now</h2>
<p>In the previous chapter we deployed the Next.js application locally.</p>
<p>How do we deploy it to a real web server, so other people can access it?</p>
<p>One of the most simple ways to deploy a Next application is through the <strong>Now</strong> platform created by <a target="_blank" href="https://zeit.co">Zeit</a>,  the same company that created the Open Source project Next.js. You can use Now to deploy Node.js apps, Static Websites, and much more.</p>
<p>Now makes the deployment and distribution step of an app very, very simple and fast, and in addition to Node.js apps, they also support deploying Go, PHP, Python and other languages.</p>
<p>You can think of it as the "cloud", as you don't really know where your app will be deployed, but you know that you will have a URL where you can reach it.</p>
<p>Now is free to start using, with generous free plan that currently includes 100GB of hosting, 1000 <a target="_blank" href="https://www.freecodecamp.org/news/serverless/">serverless</a> functions invocations per day, 1000 builds per month, 100GB of bandwidth per month, and one <a target="_blank" href="https://www.freecodecamp.org/news/cdn/">CDN</a> location. The <a target="_blank" href="https://zeit.co/pricing">pricing page</a> helps get an idea of the costs if you need more.</p>
<p>The best way to start using Now is by using the official Now CLI:</p>
<pre><code class="lang-bash">npm install -g now
</code></pre>
<p>Once the command is available, run</p>
<pre><code class="lang-bash">now login
</code></pre>
<p>and the app will ask you for your email.</p>
<p>If you haven't registered already, create an account on <a target="_blank" href="https://zeit.co/signup">https://zeit.co/signup</a> before continuing, then add your email to the CLI client.</p>
<p>Once this is done, from the Next.js project root folder run</p>
<pre><code class="lang-bash">now
</code></pre>
<p>and the app will be instantly deployed to the Now cloud, and you'll be given the unique app URL:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-06-at-14.21.09.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Once you run the <code>now</code> program, the app is deployed to a random URL under the <code>now.sh</code> domain.</p>
<p>We can see 3 different URLs in the output given in the image:</p>
<ul>
<li><a target="_blank" href="https://firstproject-2pv7khwwr.now.sh">https://firstproject-2pv7khwwr.now.sh</a></li>
<li><a target="_blank" href="https://firstproject-sepia-ten.now.sh">https://firstproject-sepia-ten.now.sh</a></li>
<li><a target="_blank" href="https://firstproject.flaviocopes.now.sh">https://firstproject.flaviocopes.now.sh</a></li>
</ul>
<p>Why so many?</p>
<p>The first is the URL identifying the deploy. Every time we deploy the app, this URL will change.</p>
<p>You can test immediately by changing something in the project code, and running <code>now</code> again:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-06-at-15.08.11.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The other 2 URLs will not change. The first is a random one, the second is your project name (which defaults to the current project folder, your account name and then <code>now.sh</code>.</p>
<p>If you visit the URL, you will see the app deployed to production.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-06-at-14.21.43.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You can configure Now to serve the site to your own custom domain or subdomain, but I will not dive into that right now.</p>
<p>The <code>now.sh</code> subdomain is enough for our testing purposes.</p>
<h2 id="heading-analyzing-the-app-bundles">Analyzing the app bundles</h2>
<p>Next provides us a way to analyze the code bundles that are generated.</p>
<p>Open the package.json file of the app and in the scripts section add those 3 new commands:</p>
<pre><code class="lang-json"><span class="hljs-string">"analyze"</span>: <span class="hljs-string">"cross-env ANALYZE=true next build"</span>,
<span class="hljs-string">"analyze:server"</span>: <span class="hljs-string">"cross-env BUNDLE_ANALYZE=server next build"</span>,
<span class="hljs-string">"analyze:browser"</span>: <span class="hljs-string">"cross-env BUNDLE_ANALYZE=browser next build"</span>
</code></pre>
<p>Like this:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"firstproject"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"description"</span>: <span class="hljs-string">""</span>,
  <span class="hljs-attr">"main"</span>: <span class="hljs-string">"index.js"</span>,
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"dev"</span>: <span class="hljs-string">"next"</span>,
    <span class="hljs-attr">"build"</span>: <span class="hljs-string">"next build"</span>,
    <span class="hljs-attr">"start"</span>: <span class="hljs-string">"next start"</span>,
    <span class="hljs-attr">"analyze"</span>: <span class="hljs-string">"cross-env ANALYZE=true next build"</span>,
    <span class="hljs-attr">"analyze:server"</span>: <span class="hljs-string">"cross-env BUNDLE_ANALYZE=server next build"</span>,
    <span class="hljs-attr">"analyze:browser"</span>: <span class="hljs-string">"cross-env BUNDLE_ANALYZE=browser next build"</span>
  },
  <span class="hljs-attr">"keywords"</span>: [],
  <span class="hljs-attr">"author"</span>: <span class="hljs-string">""</span>,
  <span class="hljs-attr">"license"</span>: <span class="hljs-string">"ISC"</span>,
  <span class="hljs-attr">"dependencies"</span>: {
    <span class="hljs-attr">"next"</span>: <span class="hljs-string">"^9.1.2"</span>,
    <span class="hljs-attr">"react"</span>: <span class="hljs-string">"^16.11.0"</span>,
    <span class="hljs-attr">"react-dom"</span>: <span class="hljs-string">"^16.11.0"</span>
  }
}
</code></pre>
<p>then install those 2 packages:</p>
<pre><code class="lang-bash">npm install --dev cross-env @next/bundle-analyzer
</code></pre>
<p>Create a <code>next.config.js</code> file in the project root, with this content:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> withBundleAnalyzer = <span class="hljs-built_in">require</span>(<span class="hljs-string">'@next/bundle-analyzer'</span>)({
  <span class="hljs-attr">enabled</span>: process.env.ANALYZE === <span class="hljs-string">'true'</span>
})

<span class="hljs-built_in">module</span>.exports = withBundleAnalyzer({})
</code></pre>
<p>Now run the command</p>
<pre><code class="lang-bash">npm run analyze
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-06-at-16.12.40.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This should open 2 pages in the browser. One for the client bundles, and one for the server bundles:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-06-at-16.11.14.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-06-at-16.11.23.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This is incredibly useful. You can inspect what's taking the most space in the bundles, and you can also use the sidebar to exclude bundles, for an easier visualization of the smaller ones:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-06-at-16.14.12.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-lazy-loading-modules">Lazy loading modules</h2>
<p>Being able to visually analyze a bundle is great because we can optimize our application very easily.</p>
<p>Say we need to load the Moment library in our blog posts. Run:</p>
<pre><code class="lang-bash">npm install moment
</code></pre>
<p>to include it in the project.</p>
<p>Now let's simulate the fact we need it on two different routes: <code>/blog</code> and <code>/blog/[id]</code>.</p>
<p>We import it in <code>pages/blog/[id].js</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> moment <span class="hljs-keyword">from</span> <span class="hljs-string">'moment'</span>

...

const Post = <span class="hljs-function"><span class="hljs-params">props</span> =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{props.post.title}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Published on {moment().format('dddd D MMMM YYYY')}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{props.post.content}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}
</code></pre>
<p>I'm just adding today's date, as an example.</p>
<p>This will include Moment.js in the blog post page bundle, as you can see by running <code>npm run analyze</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-06-at-17.56.14.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>See that we now have a red entry in <code>/blog/[id]</code>, the route that we added Moment.js to!</p>
<p>It went from ~1kB to 350kB, quite a big deal. And this is because the Moment.js library itself is 349kB.</p>
<p>The client bundles visualization now shows us that the bigger bundle is the page one, which before was very little. And 99% of its code is Moment.js.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-06-at-17.55.50.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Every time we load a blog post we are going to have all this code transferred to the client. Which is not ideal.</p>
<p>One fix would be to look for a library with a smaller size, as Moment.js is not known for being lightweight (especially out of the box with all the locales included), but let's assume for the sake of the example that we must use it.</p>
<p>What we can do instead is separating all the Moment code in a <strong>separate bundle</strong>.</p>
<p>How? Instead of importing Moment at the component level, we perform an async import inside <code>getInitialProps</code>, and we calculate the value to send to the component.<br>Remember that we can't return complex objects inside the <code>getInitialProps()</code> returned object, so we calculate the date inside it:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> posts <span class="hljs-keyword">from</span> <span class="hljs-string">'../../posts.json'</span>

<span class="hljs-keyword">const</span> Post = <span class="hljs-function"><span class="hljs-params">props</span> =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{props.post.title}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Published on {props.date}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{props.post.content}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}

Post.getInitialProps = <span class="hljs-keyword">async</span> ({ query }) =&gt; {
  <span class="hljs-keyword">const</span> moment = (<span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'moment'</span>)).default()
  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">date</span>: moment.format(<span class="hljs-string">'dddd D MMMM YYYY'</span>),
    <span class="hljs-attr">post</span>: posts[query.id]
  }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Post
</code></pre>
<p>See that special call to <code>.default()</code> after <code>await import</code>? It's needed to reference the default export in a dynamic import (see <a target="_blank" href="https://v8.dev/features/dynamic-import">https://v8.dev/features/dynamic-import</a>)</p>
<p>Now if we run <code>npm run analyze</code> again, we can see this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/Screen-Shot-2019-11-06-at-18.00.22.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Our <code>/blog/[id]</code> bundle is again very small, as Moment has been moved to its own bundle file, loaded separately by the browser.</p>
<h2 id="heading-where-to-go-from-here">Where to go from here</h2>
<p>There is a lot more to know about Next.js. I didn't talk about managing user sessions with login, serverless, managing databases, and so on.</p>
<p>The goal of this Handbook is not to teach you everything, but instead it aims to introduce you, gradually, to all the power of Next.js.</p>
<p>The next step I recommend is to take a good read at the <a target="_blank" href="https://nextjs.org/docs">Next.js official documentation</a> to find out more about all the features and functionality I didn't talk about, and take a look at all the additional functionalities introduced by <a target="_blank" href="https://github.com/zeit/next-plugins">Next.js plugins</a>, some of which are pretty amazing.</p>
<p>You can reach me on Twitter <a target="_blank" href="https://twitter.com/flaviocopes">@flaviocopes</a>.</p>
<p>Also check out my website, <a target="_blank" href="https://flaviocopes.com/">flaviocopes.com</a>.</p>
<p><a target="_blank" href="https://flaviocopes.com/page/nextjs-handbook/">Note: you can download a PDF / ePub / Mobi version of this tutorial so you can read it offline</a>!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Svelte Handbook – Learn Svelte for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ I wrote this book to help you quickly learn Svelte and get familiar with how it works. The ideal reader of the book has zero knowledge of Svelte, has maybe used Vue or React, but is looking for something more, or a new approach to things. Svelte is v... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-svelte-handbook/</link>
                <guid isPermaLink="false">66bb5abf3c5ab240beb8cdbf</guid>
                
                    <category>
                        <![CDATA[ frontend ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Svelte ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Flavio Copes ]]>
                </dc:creator>
                <pubDate>Tue, 22 Oct 2019 11:37:47 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/10/Screen-Shot-2019-10-21-at-18.39.28.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>I wrote this book to help you quickly learn Svelte and get familiar with how it works.</p>
<p>The ideal reader of the book has zero knowledge of Svelte, has maybe used Vue or React, but is looking for <em>something</em> <em>more</em>, or a new approach to things.</p>
<p>Svelte is very much worth looking into, because it provides a refreshing point of view and several unique features to the Web.</p>
<p>Thank you for getting this ebook. I hope it will help you learn more about Svelte!</p>
<p>You can reach me on Twitter <a target="_blank" href="https://twitter.com/flaviocopes">@flaviocopes</a>. My website is <a target="_blank" href="https://flaviocopes.com/">flaviocopes.com</a>.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-introduction-to-svelte">Introduction to Svelte</a></li>
<li><a class="post-section-overview" href="#heading-svelte-components">Svelte Components</a></li>
<li><a class="post-section-overview" href="#heading-handling-state-in-svelte">Handling State in Svelte</a></li>
<li><a class="post-section-overview" href="#heading-svelte-reactivity">Svelte Reactivity</a></li>
<li><a class="post-section-overview" href="#heading-svelte-props">Svelte Props</a></li>
<li><a class="post-section-overview" href="#heading-cross-component-state-management-in-svelte">Cross-component State Management</a></li>
<li><a class="post-section-overview" href="#heading-slots">Slots</a></li>
<li><a class="post-section-overview" href="#heading-svelte-lifecycle-events">Svelte Lifecycle events</a></li>
<li><a class="post-section-overview" href="#heading-svelte-bindings">Svelte Bindings</a></li>
<li><a class="post-section-overview" href="#heading-conditional-logic-in-templates">Conditional Logic in Templates</a></li>
<li><a class="post-section-overview" href="#heading-looping-in-svelte-templates">Looping in Svelte Templates</a></li>
<li><a class="post-section-overview" href="#heading-promises-in-svelte-templates">Promises in Svelte Templates</a></li>
<li><a class="post-section-overview" href="#heading-working-with-events-in-svelte">Working with Events in Svelte</a></li>
<li><a class="post-section-overview" href="#heading-where-to-go-from-here">Where To Go From Here</a></li>
</ul>
<h2 id="heading-introduction-to-svelte">Introduction to Svelte</h2>
<p>Svelte is an exciting web frontend framework that you can use to build web applications.</p>
<p>If you're just starting out, Svelte is a great choice as your first frontend framework.</p>
<p>If you are already experienced in React, Vue.js, Angular or another frontend frameworks you will be pleasantly surprised by Svelte.</p>
<p>Compared to React, Vue, Angular and other frameworks, an app built using Svelte is <strong>compiled</strong> beforehand so you don't have to serve the whole framework to every one of your site visitors.</p>
<p>As a result, the fruition of the experience is smoother, consumes less bandwidth, and everything feels faster and more lightweight.</p>
<p>At deployment, Svelte disappears and all you get is plain (and fast!) JavaScript.</p>
<p>This is just the tip of the iceberg. Let's get into it!</p>
<p><a target="_blank" href="https://thevalleyofcode.com/download/svelte/">You can get a PDF and ePub version of this Svelte Handbook</a></p>
<h3 id="heading-how-to-get-started-with-svelte">How to get started with Svelte</h3>
<p>To use Svelte, you need to have Node.js installed because all the tooling we're going to use is based on Node.</p>
<blockquote>
<p>Make sure you also check out my <a target="_blank" href="https://thevalleyofcode.com/node/">Node.js Handbook</a></p>
</blockquote>
<p>One little tip I have is that the Svelte website provides a very cool "playground" to test out Svelte at <a target="_blank" href="https://svelte.dev/repl">https://svelte.dev/repl</a>.</p>
<p>It's pretty cool to test small Svelte apps and to experiment with things.</p>
<p>With the terminal, go into the folder where you usually keep your code, for example <code>dev</code> folder in your home.</p>
<p>Run this command on your computer:</p>
<pre><code class="lang-sh">npm create vite@latest helloworld -- --template svelte
</code></pre>
<p>This sets up everything you need to get started with your first Svelte application. I called it <code>helloworld</code> so you will see a folder with that name.</p>
<p>Go into that folder with <code>cd helloworld</code> and then run</p>
<pre><code class="lang-sh">npm install
</code></pre>
<p>and when this ends:</p>
<pre><code class="lang-sh">npm run dev
</code></pre>
<p>This runs our new Svelte site in development mode, starting the app on localhost on port 5173:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen-Shot-2022-07-20-at-20.01.29.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If you point your browser there, you'll see the sample project showing up:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen-Shot-2022-07-20-at-20.04.08.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You're now ready to open the code in your favorite editor, for example <strong>VS Code</strong>.</p>
<p>You can do that running <code>code .</code> in the folder, if you've installed the <a target="_blank" href="https://code.visualstudio.com/docs/editor/command-line">The Visual Studio Code command-line interface</a>.</p>
<p>As soon as you open the project in the the editor, VS Code will prompt you to install the <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode">Svelte for VS Code</a> extension (if it doesn't, go to the extensions panel and search it):</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen-Shot-2022-07-20-at-20.09.04.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Install it, as it provides the code highlighter and other features:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screen-Shot-2022-07-20-at-20.10.11.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now back to the project!</p>
<p>Open the <code>src</code> folder, you will see a few files in there. The main one, pun intended, is <code>main.js</code>, where the Svelte application is set up:</p>
<p>This file is the entry point and initializes the main App component, which is defined in <code>App.svelte</code>:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">import</span> svelteLogo <span class="hljs-keyword">from</span> <span class="hljs-string">'./assets/svelte.svg'</span>
  <span class="hljs-keyword">import</span> Counter <span class="hljs-keyword">from</span> <span class="hljs-string">'./lib/Counter.svelte'</span>
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">main</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://vitejs.dev"</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/vite.svg"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"logo"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"Vite Logo"</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://svelte.dev"</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"{svelteLogo}"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"logo svelte"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"Svelte Logo"</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Vite + Svelte<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">Counter</span> /&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
    Check out
    <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://github.com/sveltejs/kit#readme"</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>
      &gt;</span>SvelteKit<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>
    &gt;</span>, the official Svelte app framework powered by Vite!
  <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"read-the-docs"</span>&gt;</span>Click on the Vite and Svelte logos to learn more<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
  <span class="hljs-selector-class">.logo</span> {
    <span class="hljs-attribute">height</span>: <span class="hljs-number">6em</span>;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">1.5em</span>;
    <span class="hljs-attribute">will-change</span>: filter;
  }
  <span class="hljs-selector-class">.logo</span><span class="hljs-selector-pseudo">:hover</span> {
    <span class="hljs-attribute">filter</span>: <span class="hljs-built_in">drop-shadow</span>(<span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">2em</span> #<span class="hljs-number">646</span>cffaa);
  }
  <span class="hljs-selector-class">.logo</span><span class="hljs-selector-class">.svelte</span><span class="hljs-selector-pseudo">:hover</span> {
    <span class="hljs-attribute">filter</span>: <span class="hljs-built_in">drop-shadow</span>(<span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">2em</span> #ff3e00aa);
  }
  <span class="hljs-selector-class">.read-the-docs</span> {
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#888</span>;
  }
</span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
</code></pre>
<p>See, we have 3 main sections:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">main</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
</code></pre>
<p>This is what we call a <strong>single file component</strong>, a single file that determines all about our component:</p>
<ul>
<li>the markup (the HTML)</li>
<li>the behavior (the JavaScript)</li>
<li>the style (the CSS)</li>
</ul>
<p>This structure will be the base for all your Svelte components.</p>
<h2 id="heading-svelte-components">Svelte Components</h2>
<p>Modern Web development is very much focused on components, and Svelte is no different.</p>
<p>What is a component? A component is an atomic part of the application that is self-contained and optionally references other components to compose its output.</p>
<p>In other words, it's an atomic part of the application.</p>
<p>A form can be a component.</p>
<p>An input element can be a component.</p>
<p>The whole application is a component.</p>
<p>Svelte components contain all that's needed to render a piece of the UI.</p>
<p>Every Svelte component is declared in a <code>.svelte</code> file, and in there you'll find the content (markup), the behavior (JavaScript), and the presentation (CSS) without having to define separate files.</p>
<p>Which is a good way to define a piece of the UI because you don't need to search for the items that affect the same element across various files.</p>
<p>Here's a sample component, which we'll store in a file called <code>Dog.svelte</code>:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">export</span> <span class="hljs-keyword">let</span> name
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
  <span class="hljs-selector-tag">h1</span> {
    <span class="hljs-attribute">color</span>: purple;
  }
</span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>The dog name is {name}!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
</code></pre>
<p>JavaScript code must be put in the <code>script</code> tag.</p>
<p>The CSS you have in the <code>style</code> tag is <strong>scoped</strong> to the component and does not "leak" outside.</p>
<p>If another component has an <code>h1</code> tag, this style will not affect that.</p>
<p>This is very handy when reusing components you already wrote for other applications, for example, or when you include Open Source libraries published by other people.</p>
<p>For example you can include a date picker component built by someone else and none of the stylings of the component will affect the rest of the application.</p>
<p>And in the same way, none of the CSS you wrote will modify the look of the date picker.</p>
<h3 id="heading-importing-the-component-in-other-components">Importing the component in other components</h3>
<p>A component can be used by other components.</p>
<p>Other components can now import the <code>Dog</code> component we wrote in their code.</p>
<p>For example here's a <code>House</code> component:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">import</span> Dog <span class="hljs-keyword">from</span> <span class="hljs-string">'./Dog.svelte'</span>
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>You can now import and use the Dog component, as if it was an HTML tag:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">import</span> Dog <span class="hljs-keyword">from</span> <span class="hljs-string">'./Dog.svelte'</span>
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">Dog</span> /&gt;</span>
</code></pre>
<h3 id="heading-exporting-specific-functions-from-a-component">Exporting specific functions from a component</h3>
<p>As you saw above, to export the component we didn't have to do anything, because the component itself is the <strong>default export</strong>.</p>
<p>What if you want to export something other than the component markup and its associated and built-in functionality?</p>
<p>You must write all the functions you want to export from a special <code>script</code> tag with the <code>context="module"</code> attribute.</p>
<p>Here's an example. Say you have a Button component in <code>Button.svelte</code>:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>A button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>and you want to provide other components the ability to change the color of the button.</p>
<blockquote>
<p>A better solution for this use case is to use props, which is something we'll talk about in the next chapter. But stick with me for this example</p>
</blockquote>
<p>You can provide a function, called <code>changeColor</code>.</p>
<p>You write and export it in this special <code>script</code> tag:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">context</span>=<span class="hljs-string">"module"</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">changeColor</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">//...logic to change color..</span>
  }
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>A button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>Note that you can have another "normal" script tag, in the component.</p>
<p>Now other components can import Button, which is the default export, and the <code>changeColor</code> function too:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">import</span> Button, { changeColor } <span class="hljs-keyword">from</span> <span class="hljs-string">'./Button.svelte'</span>
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>Now that is probably a silly example, but knowing you can use this functionality can be quite helpful.</p>
<h2 id="heading-handling-state-in-svelte">Handling State in Svelte</h2>
<p>Every component, in addition to defining the markup, the CSS and the JavaScript logic, can host its own <strong>state</strong>.</p>
<p>What is state? State is any data that's needed to make the component render what it's rendering.</p>
<p>For example, if a form input field has the string "test" written into it, there'll be a variable somewhere holding this value. That's the state of the input field.</p>
<p>The field is selected? A variable somewhere will register this fact. And so on.</p>
<p>State is defined in the <code>script</code> part of a component:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span>
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>To update the value of a state variable all you need is an assignment. A simple JavaScript assignment, for example using the <code>=</code> operator.</p>
<p>Say you have a <code>count</code> variable. You can increment that using, simply, <code>count = count + 1</code>, or even <code>count++</code>:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span>

  <span class="hljs-keyword">const</span> incrementCount = <span class="hljs-function">() =&gt;</span> {
    count++
  }
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

{count} <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">on:click</span>=<span class="hljs-string">"{incrementCount}"</span>&gt;</span>+1<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>I find this one of the refreshing parts of Svelte, as in React for example you'd have to use the <code>useState()</code> hook, and use a setter function any time you want to update the value of the state variable.</p>
<p>This is more intuitive and much more "JavaScript-like" syntax.</p>
<p>We need to be aware of one thing, which is learned pretty quickly: we must also make an assignment when changing the value.</p>
<p>Svelte always wants an assignment, otherwise it might not recognize that the state changed.</p>
<p>For simple values like strings and numbers, that's mostly a given, because all methods on String return new strings, and same for numbers - they are immutable.</p>
<p>But for arrays? We can't use methods that alter the array. Like <code>push()</code>, <code>pop()</code>, <code>shift()</code>, <code>splice()</code>... because there's no assignment. They change the inner data structure, but Svelte can't detect that.</p>
<p>Well, you <em>can</em> still use them, but after you've done your operation, you can use a "trick" and reassign the variable to itself, like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> list = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
list.push(<span class="hljs-number">4</span>)
list = list
</code></pre>
<p>It's is a bit counter-intuitive, compared to what I just said before, but it's a quirk you'll remember with experience.</p>
<p>Of course you could use alternatives that avoid you this situation, for example instead of using <code>Array.push()</code> you can use the spread operator to add an item:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> list = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
list = [...list, <span class="hljs-number">4</span>]
</code></pre>
<h2 id="heading-svelte-reactivity">Svelte Reactivity</h2>
<p>In Svelte you can listen for changes in the component state, and update other variables.</p>
<p>For example if you have a <code>count</code> variable:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span>
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>and you update it by clicking a button:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span>

  <span class="hljs-keyword">const</span> incrementCount = <span class="hljs-function">() =&gt;</span> {
    count = count + <span class="hljs-number">1</span>
  }
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

{count} <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">on:click</span>=<span class="hljs-string">"{incrementCount}"</span>&gt;</span>+1<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>You can listen for changes on <code>count</code> using the special syntax <code>$:</code> which defines a new block that Svelte will re-run when any variable referenced into it changes.</p>
<p>Here's an example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span>

  <span class="hljs-keyword">const</span> incrementCount = <span class="hljs-function">() =&gt;</span> {
    count = count + <span class="hljs-number">1</span>
  }

  <span class="hljs-attr">$</span>: <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${count}</span>`</span>)
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

{count} <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">on:click</span>=<span class="hljs-string">"{incrementCount}"</span>&gt;</span>+1<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>I used the block:</p>
<pre><code class="lang-js">$: <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${count}</span>`</span>)
</code></pre>
<p>You can write more than one of them:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-attr">$</span>: <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`the count is <span class="hljs-subst">${count}</span>`</span>)
  <span class="hljs-attr">$</span>: <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`double the count is <span class="hljs-subst">${count * <span class="hljs-number">2</span>}</span>`</span>)
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>And you can also add a <strong>block</strong> (opening and closing curly brackets <code>{}</code>) to group more than one statement:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-attr">$</span>: {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`the count is <span class="hljs-subst">${count}</span>`</span>)
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`double the count is <span class="hljs-subst">${count * <span class="hljs-number">2</span>}</span>`</span>)
  }
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>I used a <code>console.log()</code> call in there, but you can update other variables too:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span>
  <span class="hljs-keyword">let</span> double = <span class="hljs-number">0</span>

  <span class="hljs-attr">$</span>: {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`the count is <span class="hljs-subst">${count}</span>`</span>)
    double = count * <span class="hljs-number">2</span>
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`double the count is <span class="hljs-subst">${double}</span>`</span>)
  }
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<h2 id="heading-svelte-props">Svelte Props</h2>
<p>You can import a Svelte component into any other component using the syntax <code>import name from 'path'</code>, like this:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">import</span> SignupForm <span class="hljs-keyword">from</span> <span class="hljs-string">'./SignupForm.svelte'</span>
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<blockquote>
<p>The path is relative to the current component path. <code>./</code> means "this same folder". You'd use <code>../</code> to go back one folder, and so on.</p>
</blockquote>
<p>Once you do so, you can use the newly imported component in the markup, like an HTML tag:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">SignupForm</span> /&gt;</span>
</code></pre>
<p>In this way, you are forming a parent/child relationship between the two components: the one that imports, and the one that is imported.</p>
<p>Often you want to have the parent component pass data to the child component.</p>
<p>You can do so using <strong>props</strong>. Props behave similarly to attributes in plain HTML, and they are a one-way form of communication.</p>
<p>In this example we pass the <code>disabled</code> prop, passing the JavaScript value <code>true</code> to it:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">SignupForm</span> <span class="hljs-attr">disabled</span>=<span class="hljs-string">"{true}"</span> /&gt;</span>
</code></pre>
<p>In the SignupForm component, you need to <strong>export</strong> the <code>disabled</code> prop, in this way:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">export</span> <span class="hljs-keyword">let</span> disabled
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>This is the way you express the fact that the prop is exposed to parent components.</p>
<p>When using the component, you can pass a variable instead of a value, to change it dynamically:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">import</span> SignupForm <span class="hljs-keyword">from</span> <span class="hljs-string">'./SignupForm.svelte'</span>
  <span class="hljs-keyword">let</span> disabled = <span class="hljs-literal">true</span>
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">SignupForm</span> {<span class="hljs-attr">disabled</span>} /&gt;</span>
</code></pre>
<blockquote>
<p>Note I used <code>{disabled}</code> as a handy shorthand form for <code>disabled={disabled}</code></p>
</blockquote>
<p>When the <code>disabled</code> variable value changes, the child component will be updated with the new prop value. Example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">import</span> SignupForm <span class="hljs-keyword">from</span> <span class="hljs-string">'./SignupForm.svelte'</span>
  <span class="hljs-keyword">let</span> disabled = <span class="hljs-literal">true</span>
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    disabled = <span class="hljs-literal">false</span>
  }, <span class="hljs-number">2000</span>)
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">SignupForm</span> {<span class="hljs-attr">disabled</span>} /&gt;</span>
</code></pre>
<h2 id="heading-cross-component-state-management-in-svelte">Cross-component State Management in Svelte</h2>
<p>We've already seen how Svelte makes handling the state of a single component very easy.</p>
<p>But how do we pass state around across components?</p>
<h3 id="heading-passing-state-around-using-props">Passing state around using props</h3>
<p>The first strategy is common to other UI frameworks and it's passing state around using props, <strong>lifting the state up</strong>.</p>
<p>When a component needs to share data with another, the state can be moved up in the components tree until there's a common parent to those components.</p>
<p>The state needs to be passed down until it reaches all the components that need this state information.</p>
<p>This is done using <strong>props</strong>, and it's a technique that I think is the best as it's simple.</p>
<h3 id="heading-the-context-api">The context API</h3>
<p>However, there are cases where props are not practical. Perhaps 2 components are so distant in the components tree that we'd have to move state up to the top-level component.</p>
<p>In this case, another technique can be used and it's called <strong>context API</strong>, and it's ideal when you want to let multiple components communicate with descendants, but you don't want to pass props around.</p>
<p>The context API is provided by 2 functions which are provided by the <code>svelte</code> package: <code>getContext</code> and <code>setContext</code>.</p>
<p>You set an object in the context, associating it to a key:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">import</span> { setContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'svelte'</span>

  <span class="hljs-keyword">const</span> someObject = {}

  setContext(<span class="hljs-string">'someKey'</span>, someObject)
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>In another component you can use <code>getContext</code> to retrieve the object assigned to a key:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">import</span> { getContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'svelte'</span>

  <span class="hljs-keyword">const</span> someObject = getContext(<span class="hljs-string">'someKey'</span>)
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>You can only use <code>getContext</code> to retrieve a key either in the component that used <code>setContext</code> or in one of its descendants.</p>
<p>If you want to let two components living in 2 different component trees communicate there's another tool for us: <strong>stores</strong>.</p>
<h3 id="heading-using-svelte-stores">Using Svelte stores</h3>
<p>Svelte stores are a great tool to handle your app state when components need to talk to each other without passing props around too much.</p>
<p>You must first import <code>writable</code> from <code>svelte/store</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { writable } <span class="hljs-keyword">from</span> <span class="hljs-string">'svelte/store'</span>
</code></pre>
<p>and create a store variable using the <code>writable()</code> function, passing the default value as the first argument:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> username = writable(<span class="hljs-string">'Guest'</span>)
</code></pre>
<p>This can be put into a separate file which you can import into multiple components, for example, called <code>store.js</code> (it's not a component, so it can be in a <code>.js</code> file instead of <code>.svelte</code>):</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { writable } <span class="hljs-keyword">from</span> <span class="hljs-string">'svelte/store'</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> username = writable(<span class="hljs-string">'Guest'</span>)
</code></pre>
<p>Any other component now loading this file can access the store:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">import</span> { username } <span class="hljs-keyword">from</span> <span class="hljs-string">'./store.js'</span>
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>Now the value of this variable can be set to a new value using <code>set()</code>, passing the new value as the first argument:</p>
<pre><code class="lang-js">username.set(<span class="hljs-string">'new username'</span>)
</code></pre>
<p>And it can be updated using the <code>update()</code> function, which differs from <code>set()</code> because you don't just pass the new value to it - you run a callback function that is passed the current value as its argument:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> newUsername = <span class="hljs-string">'new username!'</span>
username.update(<span class="hljs-function">(<span class="hljs-params">existing</span>) =&gt;</span> newUsername)
</code></pre>
<p>You can add more logic here:</p>
<pre><code class="lang-js">username.update(<span class="hljs-function">(<span class="hljs-params">existing</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Updating username from <span class="hljs-subst">${existing}</span> to <span class="hljs-subst">${newUsername}</span>`</span>)
  <span class="hljs-keyword">return</span> newUsername
})
</code></pre>
<p>To get the value of the store variable <em>once</em>, you can use the <code>get()</code> function exported by <code>svelte/store</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { writable, get } <span class="hljs-keyword">from</span> <span class="hljs-string">'svelte/store'</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> username = writable(<span class="hljs-string">'Guest'</span>)
get(username) <span class="hljs-comment">//'Guest'</span>
</code></pre>
<p>To create a reactive variable that's updated whenever the store value changes instead, you can prepend the store variable using <code>$</code> (in this example <code>$username</code>). Using that will make the component re-render whenever the stored value changes.</p>
<blockquote>
<p>Svelte considers <code>$</code> to be a reserved value and will prevent you to use it for things that are not related to stores values (which might lead to confusion), so if you are used to prepending DOM references using <code>$</code>, don't do it in Svelte.</p>
<p>Another option, best suited if you need to execute some logic when the variable changes, is to use the <code>subscribe()</code> method of <code>username</code>:</p>
</blockquote>
<pre><code class="lang-js">username.subscribe(<span class="hljs-function">(<span class="hljs-params">newValue</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(newValue)
})
</code></pre>
<p>In addition to writable stores, Svelte provides 2 special kinds of stores: <strong>readable stores</strong> and <strong>derived stores</strong>.</p>
<h3 id="heading-svelte-readable-stores">Svelte Readable Stores</h3>
<p>Readable stores are special because they can't be updated from the outside - there's no <code>set()</code> or <code>update()</code> method. Instead, once you set the initial state, they can't be modified from the outside.</p>
<p>The official Svelte docs show an interesting example using a timer to update a date. I can think of setting up a timer to fetch a resource from the network, perform an API call, get data from the filesystem (using a local Node.js server) or anything else that can be set up autonomously.</p>
<p>In this case instead of using <code>writable()</code> to initialize the store variable, we use <code>readable()</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { readable } <span class="hljs-keyword">from</span> <span class="hljs-string">'svelte/store'</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> count = readable(<span class="hljs-number">0</span>)
</code></pre>
<p>You can provide a function after the default value, that will be responsible for updating it. This function receives the <code>set</code> function to modify the value:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">import</span> { readable } <span class="hljs-keyword">from</span> <span class="hljs-string">'svelte/store'</span>
  <span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> count = readable(<span class="hljs-number">0</span>, <span class="hljs-function">(<span class="hljs-params">set</span>) =&gt;</span> {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      set(<span class="hljs-number">1</span>)
    }, <span class="hljs-number">1000</span>)
  })
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>In this case, we update the value from 0 to 1 after 1 second.</p>
<p>You can setup an interval in this function, too:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { readable, get } <span class="hljs-keyword">from</span> <span class="hljs-string">'svelte/store'</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> count = readable(<span class="hljs-number">0</span>, <span class="hljs-function">(<span class="hljs-params">set</span>) =&gt;</span> {
  <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =&gt;</span> {
    set(get(count) + <span class="hljs-number">1</span>)
  }, <span class="hljs-number">1000</span>)
})
</code></pre>
<p>You can use this in another component like this:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">import</span> { count } <span class="hljs-keyword">from</span> <span class="hljs-string">'./store.js'</span>
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

{$count}
</code></pre>
<h3 id="heading-svelte-derived-stores">Svelte Derived Stores</h3>
<p>A derived store allows you to create a new store value that depends on the value of an existing store.</p>
<p>You can do so using the <code>derived()</code> function exported by <code>svelte/store</code> which takes as its first parameter the existing store value, and as a second parameter a function which receives that store value as its first parameter:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { writable, derived } <span class="hljs-keyword">from</span> <span class="hljs-string">'svelte/store'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> username = writable(<span class="hljs-string">'Guest'</span>)

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> welcomeMessage = derived(username, <span class="hljs-function">(<span class="hljs-params">$username</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-string">`Welcome <span class="hljs-subst">${$username}</span>`</span>
})
</code></pre>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">import</span> { username, welcomeMessage } <span class="hljs-keyword">from</span> <span class="hljs-string">'./store.js'</span>
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

{$username} {$welcomeMessage}
</code></pre>
<h2 id="heading-slots">Slots</h2>
<p>Slots are a handy way to let you define components that can be composed together.</p>
<p>And vice versa, depending on your point of view, slots are a handy way to configure a component you are importing.</p>
<p>Here's how they work.</p>
<p>In a component you can define a slot using the <code>&lt;slot /&gt;</code> (or <code>&lt;slot&gt;&lt;/slot&gt;</code>) syntax.</p>
<p>Here's a <code>Button.svelte</code> component that simply prints a <code>&lt;button&gt;</code> HTML tag:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">slot</span> /&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<blockquote>
<p>For React developers, this is basically the same as <code>&lt;button&gt;{props.children}&lt;/button&gt;</code></p>
</blockquote>
<p>Any component importing it can define content that is going to be put into the slot by adding it into the component's opening and closing tags:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">import</span> Button <span class="hljs-keyword">from</span> <span class="hljs-string">'./Button.svelte'</span>
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Insert this into the slot<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>You can define a default, which is used if the slot is not filled:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">slot</span>&gt;</span> Default text for the button <span class="hljs-tag">&lt;/<span class="hljs-name">slot</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>You can have more than one slot in a component, and you can distinguish one from the other using named slots. The single unnamed slot will be the default one:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">slot</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"before"</span> /&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">slot</span> /&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">slot</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"after"</span> /&gt;</span>
</code></pre>
<p>Here's how you would use it:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">import</span> Button <span class="hljs-keyword">from</span> <span class="hljs-string">'./Button.svelte'</span>
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>
  Insert this into the slot
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">slot</span>=<span class="hljs-string">"before"</span>&gt;</span>Add this before<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">slot</span>=<span class="hljs-string">"after"</span>&gt;</span>Add this after<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>And this would render the following to the DOM:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">slot</span>=<span class="hljs-string">"before"</span>&gt;</span>Add this before<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Insert this into the slot<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">slot</span>=<span class="hljs-string">"after"</span>&gt;</span>Add this after<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<h2 id="heading-svelte-lifecycle-events">Svelte Lifecycle events</h2>
<p>Every component in Svelte fires several lifecycle events that we can hook on, to help us implement the functionality we have in mind.</p>
<p>In particular, we have</p>
<ul>
<li><code>onMount</code> fired after the component is rendered</li>
<li><code>onDestroy</code> fired after the component is destroyed</li>
<li><code>beforeUpdate</code> fired before the DOM is updated</li>
<li><code>afterUpdate</code> fired after the DOM is updated</li>
</ul>
<p>We can schedule functions to happen when these events are fired by Svelte.</p>
<p>We don't have access to any of those methods by default, but we need to import them from the <code>svelte</code> package:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">import</span> { onMount, onDestroy, beforeUpdate, afterUpdate } <span class="hljs-keyword">from</span> <span class="hljs-string">'svelte'</span>
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>A common scenario for <code>onMount</code> is to fetch data from other sources.</p>
<p>Here's a sample usage of <code>onMount</code>:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">import</span> { onMount } <span class="hljs-keyword">from</span> <span class="hljs-string">'svelte'</span>

  onMount(<span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-comment">//do something on mount</span>
  })
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p><code>onDestroy</code> allows us to clean up data or stop any operation we might have started at the component initialization, like timers or scheduled periodic functions using <code>setInterval</code>.</p>
<p>One particular thing to notice is that if we return a function from <code>onMount</code>, that serves the same functionality of <code>onDestroy</code> - it's run when the component is destroyed:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">import</span> { onMount } <span class="hljs-keyword">from</span> <span class="hljs-string">'svelte'</span>

  onMount(<span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-comment">//do something on mount</span>

    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> {
      <span class="hljs-comment">//do something on destroy</span>
    }
  })
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>Here's a practical example that sets a periodic function to run on mount, and removes it on destroy:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">import</span> { onMount } <span class="hljs-keyword">from</span> <span class="hljs-string">'svelte'</span>

  onMount(<span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">const</span> interval = <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'hey, just checking!'</span>)
    }, <span class="hljs-number">1000</span>)

    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">clearInterval</span>(interval)
    }
  })
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<h2 id="heading-svelte-bindings">Svelte Bindings</h2>
<p>Using Svelte you can create a two-way binding between data and the UI.</p>
<p>Many other Web frameworks can provide two-way bindings, it's a very common UI design pattern.</p>
<p>They are especially useful with forms.</p>
<h3 id="heading-bindvalue">bind:value</h3>
<p>Let's start with the most common form of binding you'll often use, which you can apply using <code>bind:value</code>. You take a variable from the component state, and you bind it to a form field:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">let</span> name = <span class="hljs-string">''</span>
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">bind:value</span>=<span class="hljs-string">"{name}"</span> /&gt;</span>
</code></pre>
<p>Now if <code>name</code> changes the input field will update its value. And the opposite is true, as well: if the form is updated by the user, the <code>name</code> variable value changes.</p>
<blockquote>
<p>Just be aware that the variable must be defined using <code>let/var</code> and not <code>const</code>, otherwise it can't be updated by Svelte, as <code>const</code> defines a variable with a value that can't be reassigned.</p>
</blockquote>
<p><code>bind:value</code> works on all flavors of input fields (<code>type="number"</code>, <code>type="email"</code> and so on), but it also works for other kind of fields, like <code>textarea</code> and <code>select</code> (more on <code>select</code> later).</p>
<h3 id="heading-checkboxes-and-radio-buttons">Checkboxes and radio buttons</h3>
<p>Checkboxes and radio inputs (<code>input</code> elements with <code>type="checkbox"</code> or <code>type="radio"</code>) allow those 3 bindings:</p>
<ul>
<li><code>bind:checked</code></li>
<li><code>bind:group</code></li>
<li><code>bind:indeterminate</code></li>
</ul>
<p><code>bind:checked</code> allows us to bind a value to the checked state of the element:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">let</span> isChecked
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">bind:checked</span>=<span class="hljs-string">"{isChecked}"</span> /&gt;</span>
</code></pre>
<p><code>bind:group</code> is handy with checkboxes and radio inputs, because those are very often used in groups. Using <code>bind:group</code> you can associate a JavaScript array to a list of checkboxes, and have it populated based on the choices made by the user.</p>
<p>Here's an example. The <code>goodDogs</code> array populates based on the checkboxes I tick:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">let</span> goodDogs = []
  <span class="hljs-keyword">let</span> dogs = [<span class="hljs-string">'Roger'</span>, <span class="hljs-string">'Syd'</span>]
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Who's a good dog?<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
  {#each dogs as dog}
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>{dog} <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">bind:group</span>=<span class="hljs-string">"{goodDogs}"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"{dog}"</span> /&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  {/each}
<span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Good dogs according to me:<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
  {#each goodDogs as dog}
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>{dog}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  {/each}
<span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
</code></pre>
<p><a target="_blank" href="https://svelte.dev/repl/059c1b5edffc4b058ad36301dd7a1a58">See the example</a></p>
<p><code>bind:indeterminate</code> allows us to bind to the <code>indeterminate</code> state of an element (if you want to learn more head to <a target="_blank" href="https://css-tricks.com/indeterminate-checkboxes/">https://css-tricks.com/indeterminate-checkboxes/</a>)</p>
<h3 id="heading-select-fields">Select fields</h3>
<p><code>bind:value</code> also works for the <code>select</code> form field to get the selected value automatically assigned to the value of a variable:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">let</span> selected
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">bind:value</span>=<span class="hljs-string">"{selected}"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"1"</span>&gt;</span>1<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"2"</span>&gt;</span>2<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"3"</span>&gt;</span>3<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>

{selected}
</code></pre>
<p>The cool thing is that if you generate options dynamically from an array of objects, the selected option is now an object, not a string:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">let</span> selected

  <span class="hljs-keyword">const</span> dogs = [{ <span class="hljs-attr">name</span>: <span class="hljs-string">'Roger'</span> }, { <span class="hljs-attr">name</span>: <span class="hljs-string">'Syd'</span> }]
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>List of possible good dogs:<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">bind:value</span>=<span class="hljs-string">"{selected}"</span>&gt;</span>
  {#each dogs as dog}
  <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"{dog}"</span>&gt;</span>{dog.name}<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
  {/each}
<span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>

{#if selected}
<span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Dog selected: {selected.name}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
{/if}
</code></pre>
<p><a target="_blank" href="https://svelte.dev/repl/7e06f9b7becd4c57880db5ed184ea0f3">See this example</a></p>
<p><code>select</code> also allows the <code>multiple</code> attribute:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">let</span> selected = []

  <span class="hljs-keyword">const</span> goodDogs = [{ <span class="hljs-attr">name</span>: <span class="hljs-string">'Roger'</span> }, { <span class="hljs-attr">name</span>: <span class="hljs-string">'Syd'</span> }]
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>List of possible good dogs:<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">multiple</span> <span class="hljs-attr">bind:value</span>=<span class="hljs-string">"{selected}"</span>&gt;</span>
  {#each goodDogs as goodDog}
  <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"{goodDog}"</span>&gt;</span>{goodDog.name}<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
  {/each}
<span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>

{#if selected.length}
<span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Good dog selected:<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
  {#each selected as dog}
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>{dog.name}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  {/each}
<span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
{/if}
</code></pre>
<p><a target="_blank" href="https://svelte.dev/repl/b003248e87f04919a2f9fed63dbdab8c">See this example</a></p>
<h3 id="heading-other-bindings">Other bindings</h3>
<p>Depending on the HTML tag you are working on, you can apply different kinds of bindings.</p>
<p><code>bind:files</code> is a binding valid on <code>type="file"</code> input elements, to bind the list of selected files.</p>
<p>The <code>details</code> HTML element allows the use of <code>bind:open</code> to bind its open/close value.</p>
<p>The <code>audio</code> and <code>video</code> media HTML tags allow to bind several of their properties: <code>currentTime</code>, <code>duration</code>, <code>paused</code>, <code>buffered</code>, <code>seekable</code>, <code>played</code>, <code>volume</code>, <code>playbackRate</code>.</p>
<p><code>textContent</code> and <code>innerHTML</code> can be bound on <code>contenteditable</code> fields.</p>
<p>All things very useful for those specific HTML elements.</p>
<h3 id="heading-read-only-bindings">Read-only bindings</h3>
<p><code>offsetWidth</code>, <code>offsetHeight</code>, <code>clientWidth</code>, <code>clientHeight</code> can be bound, read only, on any block level HTML element, excluding void tags (like <code>br</code>) and elements that are set to be inline (<code>display: inline</code>).</p>
<h3 id="heading-get-a-reference-to-the-html-element-in-javascript">Get a reference to the HTML element in JavaScript</h3>
<p><code>bind:this</code> is a special kind of binding that allows you to get a reference to an HTML element and bind it to a JavaScript variable:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">let</span> myInputField
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">bind:this</span>=<span class="hljs-string">"{myInputField}"</span> /&gt;</span>
</code></pre>
<p>This is handy when you need to apply logic to elements after you mount them, for example, using the <code>onMount()</code> lifecycle event callback.</p>
<h3 id="heading-binding-components-props">Binding components props</h3>
<p>Using <code>bind:</code> you can bind a value to any prop that a component exposes.</p>
<p>Say you have a <code>Car.svelte</code> component:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
<span class="hljs-keyword">export</span> <span class="hljs-keyword">let</span> inMovement = <span class="hljs-literal">false</span>
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">on:click</span>=<span class="hljs-string">{()</span> =&gt;</span> inMovement = true }&gt;Start car<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>You can import the component and bind the <code>inMovement</code> prop:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">import</span> Car <span class="hljs-keyword">from</span> <span class="hljs-string">'./Car.svelte'</span>

  <span class="hljs-keyword">let</span> carInMovement
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">Car</span> <span class="hljs-attr">bind:inMovement</span>=<span class="hljs-string">"{carInMovement}"</span> /&gt;</span>

{carInMovement}
</code></pre>
<p>This can allow for interesting scenarios.</p>
<h2 id="heading-conditional-logic-in-templates">Conditional Logic in Templates</h2>
<p>In a Svelte component, when it comes to rendering HTML you can work with some specific syntax to craft the UI you need at every stage of the application lifecycle.</p>
<p>In particular, we'll now explore conditional structures.</p>
<p>The problem is this: you want to be able to look at a value/expression, and if that points to a true value do something if that points to a false value then do something else.</p>
<p>Svelte provides us a very powerful set of control structures.</p>
<p>The first is <strong>if</strong>:</p>
<pre><code class="lang-html">{#if isRed}
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Red<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
{/if}
</code></pre>
<p>There is an opening <code>{#if}</code> and an ending <code>{/if}</code>. The opening markup checks for a value or statement to be truthy. In this case <code>isRed</code> can be a boolean with a <code>true</code> value:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">let</span> isRed = <span class="hljs-literal">true</span>
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>An empty string is falsy, but a string with some content is truthy.</p>
<p>0 is falsy, but a number &gt; 0 is truthy.</p>
<p>The boolean value <code>true</code> is truthy, of course, and <code>false</code> is falsy.</p>
<p>If the opening markup is not satisfied (a falsy value is provided), then nothing happens.</p>
<p>To do something else if that's not satisfied, we use the appropriately called <code>else</code> statement:</p>
<pre><code class="lang-html">{#if isRed}
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Red<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
{:else}
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Not red<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
{/if}
</code></pre>
<p>Either the first block is rendered in the template or the second one. There's no other option.</p>
<p>You can use any JavaScript expression into the <code>if</code> block condition, so you can negate an option using the <code>!</code> operator:</p>
<pre><code class="lang-html">{#if !isRed}
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Not red<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
{:else}
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Red<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
{/if}
</code></pre>
<p>Now, inside the <code>else</code> you might want to check for an additional condition. That's where the <code>{:else if somethingElse}</code> syntax comes along:</p>
<pre><code class="lang-html">{#if isRed}
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Red<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
{:else if isGreen}
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Green<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
{:else}
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Not red nor green<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
{/if}
</code></pre>
<p>You can have many of these blocks, not just one, and you can nest them. Here's a more complex example:</p>
<pre><code class="lang-html">{#if isRed}
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Red<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
{:else if isGreen}
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Green<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
{:else if isBlue}
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>It is blue<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
{:else} {#if isDog}
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>It is a dog<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
{/if} {/if}
</code></pre>
<h2 id="heading-looping-in-svelte-templates">Looping in Svelte Templates</h2>
<p>In Svelte templates you can create a loop using the <code>{#each}{/each}</code> syntax:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">let</span> dogs = [<span class="hljs-string">'Roger'</span>, <span class="hljs-string">'Syd'</span>]
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

{#each dogs as dog}
<span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>{dog}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
{/each}
</code></pre>
<p>If you are familiar with other frameworks that use templates, it's a very similar syntax.</p>
<p>You can get the index of the iteration using:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">let</span> dogs = [<span class="hljs-string">'Roger'</span>, <span class="hljs-string">'Syd'</span>]
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

{#each dogs as dog, index}
<span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>{index}: {dog}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
{/each}
</code></pre>
<p>(indexes start at 0)</p>
<p>When dynamically editing the lists removing and adding elements, you should always pass an identifier in lists, to prevent issues.</p>
<p>You do so using this syntax:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">let</span> dogs = [<span class="hljs-string">'Roger'</span>, <span class="hljs-string">'Syd'</span>]
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

{#each dogs as dog (dog)}
<span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>{dog}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
{/each}

<span class="hljs-comment">&lt;!-- with the index --&gt;</span>
{#each dogs as dog, index (dog)}
<span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>{dog}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
{/each}
</code></pre>
<p>You can pass an object, too, but if your list has a unique identifier for each element, it's best to use it:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">let</span> dogs = [
    { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Roger'</span> },
    { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Syd'</span> },
  ]
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

{#each dogs as dog (dog.id)}
<span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>{dog.name}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
{/each}

<span class="hljs-comment">&lt;!-- with the index --&gt;</span>
{#each dogs as dog, index (dog.id)}
<span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>{dog.name}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
{/each}
</code></pre>
<h2 id="heading-promises-in-svelte-templates">Promises in Svelte Templates</h2>
<p>Promises are an awesome tool we have at our disposal to work with asynchronous events in JavaScript.</p>
<p>The relatively recent introduction of the <code>await</code> syntax in ES2017 made using promises even simpler.</p>
<p>Svelte provides us the <code>{#await}</code> syntax in templates to directly work with promises at the template level.</p>
<p>We can wait for promises to resolve, and define a different UI for the various states of a promise: unresolved, resolved and rejected.</p>
<p>Here's how it works. We define a promise, and using the <code>{#await}</code> block we wait for it to resolve.</p>
<p>Once the promise resolves, the result is passed to the <code>{:then}</code> block:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">const</span> fetchImage = (<span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://dog.ceo/api/breeds/image/random'</span>)
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> response.json()
  })()
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

{#await fetchImage}
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>...waiting<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
{:then data}
<span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"{data.message}"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"Dog image"</span> /&gt;</span>
{/await}
</code></pre>
<p>You can detect a promise rejection by adding a <code>{:catch}</code> block:</p>
<pre><code class="lang-html">{#await fetchImage}
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>...waiting<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
{:then data}
<span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"{data.message}"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"Dog image"</span> /&gt;</span>
{:catch error}
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>An error occurred!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
{/await}
</code></pre>
<p><a target="_blank" href="https://svelte.dev/repl/70e61d6cc91345cdaca2db9b7077a941">Run the example</a></p>
<h2 id="heading-working-with-events-in-svelte">Working with Events in Svelte</h2>
<h3 id="heading-listening-to-dom-events">Listening to DOM events</h3>
<p>In Svelte you can define a listener for a DOM event directly in the template, using the <code>on:&lt;event&gt;</code> syntax.</p>
<p>For example, to listen to the <code>click</code> event, you will pass a function to the <code>on:click</code> attribute.</p>
<p>To listen to the <code>onmousemove</code> event, you'll pass a function to the <code>on:mousemove</code> attribute.</p>
<p>Here's an example with the handling function defined inline:</p>
<pre><code class="lang-js">&lt;button
  <span class="hljs-attr">on</span>:click={<span class="hljs-function">() =&gt;</span> {
    alert(<span class="hljs-string">'clicked'</span>)
  }}
&gt;
  Click me
&lt;/button&gt;
</code></pre>
<p>and here's another example with the handling function defined in the <code>script</code> section of the component:</p>
<pre><code class="lang-js">&lt;script&gt;
<span class="hljs-keyword">const</span> doSomething = <span class="hljs-function">() =&gt;</span> {
  alert(<span class="hljs-string">'clicked'</span>)
}
&lt;/script&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">on:click</span>=<span class="hljs-string">{doSomething}</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
</code></pre>
<p>I prefer inline when the code is not too verbose. If it's just 2-3 lines, for example, otherwise I'd move that up in the script section.</p>
<p>Svelte passes the event handler as the argument of the function, which is handy if you need to stop propagation or to reference something in the <a target="_blank" href="https://flaviocopes.com/javascript-events/#the-event-object">Event object</a>:</p>
<pre><code class="lang-js">&lt;script&gt;
<span class="hljs-keyword">const</span> doSomething = <span class="hljs-function"><span class="hljs-params">event</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(event)
  alert(<span class="hljs-string">'clicked'</span>)
}
&lt;/script&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">on:click</span>=<span class="hljs-string">{doSomething}</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
</code></pre>
<p>Now, I mentioned "stop propagation". That's a very common thing to do, to stop form submit events for example. Svelte provides us <strong>modifiers</strong>, a way to apply it directly without manually doing it.<br><code>stopPropagation</code> and <code>preventDefault</code> are the 2 modifiers you'll use the most, I think.</p>
<p>You apply a modifier like this: <code>&lt;button on:click|stopPropagation|preventDefault={doSomething}&gt;Click me&lt;/button&gt;</code></p>
<p>There are other modifiers, which are more niche. <code>capture</code> enables <a target="_blank" href="https://flaviocopes.com/javascript-events/#event-bubbling-and-event-capturing">capturing events instead of bubbling</a>, <code>once</code> only fires the event once, <code>self</code> only fires the event if the target of the event is this object (removing it from the bubbling/capturing hierarchy).</p>
<h3 id="heading-creating-your-events-in-components">Creating your events in components</h3>
<p>What's interesting is that we can create custom events in components, and use the same syntax of built-in DOM events.</p>
<p>To do so, we must import the <code>createEventDispatcher</code> function from the <code>svelte</code> package and call it to get an event dispatcher:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">import</span> { createEventDispatcher } <span class="hljs-keyword">from</span> <span class="hljs-string">'svelte'</span>
  <span class="hljs-keyword">const</span> dispatch = createEventDispatcher()
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>Once we do so, we can call the <code>dispatch()</code> function, passing a string that identifies the event (which we'll use for the <code>on:</code> syntax in other components that use this):</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">import</span> { createEventDispatcher } <span class="hljs-keyword">from</span> <span class="hljs-string">'svelte'</span>
  <span class="hljs-keyword">const</span> dispatch = createEventDispatcher()

  <span class="hljs-comment">//when it's time to trigger the event</span>
  dispatch(<span class="hljs-string">'eventName'</span>)
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>Now other components can use ours using</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">ComponentName</span> <span class="hljs-attr">on:eventName</span>=<span class="hljs-string">{event</span> =&gt;</span> { //do something }} /&gt;
</code></pre>
<p>You can also pass an object to the event, passing a second parameter to <code>dispatch()</code>:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">import</span> { createEventDispatcher } <span class="hljs-keyword">from</span> <span class="hljs-string">'svelte'</span>
  <span class="hljs-keyword">const</span> dispatch = createEventDispatcher()
  <span class="hljs-keyword">const</span> value = <span class="hljs-string">'something'</span>

  <span class="hljs-comment">//when it's time to trigger the event</span>
  dispatch(<span class="hljs-string">'eventName'</span>, value)

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

  dispatch(<span class="hljs-string">'eventName'</span>, {
    <span class="hljs-attr">someProperty</span>: value,
  })
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>the object passed by <code>dispatch()</code> is available on the <code>event</code> object.</p>
<h2 id="heading-where-to-go-from-here">Where To Go From Here</h2>
<p>I hope this little handbook was useful to shine a light on what Svelte can do for you, and I hope you are now interested to learn more about it!</p>
<p>I can now point you to two places to learn more:</p>
<ul>
<li><a target="_blank" href="https://svelte.dev/">The official Svelte website</a></li>
<li><a target="_blank" href="https://kit.svelte.dev/">SvelteKit</a>, an awesome framework built on top of Svelte that lets you build server-side rendered apps with Node.js and Svelte</li>
</ul>
<p><a target="_blank" href="https://thevalleyofcode.com/download/svelte/">You can get a PDF and ePub version of this Svelte Handbook</a></p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
