<?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[ beginners guide - 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[ beginners guide - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 21 May 2026 10:21:44 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/beginners-guide/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Learn TypeScript – A Comprehensive Guide for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ TypeScript has become an industry standard for building large-scale applications, with many organizations choosing it as their primary language for application development. This tutorial will serve as your introductory guide to TypeScript. It's desig... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/typescript-for-beginners-guide/</link>
                <guid isPermaLink="false">66bb57043c5ab240beb8cd97</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TypeScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Isaiah Clifford Opoku ]]>
                </dc:creator>
                <pubDate>Thu, 08 Aug 2024 16:45:28 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/08/Attractive.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>TypeScript has become an industry standard for building large-scale applications, with many organizations choosing it as their primary language for application development.</p>
<p>This tutorial will serve as your introductory guide to TypeScript. It's designed to cater to learners at all stages – from beginners to advanced users. It teaches both fundamental and advanced TypeScript concepts, making it a helpful resource for anyone looking to delve into TypeScript.</p>
<p>The aim of this guide is not to be an exhaustive resource, but rather a concise and handy reference. It distills the essence of TypeScript into a digestible format.</p>
<p>Whether you're a novice just starting out, an intermediate learner aiming to consolidate your knowledge, or an advanced user in need of a quick refresher, this guide is crafted to meet your TypeScript learning requirements.</p>
<p>After carefully reading through this tutorial and practicing the examples it contains, you should have the skills to build robust, scalable, and maintainable TypeScript applications. We'll cover key TypeScript concepts like types, functions, classes, interfaces, generics, and more.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-who-is-this-guide-for">Who is this guide for?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-typescript-vs-javascript">TypeScript vs. JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-advantages-of-typescript">Advantages of TypeScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-code-generation">Code Generation</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-installation">Installation</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-configuration">Configuration</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-understanding-tsconfig-json">Understanding tsconfig.json</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-typescript-basics">TypeScript Basics</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-type-declarations-and-variables-in-typescript">Type Declarations and Variables in TypeScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-functions-in-typescript">Functions in TypeScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-classes-and-objects-in-typescript">Classes and Objects in TypeScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-interfaces-in-typescript">Interfaces in TypeScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-enums-in-typescript">Enums in TypeScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-generics-in-typescript">Generics in TypeScript</a></p>
</li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before you begin going through this guide, you should have a basic understanding of JavaScript. Familiarity with object-oriented programming concepts like classes, interfaces, and inheritance is also recommended.</p>
<p>But if you're new to these concepts, don't worry - we'll cover them in detail in this guide.</p>
<h2 id="heading-who-is-this-guide-for">Who is this Guide For?</h2>
<p>This guide is for anyone looking to learn TypeScript. Whether you're a beginner, an intermediate learner, or an advanced user, this guide is designed to meet your TypeScript learning needs.</p>
<p>It's also a handy reference for anyone looking to brush up on their TypeScript skills.</p>
<h2 id="heading-typescript-vs-javascript">TypeScript vs JavaScript</h2>
<p>TypeScript is a statically-typed superset of JavaScript, designed to enhance the development of large-scale applications.</p>
<p>It introduces optional <code>static typing</code>, <code>classes</code>, and <code>interfaces</code> to <code>JavaScript</code>, drawing parallels with languages like <code>C#</code> and <code>Java</code>. TypeScript code is transpiled to plain JavaScript, ensuring compatibility across various JavaScript environments.</p>
<p>While TypeScript and JavaScript can operate in the same environment, they exhibit key differences. The main one is that TypeScript is statically typed, providing type safety, while JavaScript is dynamically typed.</p>
<p>Let's delve into some of these differences:</p>
<p>TypeScript code is written in <code>.ts</code> or <code>.tsx</code> files, whereas JavaScript code resides in <code>.js</code> or <code>.jsx</code> files. The <code>.tsx</code> and <code>.jsx</code> extensions indicate that the file may contain JSX syntax, a popular choice for UI development in libraries like React.</p>
<p>Let's explore the differences between JavaScript and TypeScript through an example:</p>
<pre><code class="lang-js"><span class="hljs-comment">// JavaScript</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-keyword">return</span> a + b;
}

<span class="hljs-comment">// Calling the function</span>
add(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// Returns: 3</span>
</code></pre>
<p>In the JavaScript example above, the <code>add</code> function takes two parameters, <code>a</code> and <code>b</code>, and returns their sum. The function is invoked with the arguments <code>1</code> and <code>2</code>, yielding <code>3</code>. Notice that the function parameters are not annotated with types, which is typical in JavaScript.</p>
<p>Now, let's see how we can write the same function in TypeScript:</p>
<pre><code class="lang-ts"><span class="hljs-comment">// TypeScript</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span></span>): <span class="hljs-title">number</span> </span>{
  <span class="hljs-keyword">return</span> a + b;
}

<span class="hljs-comment">// Calling the function</span>
add(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// Returns: 3</span>
</code></pre>
<p>In the TypeScript version, we've annotated the parameters <code>a</code> and <code>b</code> with the <code>number</code> type. We've also specified that the function returns a <code>number</code>.</p>
<p>This is a key difference between JavaScript and TypeScript. TypeScript enforces type safety, meaning it checks the types of values at compile time and throws errors if they don't match the expected types.</p>
<p>This feature helps catch errors early in the development process, making TypeScript a popular choice for large-scale applications.</p>
<p>TypeScript and JavaScript are both powerful languages used in a wide range of applications. Let's summarize their key differences:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td>TypeScript</td><td>JavaScript</td></tr>
</thead>
<tbody>
<tr>
<td>Type System</td><td>Statically typed (types are checked at compile-time)</td><td>Dynamically typed (types are checked at run-time)</td></tr>
<tr>
<td>Superset</td><td>Yes, TypeScript is a superset of JavaScript</td><td>N/A</td></tr>
<tr>
<td>Compilation</td><td>Needs to be compiled (or transpiled) into JavaScript</td><td>Does not need to be compiled</td></tr>
<tr>
<td>OOP Features</td><td>Includes advanced OOP features such as interfaces, generics, and decorators</td><td>Supports OOP through prototypes, does not natively support interfaces or generics</td></tr>
<tr>
<td>Tooling</td><td>Offers better tooling with autocompletion, type checking, and source map support</td><td>Basic tooling</td></tr>
<tr>
<td>Community and Ecosystem</td><td>Newer, smaller community and ecosystem</td><td>Large community and vast ecosystem of libraries and frameworks since 1995</td></tr>
<tr>
<td>Learning Curve</td><td>Steeper due to additional features</td><td>Generally easier for beginners</td></tr>
<tr>
<td>Use Cases</td><td>Typically used in larger codebases where the benefits of type checking and autocompletion are most noticeable</td><td>Used for both client-side and server-side development, can be executed natively in the browser</td></tr>
</tbody>
</table>
</div><h2 id="heading-advantages-of-typescript">Advantages of TypeScript</h2>
<p>TypeScript offers several advantages over JavaScript:</p>
<ol start="2">
<li><p><strong>Improved Tooling</strong>: TypeScript's static typing enables better tooling support. Features like <code>autocompletion</code>, type <code>inference</code>, and type checking make the development process more efficient and enjoyable.</p>
</li>
<li><p><strong>Better Documentation</strong>: TypeScript codebases are often easier to understand and maintain. The type annotations serve as implicit documentation, making it easier to understand what kind of values a function expects and returns.</p>
</li>
<li><p><strong>Advanced Features</strong>: TypeScript supports advanced JavaScript features such as <code>decorators</code> and <code>async/await</code>, and it also introduces features not available in JavaScript, such as <code>interfaces</code>, <code>enums</code>, and <code>tuples</code>.</p>
</li>
<li><p><strong>Refactoring</strong>: TypeScript's tooling makes refactoring larger codebases safer and more predictable. You can make large-scale changes with confidence.</p>
</li>
<li><p><strong>Gradual Adoption</strong>: TypeScript is a superset of JavaScript, which means you can gradually adopt TypeScript in your projects. You can start by renaming your <code>.js</code> files to <code>.ts</code> and then you can gradually add type annotations as you see fit.</p>
</li>
<li><p><strong>Community and Ecosystem</strong>: TypeScript has a growing community and ecosystem. Many popular JavaScript libraries, such as React and Angular, have TypeScript definitions, which makes it easier to use them in a TypeScript project.</p>
</li>
</ol>
<h2 id="heading-code-generation">Code Generation</h2>
<p>TypeScript code isn't natively understood by browsers or Node.js, so it needs to be transpiled into JavaScript. This transpilation process is handled by the TypeScript compiler (<code>tsc</code>), which reads TypeScript code and generates equivalent JavaScript code.</p>
<p>To transpile a TypeScript file, you can use the <code>tsc</code> command followed by the filename:</p>
<pre><code class="lang-bash">$ tsc index.ts
</code></pre>
<p>This command transpiles the <code>index.ts</code> file into a <code>index.js</code> file in the same directory. The resulting JavaScript code can be executed in any JavaScript environment, such as a browser or Node.js.</p>
<h3 id="heading-watching-for-file-changes">Watching for File Changes</h3>
<p>During active development, it's beneficial to have your TypeScript code automatically recompiled whenever you make changes. The TypeScript compiler provides a <code>--watch</code> option for this purpose:</p>
<pre><code class="lang-shell">$ tsc index.ts --watch
</code></pre>
<p>With this command, the compiler will monitor the <code>index.ts</code> file and automatically recompile it whenever it detects a change.</p>
<h3 id="heading-configuring-the-typescript-compiler">Configuring the TypeScript Compiler</h3>
<p>For larger projects, it's common to have a configuration file, <code>tsconfig.json</code>, to manage compiler options. This file allows you to specify the root level files and the compiler options required to compile the project.</p>
<p>Here's an example of a <code>tsconfig.json</code> file:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"compilerOptions"</span>: {
    <span class="hljs-attr">"target"</span>: <span class="hljs-string">"es5"</span>,
    <span class="hljs-attr">"module"</span>: <span class="hljs-string">"commonjs"</span>,
    <span class="hljs-attr">"strict"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"outDir"</span>: <span class="hljs-string">"./dist"</span>
  },
  <span class="hljs-attr">"include"</span>: [<span class="hljs-string">"src/**/*.ts"</span>],
  <span class="hljs-attr">"exclude"</span>: [<span class="hljs-string">"node_modules"</span>]
}
</code></pre>
<p>In this configuration, the <code>compilerOptions</code> object contains options for the compiler. The <code>target</code> option specifies the ECMAScript target version, the <code>module</code> option sets the module system, the <code>strict</code> option enables a wide range of type checking behavior, and the <code>outDir</code> option specifies the output directory for the compiled JavaScript files.</p>
<p>The <code>include</code> and <code>exclude</code> options are used to specify the files to be compiled and ignored, respectively.</p>
<p>To compile the project based on the <code>tsconfig.json</code> file, you can run the <code>tsc</code> command without any arguments:</p>
<pre><code class="lang-bash">$ tsc
</code></pre>
<p>This command will compile all TypeScript files in the project according to the options specified in the <code>tsconfig.json</code> file.</p>
<h2 id="heading-typescript-basics">TypeScript Basics</h2>
<p>In this section , we'll go through the basics of TypeScript. You'll see more examples of how TypeScript is statically typed, and you'll learn more about its tooling and error checking.</p>
<h3 id="heading-installation">Installation</h3>
<p>Before we dive into TypeScript, you'll need to make sure that you have Node.js installed on your system. <code>Node.js</code> is a runtime environment that allows you to run JavaScript outside of the browser. You can download Node.js from the <a target="_blank" href="https://nodejs.org/en/download/">official website</a>.</p>
<p>Once Node.js is installed, you can install TypeScript using the Node Package Manager (npm), which comes bundled with Node.js.</p>
<p>Open your terminal and run the following command:</p>
<pre><code class="lang-bash">npm install -g typescript
</code></pre>
<p>This command installs TypeScript globally on your system. You can confirm the installation by running the <code>tsc</code> command, which stands for <code>TypeScript</code> <code>compiler</code>:</p>
<pre><code class="lang-bash">tsc --version
</code></pre>
<p>This command should display the version of TypeScript that you've installed.</p>
<p>Now that TypeScript is installed, we're ready to start our journey into the world of TypeScript!</p>
<h3 id="heading-configuration">Configuration</h3>
<p>Great! Now that we have TypeScript installed, let's talk about something else important: <code>configuration</code>. For larger projects, it's common to have a configuration file, <code>tsconfig.json</code>, to manage compiler options. This file allows you to specify the root level files and the compiler options required to compile the project.</p>
<p>When you run the <code>tsc</code> command, the compiler looks for a <code>tsconfig.json</code> file in the current directory. If it finds one, it uses the options specified in the file to compile the project. If it doesn't find one, it uses the default options.</p>
<p>To generate a <code>tsconfig.json</code> file, you can run the following command:</p>
<pre><code class="lang-bash">tsc --init
</code></pre>
<h3 id="heading-understanding-tsconfigjson">Understanding <code>tsconfig.json</code></h3>
<p>Now that we have TypeScript installed and configured, let's dive deeper into the <code>tsconfig.json</code> file. This file is a crucial part of any TypeScript project. It holds various settings that determine how your TypeScript code gets compiled into JavaScript.</p>
<p>To create a <code>tsconfig.json</code> file, you can use the <code>tsc --init</code> command as I showed above. This command generates a <code>tsconfig.json</code> file in your current directory with some default settings.</p>
<p>Here's an example of what a <code>tsconfig.json</code> file might look like:</p>
<pre><code class="lang-json">{
 <span class="hljs-attr">"compilerOptions"</span>: {
    <span class="hljs-attr">"target"</span>: <span class="hljs-string">"es5"</span>,
    <span class="hljs-attr">"module"</span>: <span class="hljs-string">"commonjs"</span>,
    <span class="hljs-attr">"strict"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"outDir"</span>: <span class="hljs-string">"./dist"</span>
 },
 <span class="hljs-attr">"include"</span>: [<span class="hljs-string">"src/**/*.ts"</span>],
 <span class="hljs-attr">"exclude"</span>: [<span class="hljs-string">"node_modules"</span>]
}
</code></pre>
<p>In this configuration:</p>
<ul>
<li><p>The <code>compilerOptions</code> object contains settings for the TypeScript compiler.</p>
</li>
<li><p>The <code>target</code> option tells the compiler which version of ECMAScript to compile your code down to.</p>
</li>
<li><p>The <code>module</code> option sets the module system for your project.</p>
</li>
<li><p>The <code>strict</code> option enables a wide range of type checking behavior.</p>
</li>
<li><p>The <code>outDir</code> option specifies the directory where the compiled JavaScript files will be placed.</p>
</li>
<li><p>The <code>include</code> and <code>exclude</code> options tell the compiler which files to include and exclude during the compilation process.</p>
</li>
</ul>
<p>After setting up your <code>tsconfig.json</code> file, you can compile your TypeScript project by simply running the <code>tsc</code> command in your terminal. This command will compile all TypeScript files in your project according to the options specified in your <code>tsconfig.json</code> file.</p>
<h3 id="heading-type-declarations-and-variables-in-typescript">Type Declarations and Variables in TypeScript</h3>
<p>Let's now learn more about types. TypeScript supports several types, including <code>number</code>, <code>string</code>, <code>boolean</code>, <code>object</code>, <code>null</code>, <code>undefined</code>, <code>symbol</code>, <code>bigint</code>, and <code>any</code>. Let's explore each of these types in detail.</p>
<ol>
<li><code>number</code>: This type is used for numeric values. It can be an integer or floating-point value.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> age: <span class="hljs-built_in">number</span> = <span class="hljs-number">30</span>;
<span class="hljs-keyword">let</span> weight: <span class="hljs-built_in">number</span> = <span class="hljs-number">65.5</span>;
</code></pre>
<ol start="2">
<li><code>string</code>: This type is used for textual data. It can be defined using single quotes, double quotes, or template literals.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> name: <span class="hljs-built_in">string</span> = <span class="hljs-string">'John Doe'</span>;
<span class="hljs-keyword">let</span> greeting: <span class="hljs-built_in">string</span> = <span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>`</span>;
</code></pre>
<ol start="3">
<li><code>boolean</code>: This type is used for logical values. It can only be <code>true</code> or <code>false</code>.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> isAdult: <span class="hljs-built_in">boolean</span> = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">let</span> isStudent: <span class="hljs-built_in">boolean</span> = <span class="hljs-literal">false</span>;
</code></pre>
<ol start="4">
<li><code>object</code>: This type is used for complex data structures. An object can have properties and methods.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> person: <span class="hljs-built_in">object</span> = { name: <span class="hljs-string">'John Doe'</span>, age: <span class="hljs-number">30</span> };
<span class="hljs-keyword">let</span> date: <span class="hljs-built_in">object</span> = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
</code></pre>
<ol start="5">
<li><code>null</code>: This type has only one value: <code>null</code>. It is used when you want to explicitly set a variable to have no value or object.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> emptyValue: <span class="hljs-literal">null</span> = <span class="hljs-literal">null</span>;
<span class="hljs-keyword">let</span> anotherEmptyValue: <span class="hljs-literal">null</span> = <span class="hljs-literal">null</span>;
</code></pre>
<ol start="6">
<li><code>undefined</code>: This type has only one value: <code>undefined</code>. It is used when a variable has been declared but has not yet been assigned a value.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> unassignedValue: <span class="hljs-literal">undefined</span> = <span class="hljs-literal">undefined</span>;
<span class="hljs-keyword">let</span> anotherUnassignedValue: <span class="hljs-literal">undefined</span>;
</code></pre>
<ol start="7">
<li><code>symbol</code>: This type is used to create unique identifiers for objects.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> symbol1: symbol = <span class="hljs-built_in">Symbol</span>(<span class="hljs-string">'symbol1'</span>);
<span class="hljs-keyword">let</span> symbol2: symbol = <span class="hljs-built_in">Symbol</span>(<span class="hljs-string">'symbol2'</span>);
</code></pre>
<ol start="8">
<li><code>bigint</code>: This type is used for whole numbers larger than <code>2^53 - 1</code>, which is the upper limit for the <code>number</code> type.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> bigNumber: bigint = <span class="hljs-number">9007199254740993n</span>;
<span class="hljs-keyword">let</span> anotherBigNumber: bigint = BigInt(<span class="hljs-number">9007199254740993</span>);
</code></pre>
<ol start="9">
<li><code>any</code>: This type is used when the type of a variable could be anything. It is a way of opting out of type-checking.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> variable: <span class="hljs-built_in">any</span> = <span class="hljs-string">'I am a string'</span>;
variable = <span class="hljs-number">42</span>; <span class="hljs-comment">// I am a number now</span>
</code></pre>
<p>Now let talk about some different ways you can declare variables in TypeScript.</p>
<p>TypeScript provides a way to define the shape of an object, including its properties and methods, using type declarations. This allows you to create reusable types that can be used to define the structure of objects throughout your codebase.</p>
<ol>
<li><strong>Type Aliases</strong>: Type aliases are a way to create a new name for an existing type. They are often used to define complex types that are used in multiple places.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Point = {
  x: <span class="hljs-built_in">number</span>;
  y: <span class="hljs-built_in">number</span>;
}

<span class="hljs-keyword">let</span> origin: Point = { x: <span class="hljs-number">0</span>, y: <span class="hljs-number">0</span> };
</code></pre>
<p>In this example, <code>Point</code> is a type alias for an object with <code>x</code> and <code>y</code> properties. It is used to define the type of the <code>origin</code> object.</p>
<ol start="2">
<li><strong>Intersection Types</strong>: Intersection types are a way to combine multiple types into a single type. They are often used to create complex types that have the properties of multiple other types.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Printable = {
  print: <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">void</span>;
};

<span class="hljs-keyword">type</span> Loggable = {
  log: <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">void</span>;
};

<span class="hljs-keyword">type</span> Logger = Printable &amp; Loggable;

<span class="hljs-keyword">let</span> logger: Logger = {
  print: <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Printing...'</span>),
  log: <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Logging...'</span>),
};
</code></pre>
<p>In this example, <code>Printable</code> and <code>Loggable</code> are two types that have a <code>print</code> and <code>log</code> method, respectively. The <code>Logger</code> type is an intersection of <code>Printable</code> and <code>Loggable</code>, so it has both a <code>print</code> and <code>log</code> method.</p>
<ol start="3">
<li><strong>Union Types</strong>: Union types are a way to define a type that can be one of several different types. They are often used to create flexible types that can represent a variety of values.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> ID = <span class="hljs-built_in">string</span> | <span class="hljs-built_in">number</span>;

<span class="hljs-keyword">let</span> id: ID = <span class="hljs-string">'123'</span>;
id = <span class="hljs-number">123</span>;
</code></pre>
<p>In this example, <code>ID</code> is a union type that can be either a <code>string</code> or a <code>number</code>. It is used to define the type of the <code>id</code> variable, which can be assigned a <code>string</code> or a <code>number</code>.</p>
<ol start="4">
<li><strong>Type Assertions</strong>: Type assertions are a way to tell the TypeScript compiler that you know more about the type of a value than it does. They are similar to type casting in other languages.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> value: <span class="hljs-built_in">any</span> = <span class="hljs-string">'Hello, TypeScript!'</span>;
<span class="hljs-keyword">let</span> length: <span class="hljs-built_in">number</span> = (value <span class="hljs-keyword">as</span> <span class="hljs-built_in">string</span>).length;
</code></pre>
<p>In this example, the <code>as</code> keyword is used to assert that <code>value</code> is of type <code>string</code>. This allows us to access the <code>length</code> property of the string.</p>
<h3 id="heading-functions-in-typescript">Functions in TypeScript</h3>
<p>Functions are the building blocks of any programming language. They encapsulate logic into reusable units of code, promoting code reuse and modularity. In TypeScript, functions can be defined using the <code>function</code> keyword or arrow functions (<code>=&gt;</code>). Both methods have their own use cases and characteristics.</p>
<p>Let's talk about some types of functions in TypeScript:</p>
<ol>
<li><strong>Function Declarations</strong>: Functions can be declared using the <code>function</code> keyword followed by a unique function name. The function body is enclosed in curly braces <code>{}</code>.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name: <span class="hljs-built_in">string</span></span>): <span class="hljs-title">void</span> </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>);
}

greet(<span class="hljs-string">'Alice'</span>);  <span class="hljs-comment">// Outputs: Hello, Alice!</span>
</code></pre>
<p>In this example, <code>greet</code> is a function that takes one parameter, <code>name</code>, of type <code>string</code>. The function doesn't return anything, so its return type is <code>void</code>.</p>
<ol start="2">
<li><strong>Arrow Functions</strong>: Arrow functions are a more modern syntax for writing functions in TypeScript and JavaScript. They are especially useful when writing small, inline functions.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> greet = (name: <span class="hljs-built_in">string</span>): <span class="hljs-function"><span class="hljs-params">void</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>);
}

greet(<span class="hljs-string">'Bob'</span>);  <span class="hljs-comment">// Outputs: Hello, Bob!</span>
</code></pre>
<p>In this example, <code>greet</code> is an arrow function that behaves exactly the same as the <code>greet</code> function in the previous example. The <code>=&gt;</code> symbol separates the function parameters and the function body.</p>
<ol start="3">
<li><strong>Function Types</strong>: In TypeScript, you can specify the types of the parameters and the return value of a function. This provides type safety, ensuring that the function is called with the correct types of arguments and that it returns the correct type of value.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span></span>): <span class="hljs-title">number</span> </span>{
  <span class="hljs-keyword">return</span> a + b;
}

<span class="hljs-keyword">let</span> sum: <span class="hljs-built_in">number</span> = add(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);  <span class="hljs-comment">// sum is 3</span>
</code></pre>
<p>In this example, the <code>add</code> function takes two parameters, <code>a</code> and <code>b</code>, both of type <code>number</code>, and returns a <code>number</code>.</p>
<ol start="4">
<li><strong>Optional and Default Parameters</strong>: TypeScript allows function parameters to be optional or have default values.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name: <span class="hljs-built_in">string</span>, greeting: <span class="hljs-built_in">string</span> = 'Hello'</span>): <span class="hljs-title">void</span> </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${greeting}</span>, <span class="hljs-subst">${name}</span>!`</span>);
}

greet(<span class="hljs-string">'Charlie'</span>);  <span class="hljs-comment">// Outputs: Hello, Charlie!</span>
greet(<span class="hljs-string">'Charlie'</span>, <span class="hljs-string">'Hi'</span>);  <span class="hljs-comment">// Outputs: Hi, Charlie!</span>
</code></pre>
<p>In this example, the <code>greet</code> function has two parameters, <code>name</code> and <code>greeting</code>. The <code>greeting</code> parameter is optional and has a default value of 'Hello'.</p>
<ol start="5">
<li><strong>Rest Parameters</strong>: TypeScript supports rest parameters, which allow you to pass an arbitrary number of arguments to a function.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">...numbers: <span class="hljs-built_in">number</span>[]</span>): <span class="hljs-title">number</span> </span>{
  <span class="hljs-keyword">return</span> numbers.reduce(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b, <span class="hljs-number">0</span>);
}

<span class="hljs-keyword">let</span> total: <span class="hljs-built_in">number</span> = sum(<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-comment">// total is 15</span>
</code></pre>
<p>In this example, the <code>sum</code> function takes an arbitrary number of arguments and returns their sum.</p>
<h3 id="heading-classes-and-objects-in-typescript">Classes and Objects in TypeScript</h3>
<p>Classes are a fundamental part of object-oriented programming (OOP). They are templates for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods).</p>
<p>TypeScript supports classes, which are declared using the <code>class</code> keyword. One advantage of TypeScript classes is that they support object-oriented programming (OOP) features such as <code>inheritance</code>, <code>encapsulation</code>, and <code>polymorphism</code>.</p>
<ol>
<li><strong>Class Declaration</strong>: In TypeScript, classes are declared using the <code>class</code> keyword.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">class</span> Person {
  name: <span class="hljs-built_in">string</span>;
  age: <span class="hljs-built_in">number</span>;

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params">name: <span class="hljs-built_in">string</span>, age: <span class="hljs-built_in">number</span></span>) {
    <span class="hljs-built_in">this</span>.name = name;
    <span class="hljs-built_in">this</span>.age = age;
  }

  greet(): <span class="hljs-built_in">void</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, my name is <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> and I am <span class="hljs-subst">${<span class="hljs-built_in">this</span>.age}</span> years old.`</span>);
  }
}

<span class="hljs-keyword">let</span> john = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">'John'</span>, <span class="hljs-number">25</span>);
john.greet(); <span class="hljs-comment">// Outputs: Hello, my name is John and I am 25 years old.</span>
</code></pre>
<p>In this example, <code>Person</code> is a class with two properties, <code>name</code> and <code>age</code>, and a method <code>greet</code>. The <code>constructor</code> is a special method for creating and initializing an object created with a class.</p>
<ol start="2">
<li><strong>Inheritance</strong>: TypeScript supports inheritance, a mechanism of basing a class upon another class, retaining similar implementation. Inheritance is achieved using the <code>extends</code> keyword.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">class</span> Employee <span class="hljs-keyword">extends</span> Person {
  department: <span class="hljs-built_in">string</span>;

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params">name: <span class="hljs-built_in">string</span>, age: <span class="hljs-built_in">number</span>, department: <span class="hljs-built_in">string</span></span>) {
    <span class="hljs-built_in">super</span>(name, age);
    <span class="hljs-built_in">this</span>.department = department;
  }

  greet(): <span class="hljs-built_in">void</span> {
    <span class="hljs-built_in">super</span>.greet();
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`I work in <span class="hljs-subst">${<span class="hljs-built_in">this</span>.department}</span>.`</span>);
  }
}

<span class="hljs-keyword">let</span> jane = <span class="hljs-keyword">new</span> Employee(<span class="hljs-string">'Jane'</span>, <span class="hljs-number">30</span>, <span class="hljs-string">'HR'</span>);
jane.greet(); <span class="hljs-comment">// Outputs: Hello, my name is Jane and I am 30 years old. I work in HR.</span>
</code></pre>
<p>In this example, <code>Employee</code> is a class that extends <code>Person</code>. It adds a new property <code>department</code> and overrides the <code>greet</code> method. The <code>super</code> keyword is used to call corresponding methods of the parent class.</p>
<ol start="3">
<li><strong>Abstract Classes</strong>: Abstract classes are classes that cannot be instantiated directly. They are used as base classes for other classes and can contain abstract methods that must be implemented by derived classes.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">abstract</span> <span class="hljs-keyword">class</span> Shape {
  <span class="hljs-keyword">abstract</span> area(): <span class="hljs-built_in">number</span>;
}

<span class="hljs-keyword">class</span> Circle <span class="hljs-keyword">extends</span> Shape {
  radius: <span class="hljs-built_in">number</span>;

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params">radius: <span class="hljs-built_in">number</span></span>) {
    <span class="hljs-built_in">super</span>();
    <span class="hljs-built_in">this</span>.radius = radius;
  }

  area(): <span class="hljs-built_in">number</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Math</span>.PI * <span class="hljs-built_in">this</span>.radius ** <span class="hljs-number">2</span>;
  }
}

<span class="hljs-keyword">let</span> circle = <span class="hljs-keyword">new</span> Circle(<span class="hljs-number">5</span>);
<span class="hljs-built_in">console</span>.log(circle.area()); <span class="hljs-comment">// Outputs: 78.54</span>
</code></pre>
<p>In this example, <code>Shape</code> is an abstract class with an abstract method <code>area</code>. The <code>Circle</code> class extends <code>Shape</code> and implements the <code>area</code> method. Abstract classes are useful for defining a common interface for a set of classes.</p>
<ol start="4">
<li><strong>Encapsulation</strong>: Encapsulation is the bundling of data (properties) and methods that operate on the data (methods) into a single unit called a class. In TypeScript, encapsulation is achieved by using access modifiers such as public, private, and protected.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">class</span> Person {
  <span class="hljs-keyword">private</span> name: <span class="hljs-built_in">string</span>;
  <span class="hljs-keyword">protected</span> age: <span class="hljs-built_in">number</span>;

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params">name: <span class="hljs-built_in">string</span>, age: <span class="hljs-built_in">number</span></span>) {
    <span class="hljs-built_in">this</span>.name = name;
    <span class="hljs-built_in">this</span>.age = age;
  }

  greet(): <span class="hljs-built_in">void</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, my name is <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> and I am <span class="hljs-subst">${<span class="hljs-built_in">this</span>.age}</span> years old.`</span>);
  }
}

<span class="hljs-keyword">let</span> john = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"John"</span>, <span class="hljs-number">25</span>);
<span class="hljs-built_in">console</span>.log(john.name); <span class="hljs-comment">// Error: Property "name" is private</span>
<span class="hljs-built_in">console</span>.log(john.age);  <span class="hljs-comment">// Error: Property "age" is protected</span>
</code></pre>
<p>In this example, <code>name</code> is a private property of the <code>Person</code> class, so it cannot be accessed from outside the class. <code>age</code> is a protected property, so it can be accessed from subclasses but not from outside the class.</p>
<ol start="5">
<li><strong>Polymorphism</strong>: Polymorphism is the ability of an object to take on many forms. In TypeScript, polymorphism is achieved through method overriding, where a method in a subclass has the same name and signature as a method in its superclass.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">class</span> Animal {
  speak(): <span class="hljs-built_in">void</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Animal makes a sound'</span>);
  }
}

<span class="hljs-keyword">class</span> Dog <span class="hljs-keyword">extends</span> Animal {
  speak(): <span class="hljs-built_in">void</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Dog barks'</span>);
  }
}

<span class="hljs-keyword">let</span> animal: Animal = <span class="hljs-keyword">new</span> Dog();
animal.speak(); <span class="hljs-comment">// Outputs: Dog barks</span>
</code></pre>
<p>In this example, <code>Animal</code> is a base class with a <code>speak</code> method. <code>Dog</code> is a subclass that overrides the <code>speak</code> method. When an instance of <code>Dog</code> is assigned to a variable of type <code>Animal</code>, the <code>speak</code> method of <code>Dog</code> is called.</p>
<ol start="6">
<li><strong>Access Modifiers</strong>: TypeScript supports the access modifiers <code>public</code>, <code>private</code>, and <code>protected</code>. By default, each member is <code>public</code>.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">class</span> Animal {
  <span class="hljs-keyword">private</span> name: <span class="hljs-built_in">string</span>;

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params">name: <span class="hljs-built_in">string</span></span>) {
    <span class="hljs-built_in">this</span>.name = name;
  }

  <span class="hljs-keyword">public</span> getName(): <span class="hljs-built_in">string</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.name;
  }
}

<span class="hljs-keyword">let</span> dog = <span class="hljs-keyword">new</span> Animal(<span class="hljs-string">'Dog'</span>);
<span class="hljs-built_in">console</span>.log(dog.getName()); <span class="hljs-comment">// Outputs: Dog</span>
</code></pre>
<p>In this example, <code>name</code> is a private member of the <code>Animal</code> class. It can only be accessed within the <code>Animal</code> class. The <code>getName</code> method is public, so it can be called from outside the class.</p>
<h3 id="heading-interfaces-in-typescript">Interfaces in TypeScript</h3>
<p>Interfaces in TypeScript are powerful ways to define contracts within your code. They are used to type-check whether an object fits a certain structure.</p>
<p>By defining an interface we can name a specific combination of variables, making sure they will always be used as a set.</p>
<ol>
<li><strong>Interface Declaration</strong>: Interfaces are declared with the <code>interface</code> keyword.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> Person {
  name: <span class="hljs-built_in">string</span>;
  age: <span class="hljs-built_in">number</span>;
}

<span class="hljs-keyword">let</span> john: Person = { name: <span class="hljs-string">'John'</span>, age: <span class="hljs-number">25</span> };
</code></pre>
<p>In this example, <code>Person</code> is an interface that describes an object that has a <code>name</code> of type <code>string</code> and an <code>age</code> of type <code>number</code>.</p>
<ol start="2">
<li><strong>Optional Properties</strong>: Interface properties can be marked as optional with <code>?</code>.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> Person {
  name: <span class="hljs-built_in">string</span>;
  age?: <span class="hljs-built_in">number</span>;
}

<span class="hljs-keyword">let</span> alice: Person = { name: <span class="hljs-string">'Alice'</span> };
</code></pre>
<p>In this example, <code>age</code> is an optional property in the <code>Person</code> interface. The object <code>alice</code> is still a <code>Person</code> even though it doesn't have an <code>age</code>.</p>
<ol start="3">
<li><strong>Function Types</strong>: Interfaces can also describe function types.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> GreetFunction {
  (name: <span class="hljs-built_in">string</span>, age: <span class="hljs-built_in">number</span>): <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">let</span> greet: GreetFunction = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">name: <span class="hljs-built_in">string</span>, age: <span class="hljs-built_in">number</span></span>): <span class="hljs-title">string</span> </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">`Hello, my name is <span class="hljs-subst">${name}</span> and I am <span class="hljs-subst">${age}</span> years old.`</span>;
};
</code></pre>
<p>In this example, <code>GreetFunction</code> is an interface that describes a function that takes a <code>name</code> and an <code>age</code> and returns a <code>string</code>.</p>
<ol start="4">
<li><strong>Extending Interfaces</strong>: Interfaces can extend one another, creating a new interface that inherits the members of the base interface.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> Animal {
  name: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">interface</span> Dog <span class="hljs-keyword">extends</span> Animal {
  breed: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">let</span> myDog: Dog = { name: <span class="hljs-string">'Rex'</span>, breed: <span class="hljs-string">'German Shepherd'</span> };
</code></pre>
<p>In this example, <code>Dog</code> extends <code>Animal</code>, so a <code>Dog</code> has both a <code>name</code> and a <code>breed</code>.</p>
<h3 id="heading-enums-in-typescript">Enums in TypeScript</h3>
<p>Enums are a way to define a set of named constants. They are often used to represent a set of related values, such as the days of the week or the months of the year.</p>
<p>TypeScript supports both numeric and string enums, providing a flexible way to define and work with sets of constants.</p>
<ol>
<li><strong>Numeric Enums</strong>: Numeric enums are a way to define a set of named constants with numeric values. By default, the values of the constants start at 0 and increment by 1 for each subsequent constant.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-built_in">enum</span> Day {
  Sunday,
  Monday,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday
}

<span class="hljs-keyword">let</span> today: Day = Day.Monday;
</code></pre>
<p>In this example, <code>Day</code> is a numeric enum that represents the days of the week. The constants <code>Sunday</code>, <code>Monday</code>, <code>Tuesday</code>, and so on are assigned numeric values starting from 0.</p>
<ol start="2">
<li><strong>String Enums</strong>: String enums are a way to define a set of named constants with string values. Unlike numeric enums, the values of the constants in a string enum are initialized with the value of the constant name.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-built_in">enum</span> Month {
  January = <span class="hljs-string">'January'</span>,
  February = <span class="hljs-string">'February'</span>,
  March = <span class="hljs-string">'March'</span>,
  April = <span class="hljs-string">'April'</span>,
  May = <span class="hljs-string">'May'</span>,
  June = <span class="hljs-string">'June'</span>,
  July = <span class="hljs-string">'July'</span>,
  August = <span class="hljs-string">'August'</span>,
  September = <span class="hljs-string">'September'</span>,
  October = <span class="hljs-string">'October'</span>,
  November = <span class="hljs-string">'November'</span>,
  December = <span class="hljs-string">'December'</span>
}

<span class="hljs-keyword">let</span> currentMonth: Month = Month.June;
</code></pre>
<p>In this example, <code>Month</code> is a string enum that represents the months of the year. The constants <code>January</code>, <code>February</code>, <code>March</code>, and so on are assigned string values equal to their names.</p>
<ol start="3">
<li><strong>Computed Enums</strong>: Enums can have computed values, which are initialized with an expression instead of a constant value. This allows for more flexibility in defining the values of the constants.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-built_in">enum</span> Color {
  Red = <span class="hljs-number">1</span>,
  Green = <span class="hljs-built_in">Math</span>.pow(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>),
  Blue = <span class="hljs-built_in">Math</span>.pow(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
}

<span class="hljs-keyword">let</span> color: Color = Color.Green;
</code></pre>
<p>In this example, <code>Color</code> is an enum with computed values. The constants <code>Red</code>, <code>Green</code>, and <code>Blue</code> are assigned the values 1, 4, and 8, respectively, using the <code>Math.pow</code> function.</p>
<ol start="4">
<li><strong>Reverse Mapping</strong>: Enums in TypeScript support reverse mapping, which means that you can access the name of a constant from its value. This is useful for debugging and logging purposes.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-built_in">enum</span> Day {
  Sunday,
  Monday,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday
}

<span class="hljs-keyword">let</span> dayName: <span class="hljs-built_in">string</span> = Day[<span class="hljs-number">1</span>]; <span class="hljs-comment">// 'Monday'</span>
</code></pre>
<p>In this example, the <code>Day</code> enum is used to access the name</p>
<h3 id="heading-generics-in-typescript">Generics in TypeScript</h3>
<p>Generics are a way to define a function or class that can be used with different types of data. They are often used to create reusable components that can work with different types of data.</p>
<p>TypeScript supports generics, allowing you to write type-safe code that is flexible and reusable.</p>
<p>Now let's look at some examples of generic functions and classes.</p>
<ol>
<li><strong>Generic Functions</strong>: Generic functions are functions that can work with a variety of data types. They are defined using type parameters, which are placeholders for the actual types that will be used when the function is called.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">identity</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params">value: T</span>): <span class="hljs-title">T</span> </span>{
  <span class="hljs-keyword">return</span> value;
}

<span class="hljs-keyword">let</span> result1: <span class="hljs-built_in">number</span> = identity&lt;<span class="hljs-built_in">number</span>&gt;(<span class="hljs-number">42</span>);
<span class="hljs-keyword">let</span> result2: <span class="hljs-built_in">string</span> = identity&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'Hello, TypeScript!'</span>);
</code></pre>
<p>In this example, <code>identity</code> is a generic function that takes a type parameter <code>T</code> and returns a value of type <code>T</code>. The type parameter <code>T</code> is used to specify the type of the argument and the return value.</p>
<ol start="2">
<li><strong>Generic Classes</strong>: Generic classes are classes that can work with a variety of data types. They are defined using type parameters, which are placeholders for the actual types that will be used when the class is instantiated.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">class</span> Box&lt;T&gt; {
  value: T;

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params">value: T</span>) {
    <span class="hljs-built_in">this</span>.value = value;
  }
}

<span class="hljs-keyword">let</span> box1: Box&lt;<span class="hljs-built_in">number</span>&gt; = <span class="hljs-keyword">new</span> Box&lt;<span class="hljs-built_in">number</span>&gt;(<span class="hljs-number">42</span>);
<span class="hljs-keyword">let</span> box2: Box&lt;<span class="hljs-built_in">string</span>&gt; = <span class="hljs-keyword">new</span> Box&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'Hello, TypeScript!'</span>);
</code></pre>
<p>In this example, <code>Box</code> is a generic class that takes a type parameter <code>T</code> and has a property <code>value</code> of type <code>T</code>. The type parameter <code>T</code> is used to specify the type of the value stored in the box.</p>
<ol start="3">
<li><strong>Generic Constraints</strong>: Generic constraints are a way to restrict the types that can be used with a generic function or class. They are defined using the <code>extends</code> keyword, followed by the type or interface that the type parameter must extend.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> Printable {
  print(): <span class="hljs-built_in">void</span>;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printValue</span>&lt;<span class="hljs-title">T</span> <span class="hljs-title">extends</span> <span class="hljs-title">Printable</span>&gt;(<span class="hljs-params">value: T</span>): <span class="hljs-title">void</span> </span>{
  value.print();
}

<span class="hljs-keyword">class</span> Person <span class="hljs-keyword">implements</span> Printable {
  print(): <span class="hljs-built_in">void</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Printing person...'</span>);
  }
}

<span class="hljs-keyword">let</span> person: Person = <span class="hljs-keyword">new</span> Person();
printValue(person);
</code></pre>
<p>In this example, <code>Printable</code> is an interface that defines a <code>print</code> method. The <code>printValue</code> function is a generic function that takes a type parameter <code>T</code> that must extend <code>Printable</code>. The <code>Person</code> class implements the <code>Printable</code> interface.</p>
<p>At this point you have a basic understanding of TypeScript and you can start diving into more advanced concepts.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you've learned the basics of TypeScript.</p>
<p>We talked about the basic syntax of TypeScript, such as variables, functions, and classes.</p>
<p>You also learned about TypeScript's built-in types, such as numbers, strings, and booleans.</p>
<p>We discussed TypeScript's built-in enumerations, such as number enums, string enums, and computed enums. And you learned about TypeScript's generic types, such as generic functions and classes.</p>
<p>Thank you for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is Abstraction in Coding? A Guide for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ I've met and talked to multiple new coders recently, and I see a common mistake they all seem to make. They don't embrace and understand abstractions in their code, or in their learning. But what are abstractions? And why are they important? Let's di... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-abstraction-in-coding/</link>
                <guid isPermaLink="false">66bc55f6da80a491ea5a5f65</guid>
                
                    <category>
                        <![CDATA[ abstraction ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kealan Parr ]]>
                </dc:creator>
                <pubDate>Tue, 19 Mar 2024 22:29:31 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/03/EmbraceAbstractions-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>I've met and talked to multiple new coders recently, and I see a common mistake they all seem to make.</p>
<p>They don't embrace and understand <strong>abstractions</strong> in their code, or in their learning.</p>
<p>But what are <strong>abstractions</strong>? And why are they important?</p>
<p>Let's dive in!</p>
<h2 id="heading-what-is-an-abstraction">What is an Abstraction?</h2>
<p>In coding, developers often use <strong>abstractions</strong> to simplify a system. <strong>Abstractions</strong> are a way of hiding complicated details from the end user, and trying to simplify whatever task you're trying to do.</p>
<p>But abstractions can be used in more than just code, so let's start with an example.</p>
<h3 id="heading-coffee-machine-abstractions">Coffee machine abstractions</h3>
<p>Imagine if you were creating a machine to make coffee for your users. There could be two approaches:</p>
<h4 id="heading-how-to-create-it-with-abstraction"><strong>How to Create it With Abstraction</strong></h4>
<ul>
<li>Have a button that says "Make coffee"</li>
</ul>
<h4 id="heading-how-to-create-it-without-abstraction"><strong>How to Create it Without Abstraction</strong></h4>
<ul>
<li>Have a button that says "Boil the water"</li>
<li>Have a button that says "Add the cold water to the kettle"</li>
<li>Have a button that says "Add 1 spoon of ground coffee to a clean cup"</li>
<li>Have a button that says "Clean any dirty cups"</li>
<li>And all the other buttons</li>
</ul>
<p>Can you see how, when we use abstraction, we don't expect the user to know how the machine makes coffee? But in the machine without abstraction, the user has to know in which order to press each button, which forces the user to understand how the coffee is made.</p>
<h2 id="heading-why-you-should-abstract-your-details">Why You Should Abstract Your Details</h2>
<p>When we use abstractions well, we make our system/codebase/task and so on much easier to understand and use. By hiding away complicated details inside a module, class, prototype, or function, we can make a super simple way to do complicated things.</p>
<p>So for example, let's say we have some complex code that ends up doing lots of complex, hard to understand math. We can wrap all that logic up in a function and provide a really easy interface where you just pass in your number and the function will do the work. </p>
<p>Developers in all languages and across all ecosystems make use of abstractions. The NodeJS team doesn't force you to understand how to modify 0's and 1's on a hard-drive to save text into a file – you can simply call the <code>writeFile</code> function.</p>
<p>When we use abstraction, we are essentially not forcing the person who uses our code to worry about the implementation details. They can just call the function and they'll get their answer back – they don't have to worry about what the function is doing "under the hood".</p>
<p><em>That's</em> the strength of abstracting details away in your code.  </p>
<p>I used to work at a company with a codebase that was 4 million lines long. Can you imagine a senior developer expecting me to understand every function? Every module? Every class? I would have NEVER merged a single change in that codebase if I did!</p>
<p>You can create a reusable, simple to understand, and easily changeable codebase by <strong>abstracting</strong> away certain details into the correct modules/separating out your code.</p>
<h2 id="heading-an-example-abstraction">An Example Abstraction</h2>
<p>Let's try and illustrate this with a code example.</p>
<p>Imagine you're working on a banking app, and you keep coming across this same weird subtraction over and over again, in different places in the code.</p>
<p><code>const res = bankAccountBalance - 1200</code></p>
<p><code>const res = bankAccountBalance – 1500</code></p>
<p><code>const res = bankAccountBalance - 1400</code></p>
<p>Why do we keep subtracting random numbers from everyone's bank balance once a year?! This is so unclear, there are zero comments explaining this?! What's happening? Is this an error?</p>
<p>Now imagine if this feature was clearer and did this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> minusFeesInUSDollars = <span class="hljs-function">(<span class="hljs-params">bankAccountBalance </span>) =&gt;</span> {
    <span class="hljs-comment">// Our yearly fees for this account are 1200 (USD)</span>
    <span class="hljs-keyword">const</span> YEARLY_FEES = <span class="hljs-number">1200</span>;
    <span class="hljs-keyword">return</span> bankAccountBalance - YEARLY_FEES;
}
<span class="hljs-keyword">const</span> minusFeesInGBPounds = <span class="hljs-function">(<span class="hljs-params">bankAccountBalance </span>) =&gt;</span> {
    <span class="hljs-comment">// Our yearly fees for this account are 1500 (GBP)</span>
    <span class="hljs-keyword">const</span> YEARLY_FEES = <span class="hljs-number">1500</span>;
    <span class="hljs-keyword">return</span> bankAccountBalance - YEARLY_FEES;
}
<span class="hljs-keyword">const</span> minusFeesInEuros = <span class="hljs-function">(<span class="hljs-params">bankAccountBalance </span>) =&gt;</span> {
    <span class="hljs-comment">// Our yearly fees for this account are 1400 (EUR)</span>
    <span class="hljs-keyword">const</span> YEARLY_FEES = <span class="hljs-number">1400</span>;
    <span class="hljs-keyword">return</span> bankAccountBalance - YEARLY_FEES;
}
</code></pre>
<p>The example isn't perfect, because we could remove some duplication in these functions – but we have abstracted logic into "something", in this case, a function.</p>
<h2 id="heading-why-should-i-embrace-abstractions">Why Should I Embrace Abstractions?</h2>
<p>I have explained <strong>abstractions</strong> so far in the context of code, but it can apply to your learning journey as well.</p>
<p>If you can't embrace <strong>abstractions</strong> (at least when you are starting) you will never be able to understand and excel as a developer.</p>
<p>Why is this the case?</p>
<p>Well, because there is always an <strong>abstraction</strong> beneath you, that you will be tempted to try and understand. This will ultimately frustrate you, overwhelm you, and <strong>kill your learning.</strong></p>
<p> Here's an example.</p>
<ol>
<li>You start to learn React.  </li>
</ol>
<p><em>This is going well! I'm starting to learn my first few bits of code and render some things to my computer screen. This is going well. 😊</em></p>
<ol start="2">
<li>You learn that React is a library of JavaScript.  </li>
</ol>
<p><em>Okay that's cool! I should learn a little bit of JavaScript before I start with React then. I'm going to stop learning React, and learn vanilla JavaScript first.</em></p>
<ol start="3">
<li>You learn JavaScript is a programming language made up of lots of different pieces.  </li>
</ol>
<p><em>Okay this is getting more complex now. There are JavaScript engines, third party API's, different runtimes. This is getting confusing.</em></p>
<ol start="4">
<li>You try to understand how an engine interprets JavaScript code.  </li>
</ol>
<p><em>Okay! So your JavaScript code is being run, by a piece of software coded in C++. What is C++?</em></p>
<ol start="5">
<li>You start to learn C++.  </li>
</ol>
<p><em>This learning journey isn't going so well anymore. This is starting to get very confusing and much longer.</em></p>
<ol start="6">
<li>You learn that C++ is simply an extension of C.   </li>
</ol>
<p><em>What on earth is C?!</em></p>
<p>...and so on.</p>
<p>If you continue to dig deeper and deeper and deeper, into every tiny little detail, you are much more likely to quit your learning journey, and it will only be because you feel overwhelmed.</p>
<p>And if by some miracle you haven't given up, you're going to spend a much, much longer time trying to learn some basic skills you might need for a job.</p>
<h2 id="heading-how-do-you-embrace-abstractions">How Do You Embrace Abstractions?</h2>
<p>As you're learning, you're going to have to get comfortable with not fully understanding some things in your learning journey.</p>
<p>You can just "abstract" this knowledge away, and stick to the things that are relevant to what you're currently doing.</p>
<p>Don't chase down every tiny little detail that you encounter if you are new in your learning journey. Truth is, even the experts don't know everything! They normally know lots of things in a narrow area.</p>
<h2 id="heading-one-day-you-can-dig-into-the-abstractions">One Day You Can Dig into the Abstractions</h2>
<p>I don't want this article to come across like I am saying you should never delve below the abstractions you use everyday. But what I am saying is it won't help you to delve into the abstractions <strong>before</strong> you have spent a decent time coding first.</p>
<p>You should try to learn things as you need to learn them if you are early in your journey to become a developer.</p>
<p>After all, learning to code is hard enough, without committing to learning the entire ecosystem before even understanding the basics.</p>
<p>Once you start to become comfortable in your learning journey, and want to improve your skills, <a target="_blank" href="https://www.hanselman.com/blog/please-learn-to-think-about-abstractions">then learn how your abstractions work</a>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I hope this has been useful, and is encouraging if you are feeling overwhelmed with everything you're currently learning.</p>
<p>I tweet my articles <a target="_blank" href="https://twitter.com/kealanparr">here</a> if you would like to read more.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Install React – A Step-by-Step Guide ]]>
                </title>
                <description>
                    <![CDATA[ React is an open-source JavaScript library that helps you build dynamic user interfaces (UIs). You can use it to build components that represent logically reusable parts of the UI. Because React is open source, anyone can access its source code, insp... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-install-react-a-step-by-step-guide/</link>
                <guid isPermaLink="false">66d45e043dce891ac3a967ce</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Okoro Emmanuel Nzube ]]>
                </dc:creator>
                <pubDate>Mon, 05 Feb 2024 12:43:22 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/solid-navy-blue-concrete-textured-wall.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>React is an open-source JavaScript library that helps you build dynamic user interfaces (UIs). You can use it to build components that represent logically reusable parts of the UI.</p>
<p>Because React is open source, anyone can access its source code, inspect it, modify it, and enhance it for their personal needs or app development requirements.</p>
<p>In this tutorial, you'll learn how to install React into your project.</p>
<h2 id="heading-how-to-install-react">How to Install React</h2>
<p>Now that you know what React is and why it's useful, you'll learn how to make use of this library in your project.</p>
<h3 id="heading-step-1-install-nodejs">Step 1: Install Node.js</h3>
<p>Before you start the React installation process, you must have Node.js installed on your computer. If you do not know what Node.js is all about, you can read more <a target="_blank" href="https://www.freecodecamp.org/news/what-is-node-js/">here</a>.</p>
<p>You have to install Node first because React.js is a JavaScript library, and Node.js is a JavaScript runtime environment that allows you to run JavaScript on the server side. So when you're writing React, you include JavaScript functions in your React project, and then Node.js helps run this JavaScript code on the web page.</p>
<p>Node.js has various versions. The recommended version is the latest stable version, as it contains major and significant changes. These changes includes bug fixes and security updates, compatibility with your project dependencies, and so on.</p>
<p>To install Node, navigate to the <a target="_blank" href="https://nodejs.org/en/">Node.js website</a>. On their webpage, you have the option to download either the recommended version or the current version, as seen in the image below.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Node.js.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Node.js web page interface</em></p>
<p>After you have downloaded the version of your choice, install it on your computer.</p>
<p>Once installation is complete, open your command prompt to confirm that Node has been successfully installed. Type in <code>node -v</code> in your command prompt, then click the enter button. This command should display the current version of Node installed on your computer.</p>
<p>Here is what it looks like:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/node-version-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Node version displayed in the command prompt</em></p>
<p>If your Node version is displayed like the above, congratulations! You have successfully installed Node.js on your computer.</p>
<h3 id="heading-step-2-install-react">Step 2: Install React</h3>
<p>Now you can go ahead and install React into your project. Let's go through the steps together.</p>
<p>First, we'll look at the "traditional" way of installing React, using create-react-app (CRA), so you're aware of that process. Then we'll see how to install it using the modern Vite build tool.</p>
<h4 id="heading-using-cra">Using CRA</h4>
<p>Still in your command prompt window, navigate to the directory that you want to use in creating your React project. To do this, type <code>cd [directory name]</code> then click enter.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-1_30_2024-9_53_23-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><code>cd documents</code> command to go to <code>documents</code> directory</p>
<p>As you can see in the image above, I am navigating to the <code>documents</code> directory, which is where I would like to create my React project.</p>
<p>In the <code>documents</code> directory (or wherever you're creating your project), create a folder that you will be using to create your React app. Type <code>mkdir [folder name]</code>then navigate to the newly created directory using <code>cd [newly created folder name]</code>.</p>
<p>In the newly created folder directory, type in <code>npx create-react-app [project name of your choice]</code>, and then wait until your React project is completely created. The final section should have the text in the image below displayed:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/React-project-2-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>React complete installation in the terminal</em></p>
<p>Lastly, open the React project in your code editor by typing in <code>code .</code> . Your code editor (if you are making use of VS code) should look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Welcome---reactproject---Visual-Studio-Code-1_30_2024-8_39_40-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>React Complete Installation Display Using CRA</em></p>
<p>In the above image, let's go over some of the elements you'll see there.</p>
<ul>
<li><p>The <code>node module</code> folder is a storage folder that holds your React package along with other packages that might be installed as you work on your React project. The <code>node module</code> helps configure the design system of your React project.</p>
</li>
<li><p>The <code>src</code> folder stores in all the files and components used in your react application ranging from the <code>App.js</code>, <code>index.js</code>, <code>App.css</code> just as seen in the image above.</p>
</li>
<li><p>The <code>package-lock.json</code> file locks the versions of dependencies your React project uses, and this helps in managing dependencies in your React project.</p>
</li>
</ul>
<p>Recently, create-react-app has become deprecated and the React team doesn't recommend using it anymore. Other modern tools provide a faster front-end development experience, and and you can use them to create React apps without stress. Such tools include Vite, Snowpack, Gatsby, Next.js, Percel, and so on.</p>
<p>In this section, you will learn how to use the Vite tool to install React into your project.</p>
<h4 id="heading-using-vite">Using Vite</h4>
<p>Vite is a very fast and customizable modern tool that aims to provide a linear development experience for modern web projects. You can use it to create your React apps in a fast and reliable way. It also has the same features as create-react-app (CRA).</p>
<p>Just as we did when installing React using CRA, the first step is to make sure you have Node installed on your computer. After that, navigate to the directory you want to use and create a new folder (with any name of your choice).</p>
<p>Open the newly created folder in your code editor (VS code).</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Vite_React---Visual-Studio-Code-2_2_2024-8_10_22-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Vite_React</em></p>
<p>The image above is what yours should look like. In my case, I named the folder I created <code>Vite_React</code>.</p>
<p>The next step is to open the terminal (located in between Run and Help), as seen in the image above.</p>
<p>Once in the terminal, run <code>npm create vite@latest [your project name]</code>. In my case the project named I used is <code>new-react-vite</code>. The above command should look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Vite_React---Visual-Studio-Code-2_2_2024-8_30_00-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Select Framework (React)</em></p>
<p>At this point, you are asked to select what framework you want to install, so since you are working on React, use your arrow keys to navigate to where we have React, then click on Enter.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Vite_React---Visual-Studio-Code-2_2_2024-8_36_40-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Select language (Javascript)</em></p>
<p>From the image above, the next step is to select what language you want for your project. You can choose any language of your choice, but for the sake of this tutorial, I chose JavaScript.</p>
<p>The next step is to navigate to the project directory where you created the React project. To do this, type <code>cd [directory name]</code>. Yours should look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Vite_React---Visual-Studio-Code-2_2_2024-8_44_16-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>React Complete Installation Using Vite</em></p>
<p>Once you have done this, you should see that your React files has been created and displayed on the screen like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Vite_React---Visual-Studio-Code-2_2_2024-8_49_58-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>React Installation Display</em></p>
<p>Last but not least, install the Node module folder by typing <code>npm install</code> in the terminal. This takes a little time to complete, but when installation is done, you should see the <code>node_module</code> folder at the top, like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Vite_React---Visual-Studio-Code-2_2_2024-9_02_48-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Node Modules folder</em></p>
<p>Lastly, type <code>npm run dev</code> to run your project and display on the web page. If you followed the installation steps correctly, you should see your local host:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/vite.config.js---Vite_React---Visual-Studio-Code-2_2_2024-9_11_55-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Local host</em></p>
<p>Hold your control button and click on your local host. This takes you to the web page. At this point, if your web page is displayed like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Vite---React---Google-Chrome-2_2_2024-9_16_47-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Final React Display on the web page</em></p>
<p>Congratulations on installing React on your project!</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The React library is a powerful open-source JavaScript tool you can use to create dynamic and appealing applications. It is actually a fun framework to get your hands on, so I recommend trying it out.</p>
<p>I believe at this point you can fully install React into your project with the modern tool (like Vite). If you've done it, congratulations again!</p>
<p>Happy Coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Contribute to Open-Source Projects – Git & GitHub Workflow for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ The first time I learned about open source was through a tweet that promoted Hacktoberfest in 2019. And my first-ever accepted pull request was to add a book title in emojis to a list. You might think, "You can't count that as an open source contribu... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/git-and-github-workflow-for-open-source/</link>
                <guid isPermaLink="false">66ba11dd7282cc17abcf0c6f</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Git ]]>
                    </category>
                
                    <category>
                        <![CDATA[ GitHub ]]>
                    </category>
                
                    <category>
                        <![CDATA[ open source ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ayu Adiati ]]>
                </dc:creator>
                <pubDate>Fri, 22 Sep 2023 12:35:14 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/09/Git---GitHub-Workflow-for-Beginners.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The first time I learned about open source was through a tweet that promoted Hacktoberfest in 2019. And my first-ever accepted pull request was to add a book title in emojis to a list.</p>
<p>You might think, "You can't count that as an open source contribution. That's a joke!"</p>
<p>I had the same thought myself — until recently. Getting my feet wet in open source was daunting, yet I got through it. And looking back, I learned a ton from that first contribution.</p>
<p>As a newbie who didn't know anything about open source, I learned how to communicate with the maintainers, how to work with Git and GitHub, and how to create a pull request. It was a big learning curve!</p>
<p>That is one of the reasons why I wrote this guide: to make your journey in contributing to open-source projects smoother and less daunting.</p>
<p>In this guide, I'll walk you through the basic Git and GitHub workflow when contributing to open-source projects. I'll also explain how to synchronize your forked and local repositories with the original repository and how to resolve merge conflicts when you encounter one.</p>
<p>Without further ado, let's get started!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></li>
<li><a class="post-section-overview" href="#heading-are-all-github-projects-open-source">Are all GitHub Projects Open Source?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-fork-a-repository">How to Fork a Repository</a></li>
<li><a class="post-section-overview" href="#heading-how-to-clone-a-repository">How to Clone a Repository</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-new-branch">How to Create a New Branch</a></li>
<li><a class="post-section-overview" href="#heading-how-to-add-changes-to-the-staging-area">How to Add Changes to the Staging Area</a></li>
<li><a class="post-section-overview" href="#heading-how-to-commit-changes">How to Commit Changes</a></li>
<li><a class="post-section-overview" href="#heading-how-to-synchronize-changes">How to Synchronize Changes</a></li>
<li><a class="post-section-overview" href="#heading-how-to-resolve-merge-conflicts">How to Resolve Merge Conflicts</a></li>
<li><a class="post-section-overview" href="#heading-how-to-push-changes">How to Push Changes</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-pull-request">How to Create a Pull Request</a></li>
<li><a class="post-section-overview" href="#heading-final-words">Final Words</a></li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To follow along with this tutorial, you'll need the following:</p>
<ul>
<li>A <a target="_blank" href="https://github.com/">GitHub</a> account.</li>
<li>A code editor like <a target="_blank" href="https://code.visualstudio.com/">VSCode</a> installed on your machine.</li>
</ul>
<h2 id="heading-are-all-github-projects-open-source">Are all GitHub Projects Open Source?</h2>
<p>When you're interested in making contributions, you should make sure that the project you're interested in is open source. You can't assume that all projects on GitHub are open source.</p>
<p>In this section, I will share what you should check to know if a project is open source.</p>
<h3 id="heading-the-license">The License</h3>
<p>The license is the first thing you want to check. A project on GitHub is not an open source unless it has a license.</p>
<p>In most jurisdictions, a project without a license is automatically licensed as "All Rights Reserved" by its owner. It means that no one may use, modify, or redistribute anything in the project without the permission of the owner. If you ignore it, they can legally sue you.</p>
<p>You can find the license in a file called <code>LICENSE</code>. You'd usually see in the "About" section of the repository.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/repo-about-section-github-2.png" alt="Image" width="600" height="400" loading="lazy">
<em>An MIT license in the "About" section on the right sidebar of a repository on GitHub</em></p>
<h3 id="heading-the-contribution-guide">The Contribution Guide</h3>
<p>Most open-source projects are ready to receive contributions when it has a contribution guide. This guide contains everything you should know about how to contribute to the project, from opening an issue to creating a pull request. From the code of conduct to the expected communication style.</p>
<p>The procedures and requirements for contributing to open-source projects may differ from one to another. You always want to read and follow the guide when contributing to a project.</p>
<p>Usually, you'll find a section about the contributing guide on the README. But if you can't find it there, look for a file called <code>CONTRIBUTING.md</code> or anything similar.</p>
<h3 id="heading-hacktoberfest-topic">Hacktoberfest Topic</h3>
<p><a target="_blank" href="https://hacktoberfest.com/">Hacktoberfest</a> is a yearly event in October sponsored by DigitalOcean to support open source. </p>
<p>To participate in this event and get your pull requests reviewed and counted, you should check whether a project is involved in Hacktoberfest before contributing.</p>
<p>A project participating in the event should have a <code>hacktoberfest</code> topic that you can find tagged in the "About" section of the repository's main page.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/about-repository-github.png" alt="Image" width="600" height="400" loading="lazy">
<em>The "About" section on the right sidebar of a repository with <code>hacktoberfest</code> as one of the topics — Credit: <a target="_blank" href="https://github.com/AliceWonderland/hacktoberfest">AliceWonderland/hacktoberfest</a></em></p>
<h2 id="heading-how-to-fork-a-repository">How to Fork a Repository</h2>
<p>So, you're ready to contribute to a repository of your choice. The first thing that you should do is to fork the repository.</p>
<p>Fork means creating a copy of a repository in your GitHub account.</p>
<p>You always want to fork a repository because most open-source project owners don't authorize contributors to push changes directly to their repositories.</p>
<p>By convention, your forked repository is called the <code>origin</code> repository, while the original repository is the <code>upstream</code> repository. I will use these aliases from now on to differentiate them.</p>
<p>At the repository's main page on GitHub, click the <code>Fork</code> button at the top right:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/fork-button.png" alt="Image" width="600" height="400" loading="lazy">
<em><code>Fork</code> button on GitHub</em></p>
<p>It will redirect you to the "Create a new fork" form. You can leave the inputs as it is. Then, click the green "Create fork" button at the bottom.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/create-new-fork.png" alt="Image" width="600" height="400" loading="lazy">
<em>A <code>Create a new fork</code> form with a green <code>Create fork</code> button on GitHub</em></p>
<p>This will create a copy of the repository in your GitHub account.</p>
<h2 id="heading-how-to-clone-a-repository">How to Clone a Repository</h2>
<p>After forking the repository, the next thing to do is to clone it.</p>
<p>Cloning a repo means creating a copy of a repository in your local environment. You should clone your forked repository when contributing to an open-source project.</p>
<p>Here are the steps to follow:</p>
<h4 id="heading-step-1-navigate-to-the-forked-repo">Step #1 - Navigate to the forked repo</h4>
<p>Navigate to your forked repository with these steps:</p>
<ul>
<li>Click your avatar on the top right.</li>
<li>Click <code>Your repositories</code> on the dropdown menu.</li>
<li>Click the repository that you want to clone to open it.</li>
</ul>
<p>Then click on the green <code>&lt;&gt; Code</code> button. Copy the HTTPS URL by clicking the copy icon.</p>
<p>To ensure that you are cloning the forked repository, you should see your GitHub username in the link. For example:</p>
<pre><code class="lang-text">https://github.com/&lt;github-username&gt;/&lt;repository-name&gt;.git
</code></pre>
<p>That is:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/avatar-github.png" alt="Image" width="600" height="400" loading="lazy">
<em>User's avatar on GitHub</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/dropdown-github-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>Dropdown menu on GitHub that highlights <code>Your repositories</code></em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/clone-github-resize-2.png" alt="Image" width="600" height="400" loading="lazy">
<em>A green <code>&amp;lt;&amp;gt; Code</code> button and a HTTPS URL of a repository followed by a copy icon on GitHub</em></p>
<h4 id="heading-step-2-clone-the-project-locally">Step #2 - Clone the Project Locally</h4>
<p>In your terminal, run the <code>git clone</code> command along with the URL that you copied:</p>
<pre><code class="lang-bash">git <span class="hljs-built_in">clone</span> &lt;copied-url&gt;
</code></pre>
<p>You can navigate to the project's directory with this command:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> &lt;project-name&gt;
</code></pre>
<h2 id="heading-how-to-create-a-new-branch">How to Create a New Branch</h2>
<p>The best practice in open source is to create a new branch whenever you are going to work on an issue. A new branch isolates your changes and keeps the <code>main</code> branch clean.</p>
<p>Run this command to create a new branch and navigate to it:</p>
<pre><code class="lang-bash">git checkout -b &lt;branch-name&gt;
</code></pre>
<p>Although you can give a branch any name, you should follow conventions related to naming a branch. A branch name usually refers to the change that you make. For example, <code>feature/add-dark-mode</code> or <code>bugfix/broken-link-to-about-page</code>.</p>
<p>Now you can start to make changes in your new branch.</p>
<h2 id="heading-how-to-add-changes-to-the-staging-area">How to Add Changes to the Staging Area</h2>
<p>Let's say you've finished working on changes. Before committing, you must first add them to the staging area.</p>
<p>This step allows you to keep your changes while you can still modify them before committing. It also lets you choose which change(s) you're ready to commit.</p>
<p>Adding changes to the staging area is often seen as a less critical step. But that's not true. This step allows you to change your mind before committing. Because once you commit your changes, you add a piece of story to the project's history.</p>
<h3 id="heading-how-to-add-single-or-multiple-files-to-the-staging-area">How to Add Single or Multiple Files to the Staging Area</h3>
<p>When you want to add one or multiple files — but not all — to the staging area, run this command:</p>
<pre><code class="lang-bash">git add &lt;file-name-1&gt; &lt;file-name-2&gt;
</code></pre>
<p>For example:</p>
<pre><code class="lang-bash">git add README.md CONTRIBUTING.md
</code></pre>
<p>The command above adds the <strong>README.md</strong> and <strong>CONTRIBUTING.md</strong> files to the staging area.</p>
<p>When you add nested files(s) to the staging area, you want to add the path(s) to the file(s). If you can't figure out the exact path, running <code>git status</code> will help give you the status of the files that contain your changes.</p>
<p>Here is how to do it:</p>
<p>Run <code>git status</code> in your terminal. You will see something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/git-status-modified-files-4.png" alt="Image" width="600" height="400" loading="lazy">
<em><code>git status</code> showing paths to three modified files on the VSCode terminal</em></p>
<p>Copy the path and run the <code>git add</code> command along with the path(s) to the file(s):</p>
<pre><code class="lang-bash">git add &lt;path-to-file-1&gt; &lt;path-to-file-2&gt;
</code></pre>
<p>Here is an example of adding paths to two files based on the screenshot above:</p>
<pre><code class="lang-bash">git add app/routes/__frontend/resources/index.mdx app/routes/__frontend/resources/developer-resources/open-source/index.mdx
</code></pre>
<h3 id="heading-how-to-add-all-files">How to Add All Files</h3>
<p>When you want to add all files to the staging area, run this command:</p>
<pre><code class="lang-bash">git add .
</code></pre>
<p>This adds all the files with changes to the staging area.</p>
<h2 id="heading-how-to-commit-changes">How to Commit Changes</h2>
<p>To commit means to record your changes. That is why a commit requires a message as the record. Over time, commits will tell the story of the project's history. So, a clear and descriptive commit message is essential.</p>
<p>What you should know when committing your changes:</p>
<ul>
<li><strong>Add and commit your changes often</strong>. The best time to add and commit your changes is every time you finish making a meaningful change, even if it's a small change. Committing your work once completed also prevents your changes from being carried over to other branches.</li>
<li><strong>Use a clear and descriptive message</strong>. "Change the background color from black to dark blue" is more descriptive and easy to understand by everyone than "Fix style".</li>
</ul>
<p>To make a commit, run this command in your terminal:</p>
<pre><code class="lang-bash">git commit -m <span class="hljs-string">"Your message"</span>
</code></pre>
<p>Here is an example of a single line commit:</p>
<pre><code class="lang-bash">git commit -m <span class="hljs-string">"Fix the link to the About page"</span>
</code></pre>
<p>And here's a commit with multiple lines:</p>
<pre><code class="lang-bash">git commit -m <span class="hljs-string">"Fix the link to the About page
Fix the typos in the About page"</span>
</code></pre>
<h2 id="heading-how-to-synchronize-changes">How to Synchronize Changes</h2>
<p>When you are working on changes, there is a possibility that the <code>main</code> branch on the <code>upstream</code> repository has already merged in some pull requests. So, the state of the <code>origin</code> and your local repositories at this time will no longer be the same as the <code>upstream</code>.</p>
<p>For this reason, you should always update your local working branch so you'll push the same state as the <code>upstream</code> repository.</p>
<h3 id="heading-how-to-update-the-origin-repository">How to Update the <code>origin</code> Repository</h3>
<p>First, go to the <code>origin</code> repository on GitHub to check if it's up to date with the <code>upstream</code>.</p>
<p>You can push your changes when no change exists in the <code>upstream</code> repository.</p>
<p>To know if the <code>origin</code> repository is up to date, you'll see a message that says, "This branch is up to date with " on the main page of the repository, as shown in the screenshot below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/up-to-date-branch-github-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>An up-to-date branch in the <code>origin</code> repository on GitHub</em></p>
<p>But when there are changes, you will see a message that says, "This branch is X commit(s) behind ".</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/branch-x-commits-behind-github-2.png" alt="Image" width="600" height="400" loading="lazy">
<em>A message indicating a branch in the <code>origin</code> repository is eight commits behind the <code>upstream</code> repository on GitHub</em></p>
<p>To update the <code>origin</code> repository:</p>
<ol>
<li>Click the <code>Sync fork</code> dropdown button.</li>
<li>Click the green <code>Update branch</code> button.</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/update-branch.png" alt="Image" width="600" height="400" loading="lazy">
<em>The <code>Sync fork</code> and <code>Update branch</code> buttons on GitHub</em></p>
<p>After it's updated, you will see a "Successfully fetched and fast-forwarded from upstream " notification at the top.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/successfully-fetched-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>A notification "Successfully fetched and fast-forwarded from upstream" on GitHub</em></p>
<h3 id="heading-how-to-pull-changes">How to Pull Changes</h3>
<p>Now that your <code>origin</code> is up to date with the <code>upstream</code> repository, it's time to pull the changes and update your local one.</p>
<p>Pull is a way of getting new changes from the remote to the local repository.</p>
<p>To pull the changes, ensure that you are on your working branch. You can do so by running <code>git status</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/git-status-branch.png" alt="Image" width="600" height="400" loading="lazy">
<em><code>git status</code> showing a branch name</em></p>
<p>Run the <code>git pull</code> command to pull the changes from the <code>main</code> branch in the <code>origin</code> repository:</p>
<pre><code class="lang-bash">git pull origin main
</code></pre>
<p>You can now push your changes if you don't need to resolve conflicts.</p>
<h2 id="heading-how-to-resolve-merge-conflicts">How to Resolve Merge Conflicts</h2>
<p>After updating your local repository, you might encounter conflicts that you must fix before you can push your changes.</p>
<p>It's common to encounter these conflicts in open source projects. Merge conflicts usually occur when there are changes in the same line(s) and file(s) from two different branches.</p>
<p>When a conflict arises, you will see options for accepting changes on top of your workspace in VSCode. You will also see another change(s) different from yours — the incoming change.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/git-conflict.png" alt="Image" width="600" height="400" loading="lazy">
<em>Options to accept change, the current change, and the incoming change on VSCode</em></p>
<h3 id="heading-how-to-fix-merge-conflicts">How to Fix Merge Conflicts</h3>
<p>You can choose from different options when you want to resolve a conflict:</p>
<ul>
<li><strong>Accept Current Change</strong>: When you wish to keep your changes only.</li>
<li><strong>Accept Incoming Change</strong>: When you want to accept only the incoming changes that aren't yours.</li>
<li><strong>Accept Both Changes</strong>: When you want to accept your changes and the incoming changes.</li>
</ul>
<p>You can still fix things if necessary after choosing the desirable action.</p>
<p>After resolving the conflicts, you can then add your changes to the staging area and commit them.</p>
<p>Since you'll add and commit changes in an existing file, you can run this command to do both actions at the same time:</p>
<pre><code class="lang-bash">git commit -am <span class="hljs-string">"Your message"</span>
</code></pre>
<h2 id="heading-how-to-push-changes">How to Push Changes</h2>
<p>Now, it's time to push your changes. This means moving changes from the local to the remote repository.</p>
<p>You always want to push your changes to the <code>origin</code> repository. To do that, run this command in your terminal:</p>
<pre><code class="lang-bash">git push origin &lt;branch-name&gt;
</code></pre>
<p>There's a possibility that you may get this error message:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/no-upstream-branch-1.png" alt="Image" width="600" height="400" loading="lazy">
<em><code>git push</code> message "fatal: The current branch &lt;branch-name&gt; has no upstream branch."</em></p>
<p>You can copy, paste, and run the command in the error message in your terminal:</p>
<pre><code class="lang-bash">git push --set-upstream origin &lt;branch-name&gt;
</code></pre>
<p> Alternatively, you can run this command:</p>
<pre><code class="lang-bash">git push -u origin &lt;branch-name&gt;
</code></pre>
<h2 id="heading-how-to-create-pull-request">How to Create Pull Request</h2>
<p>A pull request — commonly called a PR — is a way to notify others that a branch with changes has been pushed to a remote repository.</p>
<p>After a pull request is opened, maintainers can review and discuss your changes. They can ask you to make more changes before they can merge your pull request or merge them immediately into the <code>main</code> branch.</p>
<h3 id="heading-how-to-create-a-pull-request">How to Create a Pull Request</h3>
<p>First, go to the <code>upstream</code> or <code>origin</code> repository on GitHub. </p>
<p>Then click the green <code>Compare &amp; pull request</code> button to redirect to the <code>Open a pull request</code> form:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/compare-and-pull-request1.png" alt="Image" width="600" height="400" loading="lazy">
<em>The green <code>Compare &amp;amp; pull request</code> button on GitHub</em></p>
<p>Then fill out the pull request form. If there's a pull request template, complete all required areas to help maintainers review your changes.</p>
<p>If there is no pull request template, you can write the pull request in a structured manner. Consider this when writing your pull request:</p>
<ul>
<li>A short, clear, and informative title.</li>
<li>A clear description of the changes.</li>
<li>The link to the related issue. For example, "Closes #456".</li>
<li>Screenshots or screen recordings when necessary.</li>
</ul>
<p>Lastly, click the green <code>Create pull request</code> button at the bottom to create a PR.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/create-pull-request-button.png" alt="Image" width="600" height="400" loading="lazy">
<em>The green <code>Create pull request</code> on GitHub</em></p>
<h2 id="heading-final-words">Final Words</h2>
<p>Contributing to open-source projects can be daunting and make you feel intimidated at the beginning. But like other skills, with continuous practice, you will become better.</p>
<p>Besides understanding Git and GitHub, there are <a target="_blank" href="https://www.freecodecamp.org/news/how-to-contribute-to-open-source/">non-technical aspects of open source that you should know</a> too.</p>
<p>And once you get the grip, open source can be so much fun!</p>
<p>If you liked and enjoyed this article, please share it with others. You can find other works of mine on my <a target="_blank" href="https://adiati.com/">blog</a>, and let's connect on <a target="_blank" href="https://twitter.com/@AdiatiAyu">X (formerly Twitter)</a> or <a target="_blank" href="https://www.linkedin.com/in/adiatiayu/">LinkedIn</a>!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Contribute to Open Source Projects – Non-Technical Things You Should Know ]]>
                </title>
                <description>
                    <![CDATA[ I've contributed to open-source projects for a few years and learned a lot from the process. These experiences allowed me to look closer at the open source flow, from the technical, such as Git and GitHub, to the non-technical aspects. Although they ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-contribute-to-open-source/</link>
                <guid isPermaLink="false">66ba11e31a6c5fb4d0a38b3e</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ GitHub ]]>
                    </category>
                
                    <category>
                        <![CDATA[ open source ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ayu Adiati ]]>
                </dc:creator>
                <pubDate>Thu, 14 Sep 2023 17:34:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/09/How-to-Contribute-to-Open-Source-Projects-Non-Technical-Things-You-Should-Know--1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>I've contributed to open-source projects for a few years and learned a lot from the process. These experiences allowed me to look closer at the open source flow, from the technical, such as Git and GitHub, to the non-technical aspects.</p>
<p>Although they are as important as the technical sides, the non-technical ones often get overlooked. In this article, I will share the essential non-technical things you should know when contributing to open source projects. </p>
<h2 id="heading-what-are-the-important-files-in-a-repository">What are the Important Files in a Repository?</h2>
<p>In this section, we'll talk about some of the important files you'll likely come across when contributing to an open source project.</p>
<h3 id="heading-the-readmemd-file">The <code>README.md</code> File</h3>
<p>When you're interested in contributing to an open-source project, you should always read the <code>README.md</code> file — commonly called README — to familiarize yourself with the project.</p>
<p>The <code>README.md</code> file is the face of the project, containing everything essential. You'll usually find most, if not all, of these sections in a README:</p>
<ul>
<li>The project's description.</li>
<li>The technology used for the project.</li>
<li>Instructions on how to install, run, and use the project.</li>
<li>The project's license.</li>
<li>The code of conduct.</li>
<li>How to contribute to the project.</li>
<li>The expected communication style (through issue and pull request comments, GitHub discussion, chat service apps such as Slack or Discord, and so on).</li>
</ul>
<h3 id="heading-the-contributingmd-file"><strong>The</strong> <code>CONTRIBUTING.md</code> File</h3>
<p>Next, you must know the rules to follow in order to contribute to a project. The procedures and requirements for contributing may differ between projects. For example, in some projects, you're required to comment on an issue before it gets assigned to you, while others allow you to assign an issue to yourself.</p>
<p>The <code>CONTRIBUTING.md</code> file serves as a contribution guide. It explains the community's rules and expectations from their contributors, from creating an issue to creating a pull request.</p>
<p>In most cases, you'll find a contribution section in the README. But if it's not included in the README, you can find it in a file named <code>CONTRIBUTING.md</code> or anything similar.</p>
<h3 id="heading-the-license-file">The <code>LICENSE</code> File</h3>
<p>You can't just assume that all projects on GitHub are open-source and that their codebase is freely available.</p>
<blockquote>
<p>"In most jurisdictions, any code or content is automatically copyrighted by the author, with all rights reserved, unless otherwise stated." (Source: <a target="_blank" href="https://arstechnica.com/gadgets/2020/02/how-to-choose-an-open-source-license/">Open source licenses: What, which, and why</a>)</p>
</blockquote>
<p>"All rights reserved" means that no one may use, modify, or redistribute anything in the project unless the owner gives you permission to. If you ignore it, they can legally sue you. So, a project on GitHub is only open source if they have a license that specifies that.</p>
<p>You'd usually find a license section on the README, in the "About" section of a repository. It is found in a file called <code>LICENSE</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/repo-about-section-github-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>An MIT license in the "About" section on the right sidebar of a repository on GitHub</em></p>
<h3 id="heading-the-codeofconductmd-file">The <code>CODE_OF_CONDUCT.md</code> File</h3>
<p>You should habitually read the community's Code of Conduct (COC). The COC is the house rule of the community. It is there for a reason: to maintain a safe, welcoming space for contributors. Following the COC will prevent you from getting banned from the community and the project.</p>
<p>You can find the COC in a file called <code>CODE_OF_CONDUCT.md</code>, in the "About" section on of the repository. Most times, it's also included in the README and contributing guide.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/code-of-conduct-on-github.png" alt="Image" width="600" height="400" loading="lazy">
<em>Code of Conduct in the "About" section on the right sidebar of a repository on GitHub</em></p>
<h2 id="heading-ethics-in-open-source"><strong>Ethics in Open Source</strong></h2>
<h3 id="heading-check-for-duplication">Check for Duplication</h3>
<p>Let's say you install and run a project on your local machine and encounter a bug. Or you read through the docs and find a missing step. You might want to raise an issue to address it.</p>
<p>Before doing so, you must check if a similar (open and closed) issue or pull request has been raised to avoid duplication. Enter possible keywords in the search bar on top of the issue or pull request page on GitHub to check for possible duplication.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/search-bar-github.png" alt="Image" width="600" height="400" loading="lazy">
<em>Search bar on top of the issue or pull request page on GitHub</em></p>
<p>For example:</p>
<pre><code class="lang-text">is:issue is:open docs
</code></pre>
<pre><code class="lang-text">is:pull request is:closed button
</code></pre>
<p>Checking for duplicates will help prevent your issue or pull request from getting turned down by maintainers.</p>
<h3 id="heading-ask-for-permission-before-working-on-an-issue">Ask for Permission before Working on an Issue</h3>
<p>One of the essential ethics in open source is asking for the maintainer's permission to work on an issue unless stated otherwise in the contribution guide. Asking for permission helps the maintainers in controlling and avoiding duplicate pull requests.</p>
<p>You only want to work on changes and create a pull request after you get the green light from a maintainer. If you ignore this part and go ahead to work on the changes, your pull request will likely be ignored or turned down. This is because the issue may have been assigned to someone else already, or the issue may not be their priority at that moment. </p>
<p>Either way, it would be a loss for you. So, what should you do when asking for permission?</p>
<h4 id="heading-1-check-if-the-issue-has-already-been-assigned">1. Check if the issue has already been assigned</h4>
<p>You can see if an issue has been assigned by looking at the "Assignee" column when you open the issue tab in the GitHub repository or on the right sidebar when you open the issue.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/issue-tab-github-01-3.png" alt="Image" width="600" height="400" loading="lazy">
<em>Assignee column on the issues page on GitHub</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/issue-right-sidebar-01-3.png" alt="Image" width="600" height="400" loading="lazy">
<em>Assignees section on the right sidebar of the issue page on GitHub</em></p>
<h4 id="heading-2-check-the-comment-threads">2. Check the comment threads</h4>
<p>You also want to make sure that someone has not already asked the maintainers to assign the issue to them. If they haven't gotten any response, then the maintainers have probably not seen the comment. You should also check other information in the threads to understand more about the issue.</p>
<h4 id="heading-3-leave-a-comment-to-request-for-an-issue-you-want-to-work-on">3. Leave a comment to request for an issue you want to work on</h4>
<p>You can say, "Hi, I want to work on this issue. Can you assign it to me?" Or, "I see this issue has been assigned, but I haven't seen any activity here in a while. If you still need help, can I work on this?"</p>
<h4 id="heading-4-wait-until-the-maintainer-replies-to-your-message">4. Wait until the maintainer replies to your message</h4>
<p>If they (the maintainer(s)) say you can have it and assign it to you, then you can start working on the issue and, in the end, create a pull request.</p>
<h3 id="heading-what-is-the-good-first-issue-label">What is the Good First Issue Label?</h3>
<p>Labels on GitHub are tags that pass information about the type or the status of an issue or a pull request. A <code>good-first-issue</code> is a label considered appropriate for beginners by the project's owner and maintainers.</p>
<p>I once created an issue about a broken link. I explained the bug and the steps contributors must take to resolve it.</p>
<p>I also mentioned that this issue is beginner-friendly, so we want to leave it for beginners who wish to contribute to the project. After passing the review from the maintainers, the issue was labeled as a <code>good-first-issue</code>.</p>
<p>The sad part was that people who deliberately took the issue were not beginners.</p>
<p>If you already have some experience, please consider leaving this label. It is meant for beginners in open source or the technology used in the project.</p>
<h3 id="heading-good-communication-and-patience">Good Communication and Patience</h3>
<p>Always use clear and polite words to communicate with maintainers and other contributors. Remember that async communication is prone to loss in translation and miscommunication.</p>
<p>If you need more clarification on something, ask the maintainers. Don't make assumptions. You can ask questions in the issue or pull request comments. Some communities also have a GitHub discussions board that you can find on the top bar, while some use chat service apps like Slack or Discord to share ideas and ask questions or clarifications.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/discussion-tab-github.png" alt="Image" width="600" height="400" loading="lazy">
<em>Discussions tab on GitHub</em></p>
<p>A maintainer may ask you to fix something in your pull request or ask for clarifications using a straightforward sentence. Short and direct messages mostly happen because they are busy. They must be fast and effective in replying to messages. Don't take it personal as this may lead to poor communication or even lead to losing your chance at contributing.</p>
<p>Most of the maintainers and contributors in open source are volunteers. That said, they have life and other duties outside of the project. So, when you're contributing, you need to have patience. Don't ask maintainers to immediately answer your question or merge your pull request.</p>
<h3 id="heading-write-issue-and-pull-request-in-a-structured-way">Write Issue and Pull Request in a Structured Way</h3>
<p>Some open-source communities provide templates on GitHub for opening an issue or creating a pull request. But when they don't, consider writing them in a structured manner. It would be handy for everyone to see the details and help maintainers review and merge pull requests.</p>
<h4 id="heading-how-to-write-a-github-issue">How to Write a GitHub Issue</h4>
<p>Here are some things to consider when writing an issue:</p>
<p><strong>Use c</strong>lear and descriptive title<strong>s</strong>: By reading a clear and descriptive title, everyone can understand the issue. For example, "fix: Link to the About page leads to 404".</p>
<p><strong>Search</strong> for <strong>similar issues</strong>: Check open and closed issues to see if there is a similar or identical issue as yours. If you don't find any, then include in the description that you've checked and did not find any similar issues. This step is essential to avoid any duplication.</p>
<p><strong>Description of the issue</strong>: Describe the issue as straightforward as possible.</p>
<p><strong>Expected behavior</strong>: Describe the expected behavior of an issue.</p>
<p><strong>Actual behavior</strong>: State the actual problematic behavior that causes the issue.</p>
<p><strong>Reproduce the problem</strong>: What steps do we need to take to reproduce the problem? It would be helpful for everyone to run the same steps and test it out. Here's an example:</p>
<pre><code class="lang-markdown"><span class="hljs-bullet">1.</span> Go to this link.
<span class="hljs-bullet">2.</span> Click this button.
<span class="hljs-bullet">3.</span> This is what is happening.
</code></pre>
<p><strong>Screenshots or screen recording</strong>s: Provide some screenshots or screen recordings if necessary. It is usually beneficial for UI issues.</p>
<p><strong>Suggest a solution</strong>: If you have a solution in mind, you can give a suggestion. But if you don't, it's okay too. You are not expected to have a solution when you raise an issue.</p>
<p>Here's an examples that uses the points listed above:</p>
<pre><code class="lang-markdown"><span class="xml"><span class="hljs-comment">&lt;!-- Issue title --&gt;</span></span>
<span class="hljs-section"># fix: Link to the About page leads to 404</span>

<span class="xml"><span class="hljs-comment">&lt;!-- Issue body --&gt;</span></span>
<span class="hljs-section">## Description</span>

When I went to the About page, I got a 404.
I have searched and didn't find any similar issues.

<span class="hljs-section">## Expected Behavior</span>

We should see the About section when we go to the About page.

<span class="hljs-section">## Actual Behaviour</span>

When we go to the About page, we see a 404 page.

<span class="hljs-section">## How to Reproduce</span>

<span class="hljs-bullet">1.</span> Go to the https://website.com.
<span class="hljs-bullet">2.</span> Click the About tab.
<span class="hljs-bullet">3.</span> You will see the 404.

<span class="hljs-section">## Screenshots</span>

![<span class="hljs-string">404 in about page</span>](<span class="hljs-link">link to the image</span>)

<span class="hljs-section">## Suggestion</span>

Fix and use the correct link to the About page.
</code></pre>
<h4 id="heading-how-to-write-a-pull-request">How to Write a Pull Request</h4>
<p>Here are some things to consider when writing a pull request:</p>
<p><strong>Use a s</strong>hort, clear, and informative title<em>**</em>: For example, "fix: Link to About page".</p>
<p><strong>Use a </strong>clear description of the fix<em>**</em>: For example, "This pull request fixes the link to the About page that previously led to 404."</p>
<p><strong>Link to the</strong> related <strong>issue</strong>: Include the link to the related issue. For example, "Fixes #123".</p>
<p><strong>Screenshots or screen recording</strong>s: Provide some screenshots or screen recordings that shows the issue before and after the fix if necessary.</p>
<p>Here's an example that uses the structure above:</p>
<pre><code class="lang-markdown"><span class="xml"><span class="hljs-comment">&lt;!-- Pull request title --&gt;</span></span>
<span class="hljs-section"># fix: Link to About page</span>

<span class="xml"><span class="hljs-comment">&lt;!-- Pull request body --&gt;</span></span>
<span class="hljs-section">## Related Issue</span>

Fixes #123

<span class="hljs-section">## Description</span>

This PR fixes the link to the About page that previously led to 404.

<span class="hljs-section">## Screenshots</span>

<span class="hljs-section">### Before</span>

![<span class="hljs-string">404 in about page</span>](<span class="hljs-link">link to the image</span>)

<span class="hljs-section">### After</span>

![<span class="hljs-string">About page</span>](<span class="hljs-link">link to the image</span>)
</code></pre>
<h2 id="heading-good-to-know-contributing-to-open-source-is-not-all-about-code">Good to Know: Contributing to Open Source is Not All About Code</h2>
<p>I often hear that people — especially beginners — hesitate to contribute to open source because they need more skills or time to help with code. However, contributing to an open-source project is involves more than just code.</p>
<p>There are many non-technical ways to contribute to a project and its community, such as:</p>
<ul>
<li>Opening an issue when you see a bug or room for improvement.</li>
<li>Reviewing issues and pull requests.</li>
<li>Improving the project's documentation.</li>
<li>Answering questions.</li>
<li>Throwing ideas around the project.</li>
<li>Onboarding new contributors.</li>
<li>Mentoring other contributors.</li>
<li>Writing a blog post or creating a video about the project.</li>
<li>Promoting the project on social media, and many more!</li>
</ul>
<h2 id="heading-final-words">Final Words</h2>
<p>Contributing to open-source projects is not all about understanding Git and GitHub. Some non-technical things are important for you to know, too. I hope this article helps.😊</p>
<p>If you liked and enjoyed this article, please share it. You can find other works of mine on my <a target="_blank" href="https://adiati.com">blog</a>, and let's connect on <a target="_blank" href="https://twitter.com/@AdiatiAyu">X (formerly Twitter)</a> or <a target="_blank" href="https://www.linkedin.com/in/adiatiayu/">LinkedIn</a>!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Contribute to Open-Source Projects – A Handbook for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ Over the past decade, open-source projects have become the backbone of the technology ecosystem. They power everything from applications to innovations across different fields. These collaborative inventions bring together people with different skill... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-contribute-to-open-source-handbook/</link>
                <guid isPermaLink="false">66b8dbd4abe19f6180038a2b</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Collaboration ]]>
                    </category>
                
                    <category>
                        <![CDATA[ community ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ open source ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Hillary Nyakundi ]]>
                </dc:creator>
                <pubDate>Wed, 06 Sep 2023 15:39:30 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/09/How-to-Contribute-to-Open-Source--with-photo--Cover--1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Over the past decade, open-source projects have become the backbone of the technology ecosystem. They power everything from applications to innovations across different fields.</p>
<p>These collaborative inventions bring together people with different skill sets including developers, designers, and tech enthusiasts in general with one goal in mind to build: to improve and share software freely.</p>
<p>The open source movement champions the idea that knowledge should be accessible to all, and fosters a culture of openness, transparency, and cooperation.</p>
<p>Contributing to open source has many benefits not only for those taking part in it but also the community at large.</p>
<p>Now, if you are just a beginner trying to get into the open-source world, you should keep in mind that you are embarking on a journey that will not only improve your technical skills but also open many doors for you and give you multiple opportunities to interact with like-minded individuals.</p>
<p>This is just a portion of what you can achieve. You'll also have an opportunity to:</p>
<ul>
<li><p>Create an impact through your work</p>
</li>
<li><p>Build your portfolio</p>
</li>
<li><p>Network and connect with other devs, and</p>
</li>
<li><p>Give back to the developer community.</p>
</li>
</ul>
<p>This beginner friendly handbook is crafted to be your companion as you begin your journey into the world of open-source. It will cover concepts that will allow a beginner like you to make your mark in the open-source world.</p>
<p>We will start with the fundamentals of open source, and I'll guide you through setting up your development environment, navigating open-source communities, selecting the right projects, and making your first contribution.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-open-source-software">What is Open-Source Software?</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-characteristics-of-open-source-software">Characteristics of Open-Source Software</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-types-of-open-source-licenses">Types of Open-Source Licenses</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-benefits-of-contributing-to-open-source-projects">Benefits of Contributing to Open-Source Projects</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-get-started-with-open-source-contributions">How to Get Started with Open-Source Contributions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-navigate-open-source-communities">How to Navigate Open-Source Communities</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-understanding-community-dynamics">Understanding community dynamics</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-find-and-join-open-source-communities">How to Find and Join Open-Source Communities</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-etiquette-communication-norms-and-best-practices">Etiquette, Communication Norms, and Best Practices</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-set-up-a-development-environment">How to Set Up a Development Environment</a></p>
<ul>
<li><p><a class="post-section-overview" href="#howtoinstallthenecessarytools">How to Install the Necessary Tools</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-text-editors-and-integrated-development-environments-ides">Text Editors and Integrated Development Environments (IDEs)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-version-control-systems-1">Version control systems</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-fork-clone-and-set-up-projects">How to fork, clone, and set up projects</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-understanding-project-structure-and-workflow">Understanding Project Structure and Workflow</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-make-your-first-contribution">How to Make Your First Contribution</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-step-by-step-guide-to-making-a-contribution">Step-by-Step Guide to Making a Contribution</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-collaboration-within-the-community">Collaboration within the Community</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-beyond-code-non-coding-contributions">Beyond Code: Non-Coding Contributions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-best-practices-for-quality-contributions">Best Practices for Quality Contributions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-handle-challenges">How to Handle Challenges</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-showcase-your-open-source-contributions">How to Showcase Your Open-Source Contributions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-additional-resources">Additional Resources</a></p>
</li>
</ul>
<p>By the end of this guide you will be equipped with the necessary skills to become an active member of the open-source community. This is the beginning of your open source journey where you will get to continuously learn, collaborate with others, and create an impact. Let's get started!</p>
<h2 id="heading-what-is-open-source-software">What is Open-Source Software?</h2>
<p>In simple words, open source can be described as source code and projects that are made available to the public to view, use, modify, and distribute under a permissive license.</p>
<p>Open-source projects are usually developed in a collaborative manner, mostly by a community of volunteers. Unlike proprietary software, which is usually controlled by a single entity, open source promotes transparency, collaboration, and innovation through community support.</p>
<p>Open-source projects don't only empower their users to use the projects themselves, but also gives them an opportunity to understand how the project works, contribute to its growth, and improve it too.</p>
<p>The main idea behind the open-source software is not only to share the code but create communities with a culture of collaboration, transparency and shared learning.</p>
<p>With this approach in mind, the open-source world has given a rise to some of the most innovative and impactful technologies in use today.</p>
<h3 id="heading-characteristics-of-open-source-software">Characteristics of Open-Source Software</h3>
<ul>
<li><p><strong>Free to use</strong> - users can feely use, modify and redistribute the software.</p>
</li>
<li><p><strong>Transparent</strong> - source code is accessible to all. This promotes trust among the users, as well as openness amongst developers who peer review and fix bugs.</p>
</li>
<li><p><strong>Collaborative</strong> - most open source projects promote collaboration, which enables different people from around the world to contribute their skills, ideas, and expertise.</p>
</li>
<li><p><strong>Community-driven</strong> - open-source projects foster and promote the building of strong communities of like minded individuals with common goals.</p>
</li>
<li><p><strong>Diversity</strong> - brings together people from different backgrounds who share a common goal.</p>
</li>
<li><p><strong>Continuous Improvement</strong> - open source software is continuously evolving. This means that bugs are fixed regularly, new features are added often, and updates are released from time to time.</p>
</li>
<li><p><strong>Licensing</strong> - each open source software has a license that protects the rights of both authors and users, enabling the software's continued openness.</p>
</li>
</ul>
<h3 id="heading-types-of-open-source-licenses">Types of Open-Source Licenses</h3>
<p>Open-source licenses protect the rights of both the authors and the users. They also define terms under which the software can be used, modified, and distributed.</p>
<p>Some of the most common licenses are:</p>
<ul>
<li><p><strong>GNU General Public License (GPL)</strong> - this guarantees the end user the freedom to run, study, share and modify the software.</p>
</li>
<li><p><strong>MIT License</strong> - originates from the Massachusetts Institute of Technology (MIT). It permits reuse of proprietary software.</p>
</li>
<li><p><strong>Apache License</strong>- commonly used for projects associated with the Apache software Foundation.</p>
</li>
<li><p><strong>BSD Licenses</strong> - they are a family of free software licenses that impose minimal restrictions on the use and distribution of covered software.</p>
</li>
<li><p><strong>Mozilla Public License (MPL)</strong> - this is a copyleft license that will require the authors to share modifications they make on your code.</p>
</li>
<li><p><strong>Creative Commons Licenses</strong> - most commonly used not only in software but for other creative works, too. Used when an author wants to give other people right to share, use, and build upon their work.</p>
</li>
</ul>
<p>Having an understanding of these licenses at an early stage is really important as they dictate how your contributions can be used and distributed.</p>
<h2 id="heading-benefits-of-contributing-to-open-source-projects">Benefits of Contributing to Open-Source Projects</h2>
<p>Contributing to open source can be a rewarding way to learn, teach, share, and build experience. There are plenty of benefits that extend beyond the contributions you make.</p>
<p>By contributing to open-source projects you can:</p>
<ul>
<li><p><strong>Learn and Grow</strong> - It will open different avenues for you by giving you an opportunity to experience real world development practices, code review processes, problem solving techniques, and so on.</p>
</li>
<li><p><strong>Build a Portfolio</strong> - Your contributions serve as a proof of your skills, which can be helpful when applying for jobs.</p>
</li>
<li><p><strong>Community and Networking</strong> - It gives you the opportunity to engage and interact with like-minded individuals from around the world. It opens doors for mentors and professional contacts who can guide you.</p>
</li>
<li><p><strong>Solving Real Problems</strong> - Some projects are targeted at solving problems faced by many people like security and healthcare. Contributing to them means you are making a direct impact in solving issues that matter.</p>
</li>
<li><p><strong>Improving Software</strong> - The contributions you make may help improve the quality, functionality, and usability of software you use or that's used by millions of people. Each contribution you make, whether it's fixing a bug, typo, or adding code potentially benefits countless users.</p>
</li>
<li><p><strong>Recognition and Respect</strong> - As you work your way into the open-source world and become consistent, you will gain recognition and be celebrated for your work.</p>
</li>
<li><p>Additionally, it's a fun experience and gives you <strong>personal satisfaction</strong>. And hey, you never know who is watching, maybe it's your next employer or partner 🙂.</p>
</li>
</ul>
<h2 id="heading-how-to-get-started-with-open-source-contributions">How to Get Started with Open-Source Contributions</h2>
<p>Before taking a deep dive into the open-source world, it's important to first evaluate your skills and interests.</p>
<p>Reflect on the programming languages you know, your general technical abilities, and your areas of expertise. Identify your strengths and areas where you want to grow.</p>
<p>This self-assessment will help you find projects that align with your skills and passions.</p>
<h3 id="heading-1-setting-up-the-right-mindset">1. Setting Up the Right Mindset</h3>
<p>As you may know, contributing to open-source is not only about code – it's more of collaboration that will promote growth, learning and positive community engagement.</p>
<p>Before getting started, having the right mindset will empower you throughout the journey. For that you will need to:</p>
<ul>
<li><p><strong>Understand the value of open-source</strong> - the key principle behind the success of open-source projects is collaboration. Each contribution made, no matter how small, adds value. These collective contributions add benefits to the global community.</p>
</li>
<li><p><strong>Embrace the learning process</strong> - not knowing everything is okay, and that's why open-source encourages learning through collaboration. Remember to always do your research and then, if needed, seek help when you are stuck. This is a sign of progress and not weakness.</p>
</li>
<li><p><strong>There is more than code</strong> - as much as code is the core of most open-source projects, it's not the only way to get involved. Before making contributions consider your strengths and interests and then explore non-coding avenues, too.</p>
</li>
</ul>
<h3 id="heading-2-choosing-a-programming-languagetechnology">2. Choosing a Programming Language/Technology</h3>
<p>In order for you to make effective contributions, you'll need to decide which programming languages/technologies you feel most comfortable with. And for that you will need to do the following:</p>
<ul>
<li><p><strong>Assess your skillset</strong> - assessing your skillset will help you decide whether to leverage the skills you already have or venture into learning new ones.</p>
</li>
<li><p><strong>Research technologies</strong> - consider technologies used in different projects that you are interested in and whether they align with your interests.</p>
</li>
<li><p><strong>Personal interests</strong> - passion fuels contributions, and contributing to projects that resonate with you can be fulfilling and fun.</p>
</li>
</ul>
<h3 id="heading-3-finding-projects">3. Finding Projects</h3>
<p>Identifying the right open-source projects can really enhance your contribution experience. There are a few different ways you can search for projects. Here are a few highlights on that:</p>
<ul>
<li><p><strong>Use Open-Source Directories</strong> - explore different platforms that list different open-source projects. Websites like <a target="_blank" href="https://github.com/explore">GitHub Explore</a>, <a target="_blank" href="https://gitlab.com/explore">GitLab Explore</a>, <a target="_blank" href="https://opensourcefriday.com/">Open Source Friday</a> and others all list projects, making it easier to search through.</p>
</li>
<li><p><strong>Source code platforms</strong> - platforms such as GitHub and GitLab are central to the open-source world. Search on these platforms using keywords, and filter across different projects to easily find ones that match your interests.</p>
</li>
<li><p><strong>Project activity</strong> - while searching, look for recent commits, open issues, and ongoing discussions. An active community is a positive sign for the success of the project.</p>
</li>
<li><p><strong>Community engagement</strong> - before you begin making contributions, engage with the project's community. This can be through joining forums, a mailing list, or chat channels. Ask questions and interact with others, as this will help you understand the project's dynamics.</p>
</li>
</ul>
<h3 id="heading-4-choosing-the-right-project">4. Choosing the right project</h3>
<p>Ensuring that you pick the right project to work on is important, as it will be the first step to achieving all your goals.</p>
<p>In order to more easily navigate the open-source landscape and find the right project to work on, here are a few thing to consider:</p>
<ul>
<li><p><strong>Interest alignment</strong> - Make sure you look for projects that align with your technical interests and areas of expertise.</p>
</li>
<li><p><strong>Project activity</strong> - Be sure to check how active the project is. A project with a vibrant community with recent issues and commits indicates it's actively maintained.</p>
</li>
<li><p><strong>Friendliness</strong> - If you are beginner getting into open source for the first time, opt for projects with a reputation of welcoming newcomers.</p>
</li>
<li><p><strong>Project goals</strong> - Have an understanding of the project goals and be sure they align with your values.</p>
</li>
</ul>
<p>After you have found the project you want to contribute to, it's time to do a little vetting. Make sure it meets the following criteria so you know it'll be a good project to work on:</p>
<ul>
<li><p>Check out if it has a license file.</p>
</li>
<li><p>Look for the number of contributors.</p>
</li>
<li><p>Check how often people make commits.</p>
</li>
<li><p>Does it have any open issues? If yes, this might be a good sign – you will have a place to begin.</p>
</li>
<li><p>How long does it take for maintainers to respond? You can check and see how often issues are closed and PRs are merged.</p>
</li>
<li><p>Is there an active discussion on an issue?</p>
</li>
<li><p>Are the issues getting closed regularly?</p>
</li>
<li><p>How many open pull requests are there?</p>
</li>
<li><p>How recently was the latest pull requests merged?</p>
</li>
<li><p>Do the maintainers thank people for contributing?</p>
</li>
</ul>
<p>If this vetting process checks out, then you are probably good to go and start your contributions.</p>
<h2 id="heading-how-to-navigate-open-source-communities">How to Navigate Open-Source Communities</h2>
<p>Open-source projects are more than just code repositories. They are communities where developers from around the world collaborate to create something impactful.</p>
<p>In order to contribute effectively, it's essential to understand the dynamics of these communities and engage with them in a meaningful way.</p>
<p>When it comes to building strong, sustainable open-source contributor communities, it's not just about providing robust newcomer support. For many people, getting involved with open-source projects can be intimidating, overwhelming, and frustrating - especially if they lack exposure to and experience with the different tools and workflows commonly used in the open-source world.</p>
<p>But with the right support structures in place, new members can quickly become valuable contributors to any project - bringing fresh perspectives, enthusiasm, and a willingness to learn.</p>
<p>The benefits offered by these communities are 'on another level' as I would say. They have helped people start from scratch and gain new skills, create connections, and even land their dream jobs.</p>
<p>Other benefits include:</p>
<ul>
<li><p>They promote exchange of ideas, solutions, and best practices.</p>
</li>
<li><p>Overcoming challenges is often easier as a community, and can make problem solving more efficient.</p>
</li>
<li><p>Peer review from different contributors ensures code quality, and can help you catch bugs and improve the project in general.</p>
</li>
<li><p>Contributing to open source projects often provides you with networking opportunities.</p>
</li>
</ul>
<h3 id="heading-understanding-community-dynamics">Understanding community dynamics</h3>
<p>Each open source community has its own culture and values. Understanding these dynamics is key to integrating successfully into the project's workflow.</p>
<ul>
<li><p><strong>Project Vision and Goals</strong> - In order for you to make an effective and meaningful contribution, make sure you understand the project's vision and objectives.</p>
</li>
<li><p><strong>Community Norms and Values</strong> - Every community has both written and unwritten rules and values that contributors should respect. These can include coding standards, communication etiquette, and diversity and inclusion principles.</p>
</li>
<li><p><strong>Recognizing Hierarchy and Roles</strong> - Open source projects often have a hierarchy of roles, from maintainers to newcomers. Understand these roles and how decisions are made within the community.</p>
</li>
</ul>
<h3 id="heading-how-to-find-and-join-open-source-communities">How to Find and Join Open-Source Communities</h3>
<p>Finding the right community is an important step to ensure you have a meaningful open-source experience. So here are a few tips you can use to discover and join open-source communities.</p>
<ul>
<li><strong>Research</strong> - use the readily available platforms to search for projects that align with your skillset. As a beginner at first it might not be a walk in the park for you but with enough guidance you will find it easy.</li>
</ul>
<p>For starters, platforms such as GitHub, Gitlab and Bitbucket can be good platforms to search for projects. One similarity that cuts across all this platforms is that you can use the search functionality to find projects by keywords, technologies used or specific topics.</p>
<p>For example, using GitHub if you are interested in finding Python development projects they you can have your search as shown below and additionally from the left panel further filter the search to suit your desires.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/find-project.png" alt="find-project" width="600" height="400" loading="lazy"></p>
<ul>
<li><strong>Forums and mailing lists</strong> - many projects use different ways to communicate. By finding the right one you can easily introduce yourself and ask questions. The communications options you choose will also depend with the kind of info you want to get.</li>
</ul>
<p>If you are interested in just receiving updates and news about a specific project you are interested in, then consider joining the mailing lists which in most cases is weekly, monthly or quarterly. To sign up for a mailing list/newsletter, you can visit either the official site of the project or a related repository.</p>
<p>If you are more into engaging with other contributors, then joining the forum/discussion boards is the right thing to do. These boards enable the maintainers and contributors to have discussions and share knowledge among themselves. Below is section of freeCodeCamp's forum and some of the conversation that take place.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/forum.png" alt="forum" width="600" height="400" loading="lazy"></p>
<p><strong>Note</strong> the freeCodeCamp forum is subdivided into different sub-forums. This is a very common practice for big projects as it makes it easier for different contributors with questions to know where to ask for help</p>
<ul>
<li><p><strong>Social Media</strong> - follow open-source project accounts on platforms such as X (Twitter), LinkedIn, and GitHub to easily get updates. This works best for those who are actively participating on the social media platforms. For quick updates and news regarding a specific project, then this is the right place to get it – plus it also allows you to enage with other people interested with the same project as you.</p>
</li>
<li><p><strong>Meetups and conferences</strong> - start attending local meetups, conferences, and workshops that are related to open-source projects. This may act as a good opportunity to start making connections.</p>
</li>
<li><p><strong>Online communities</strong> - use platforms such as Stack Overflow, Reddit, and Discord to connect with fellow contributors.</p>
</li>
</ul>
<h3 id="heading-etiquette-communication-norms-and-best-practices">Etiquette, Communication Norms, and Best Practices</h3>
<p>Once you've found a community to join, it's important to follow etiquette and communication norms. Here's a guide to best practices:</p>
<ul>
<li><p><strong>Read the guidelines</strong> - Read and understand the community guidelines. They help ensure that everyone feels equal, safe, and respected.</p>
</li>
<li><p><strong>Introduce yourself</strong> - How we introduce ourselves will often be how others remember us. When you introduce yourself, remember to be respectful and concise.</p>
</li>
<li><p><strong>Listen and learn</strong> - Before you begin making any kind of contributions, take some time to first understand the culture of the community.</p>
</li>
<li><p><strong>Ask questions</strong> - whenever you encounter a challenge, feel free to ask a question and be sure to provide some context to indicate you did attempt to find an answer yourself.</p>
</li>
<li><p><strong>Accept feedback</strong> - whenever you receive feedback of any kind, thank the person and accept their opinion. Remember that continuous learning is key.</p>
</li>
<li><p><strong>Don't spam</strong> - Avoid spamming the communication channels with the same questions. Just use appropriate channels for different topics.</p>
</li>
<li><p><strong>Be patient</strong> - remember that the communities have contributors from different time zones, so give them adequate time to respond.</p>
</li>
</ul>
<h2 id="heading-how-to-set-up-a-development-environment">How to Set Up a Development Environment</h2>
<p>A well-configured environment is the foundation not only for open-source contribution but for development in general.</p>
<p>It may sound like a difficult thing to do, but when you are contributing to multiple projects and working on personal projects from your machine, having an environment will be really helpful.</p>
<p>Here are a few things to note when it comes to setting up your development environment:</p>
<h3 id="heading-install-the-necessary-tools">Install the Necessary Tools</h3>
<ul>
<li><p>Local setup - In most projects, they will list all the requirements needed for setup. Just be sure to install them as instructed on the project's documentation.</p>
</li>
<li><p>Consider using a virtual environment, as this will help in isolating project-specific dependencies.</p>
</li>
<li><p>Using Docker is a good option, too, as it ensures consistent environments across different machines you might be working with.</p>
</li>
</ul>
<h3 id="heading-text-editors-and-integrated-development-environments-ides">Text Editors and Integrated Development Environments (IDEs)</h3>
<p>Text Editors and IDEs are the tools that help your write, edit, and manage your code. Depending on your programming language of choice and personal preference, you can choose from different options such as Visual Studio Code, Sublime Text, or JetBrains IDEs like PyCharm or IntelliJ IDEA.</p>
<p>These tools offer features like:</p>
<ul>
<li><p>syntax highlighting,</p>
</li>
<li><p>auto-completion</p>
</li>
<li><p>debugging</p>
</li>
</ul>
<p>These features can help enhance your coding experience.</p>
<p>In addition to the regular installation, be sure to install any necessary extensions that will help make your workflow smoother.</p>
<h3 id="heading-version-control-systems">Version control systems</h3>
<p>Version control is the cornerstone of collaboration in software development. The most commonly known and used one is Git. It allows you as a developer to record changes made to code, create branches to easily add new features without interfering with main code, and allows easy merging of the changes.</p>
<p>But Git by itself can't accomplish all this, so it works together with GitHub.</p>
<p>GitHub is a web-based platform that allows you to host source code in what is referred to as a repository. Together with Git, GitHub offers multiple beneficial features to developers – but the most important one, apart from collaboration, is that it offers a visual interface for managing the repositories. This makes it easier to track issues, merge changes and so on.</p>
<p>You can learn more about the basics of Git and GitHub in this <a target="_blank" href="https://www.freecodecamp.org/news/git-and-github-the-basics/">guide</a>.</p>
<p>Moving forward, just like with any other software, to get started using Git you'll first need to download and set it up. But first make sure that you already have a GitHub account created. If not, you can visit <a target="_blank" href="https://github.com/">github.com</a> and create one, then proceed with the steps below afterwards.</p>
<ul>
<li><p>Step 1: Download Git from the <a target="_blank" href="https://git-scm.com/downloads">official site</a>.</p>
</li>
<li><p>Step 2: Run the executable file to install Git locally. If you are on another OS than Windows, be sure to check the specific commands you can use to install Git from the official site.</p>
</li>
<li><p>Step 3: Configure Git with your details, including your username and email. For that you will need to open the Git terminal and run the commands below:</p>
</li>
</ul>
<pre><code class="lang-python">git config --<span class="hljs-keyword">global</span> user.name <span class="hljs-string">"Your name here"</span>
git config --<span class="hljs-keyword">global</span> user.email <span class="hljs-string">"your_email@example.com"</span>
</code></pre>
<p>For some extra customization, you can run the commands below. The first one will add some color to the output, and the second one will tell Git to use emacs.</p>
<pre><code class="lang-python">git config --<span class="hljs-keyword">global</span> color.ui true
git config --<span class="hljs-keyword">global</span> core.editor emacs
</code></pre>
<p>Now you should be ready to use Git. If you want to learn more and dive in deeper, here's a helpful <a target="_blank" href="https://www.freecodecamp.org/news/how-to-use-git-best-practices-for-beginners/">beginner-friendly Git resource</a> for you.</p>
<p>We will be discussing the most common Git commands later on in the upcoming sections.</p>
<h3 id="heading-how-to-fork-clone-and-set-up-projects">How to fork, clone, and set up projects</h3>
<p>Now we'll cover some of the most important parts of using Git.</p>
<p>First, what is <strong>forking</strong>? Well, it allows you to make a personal copy of a project's repository to your GitHub account. This step is important mostly when you want to make contribution to a project that you don't have direct access to.</p>
<p>In order to fork a repo, on the GitHub repository page, click <code>Fork</code>, usually on the top right corner.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/fork-repo-1.png" alt="fork-repo-1" width="600" height="400" loading="lazy"></p>
<p>This will create a copy of the repository under your account, changing the URL of the project to:</p>
<p><code>https://github.com/&lt;your-user-name&gt;/projectname</code></p>
<p><strong>Cloning</strong> allows you to download a copy of the already forked repo to your own local machine. In order for you to perform this step, you must have Git installed locally in your machine. If you haven't done this yet, check out the <a class="post-section-overview" href="#heading-version-control-systems-1">Version control systems</a> section above.</p>
<p>First, you will need to navigate to your account and locate the forked repo. Then copy the URL directly from the browser or click the <code>Code</code> button to copy the URL. You'll have three option to choose from: HTTPS, SSH, and GitHub CLI. You can choose either of the first two options.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/clone-repo.png" alt="clone-repo" width="600" height="400" loading="lazy"></p>
<p>Next, in your local machine, open the terminal and run this command:</p>
<p><code>git clone https://github.com/&lt;your-user-name&gt;/&lt;projectname&gt;</code></p>
<p>Be sure to navigate to where you need the project to be copied to, for example Downloads, Desktop, and so on:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/git-clone.jpg" alt="git-clone" width="600" height="400" loading="lazy"></p>
<p>Alternatively, you can opt to use the GitHub Desktop application to perform all the above steps. But first you will need to have it <a target="_blank" href="https://desktop.github.com/">installed</a> and fully configured.</p>
<p>Next, instead of copying the URL and pasting it on your terminal, select the option that says <code>Open with GitHub Desktop</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/github-desktop.png" alt="github-desktop" width="600" height="400" loading="lazy"></p>
<p>Now you'll need to know how to <strong>set up the project locally</strong>. Navigate to the project directory using the terminal and be sure to install dependencies if there are any that are listed.</p>
<p>To check if everything is set up correctly, run the project locally and ensure that it works as expected.</p>
<h2 id="heading-understanding-project-structure-and-workflow">Understanding Project Structure and Workflow</h2>
<p>Open-source projects come in various shapes and sizes, but what's common among them all is the structure and workflow. By having a clear understanding of the development process, it will make your contributing process easier.</p>
<h3 id="heading-overview-of-a-typical-open-source-project-structure">Overview of a Typical Open-Source Project Structure</h3>
<p>A typical open-source project will have the following people associated with it:</p>
<ul>
<li><p><strong>Author</strong> - Also referred to as Owner. Represents the person who created the project. They have the power to assign new roles to other members to help with the project's maintenance.</p>
</li>
<li><p><strong>Maintainers</strong> - They are responsible for driving the vision and goals of the project. They're usually responsible for the direction of the project and are committed to improving it.</p>
</li>
<li><p><strong>Contributors</strong> - This represents people like you who add/make changes to the project in one way or another. They follow the same code review process, are subject to the same requirements on code style, and so on.</p>
</li>
<li><p><strong>Community Members/Users</strong> - These valuable members of the community can provide feedback about features, bug reports, and more.</p>
</li>
</ul>
<p>In addition the different roles and people, the structure will usually look like this:</p>
<ul>
<li><p>The <strong>Root Directory</strong> will consist of important project files, such as the README, license information, and configuration files.</p>
</li>
<li><p>The <strong>Source Code Directory</strong> houses the main source code of the project. It can be organized by either libraries, modules or components.</p>
</li>
<li><p>The <strong>Documentation Directory</strong> contains user manuals, guides for any APIs to help users and contributors understand the project.</p>
</li>
<li><p>The <strong>Configuration Files</strong> contain files with instructions on how to setup the project's build process, dependencies and other helpful configurations.</p>
</li>
<li><p>The <strong>Assets Directory</strong> contains no-code files like images and other templates used by the project.</p>
</li>
<li><p>The <strong>Scripts Directory</strong> contains automation tools that the project might need.</p>
</li>
</ul>
<p>Below is a section of the freeCodeCamp repository workflow with most of the files listed above:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/workflow-structure.png" alt="workflow-structure" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-make-your-first-contribution">How to Make Your First Contribution</h2>
<p>Before making your first contribution, make sure that you have chosen beginner friendly issues or task to work on. To help you find good beginner friendly issues/tasks, here are a few tips:</p>
<ul>
<li><p>Browse through project issues trackers on platforms such as GitHub. During the search, look for projects labeled "beginner-friendly," "good first issue," or "help wanted." This are usually designed for beginners. <a target="_blank" href="https://www.freecodecamp.org/news/how-to-find-good-first-issues-on-github/">Here's a guide</a> that shares more info on this topic.</p>
</li>
<li><p>Make sure you understand the issue's description before you begin working on the task. This will help you choose a task that aligns with your skills and interests.</p>
</li>
<li><p>If you are completely new with no prior knowledge, check for projects that offer mentorships to beginners.</p>
</li>
</ul>
<p>For a detailed guide on <a target="_blank" href="https://www.freecodecamp.org/news/github-search-tips/">how to search for issues and repos on GitHub, check out this guide</a>.</p>
<h3 id="heading-step-by-step-guide-to-making-a-contribution">Step-by-Step Guide to Making a Contribution</h3>
<p>Now that you know how to search for a beginner friendly project – and assuming you have already gotten one that aligns with your skills – the next step is making your contributions.</p>
<p>For a demo, I will be making a non-code contribution (and I'll discuss more about this later).</p>
<ul>
<li><p>Step 1: Fork the repository</p>
</li>
<li><p>Step 2: Clone the repo onto your local machine.</p>
</li>
<li><p>Step 3: Create a new branch</p>
</li>
</ul>
<p>To create a branch, run the below command and remember to give your branch a descriptive name:</p>
<p><code>git checkout -b descriptive name</code></p>
<p>This will create the branch and switch to it automatically.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/branch-name.jpg" alt="branch-name" width="600" height="400" loading="lazy"></p>
<ul>
<li><p>Step 4: Make the necessary changes – this can be fixing typos, fixing a bug, and so on – it all depends with the issue you have chosen.</p>
</li>
<li><p>Step 5: After making your changes, it's time to add the new changes into the main branch. You can see all changes made by running: <code>git status</code></p>
</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/git-status.jpg" alt="git-status" width="600" height="400" loading="lazy"></p>
<p>You can choose to add each file modified individually using <code>git add file-name</code> or you can add the modified files all at once using: <code>git add *</code></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/git-add.jpg" alt="git-add" width="600" height="400" loading="lazy"></p>
<p>You will notice that the changes are no longer highlighted in red but instead in green. This means that they are ready to be committed.</p>
<p>To make a commit, we move on to the next step which is adding a commit message. This basically explains the changes we have made: <code>git commit -m "&lt;message here&gt;"</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/commit-message.jpg" alt="commit-message" width="600" height="400" loading="lazy"></p>
<ul>
<li>Step 6: We need to regularly sync the forked repo with the original repo. This incorporates all the changes made by other contributors. To do this, run the commands below one after the other:</li>
</ul>
<pre><code class="lang-python">git fetch upstream
git rebase upstream/main
</code></pre>
<ul>
<li>Step 7: Push the changes to GitHub Now that everything is set, it's time to let our maintainer know what we have added. You do this by pushing the changes with this command: <code>git push origin descriptive-branch-name</code>.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/git-push.jpg" alt="git-push" width="600" height="400" loading="lazy"></p>
<ul>
<li>Step 8: This is the last step, where we submit a PR. For this step you will need to go back to GitHub under the repo you had forked earlier. You should be able to see a pop-up with a button saying <code>Compare &amp; pull request</code> – click on it.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/pull-request.png" alt="pull-request" width="600" height="400" loading="lazy"></p>
<p>Clicking this will allow you to give your PR a name, add a description of what you have done, mark the checklist (if there is one) to ensure that you have fulfilled all the requirements, and then finally clicking on the <code>Create pull request</code> button which is slightly below the description box.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/create-pr.png" alt="create-pr" width="600" height="400" loading="lazy"></p>
<p>Then the maintainer will merge all your changes into the master branch of this project (unless they need you to make updates first). You will get a notification email once the changes have been merged.</p>
<h2 id="heading-collaboration-within-the-community">Collaboration Within the Community</h2>
<p>Being part of a new community or environment in any kind of setting isn’t easy – and more so for people who refer to themselves as introverts.</p>
<p>When it comes to open-source communities, newcomers often face various challenges that can deter them from feeling comfortable and affect their contributions.</p>
<p>The first step in fixing a problem is to identify it. This will bring you closer to finding a solution. Some of the most common challenges faced by newcomers in OS communities include:</p>
<ul>
<li><p>Feeling overwhelmed/intimidated by the expertise of other community members.</p>
</li>
<li><p>Struggling to understand the project structure and codebase.</p>
</li>
<li><p>Lack of clear understanding of the contribution guidelines.</p>
</li>
<li><p>Encountering an unwelcoming community.</p>
</li>
<li><p>Lack of recognition and appreciation of contributions.</p>
</li>
<li><p>Struggling to find tasks that matches your skills/expertise</p>
</li>
</ul>
<p>By addressing the above challenges, we will be one step closer to creating supportive communities which are comfortable for all. As we know collaboration is key for the success of any open-source project and community engagement can play a major role on your career while at the same time shaping you to become a better contributor.</p>
<p>There are different ways to address these common challenges while at the same time engaging with the community to ensure the project's success:</p>
<ol>
<li><p>Participating in discussions and forums</p>
</li>
<li><p>Giving and receiving feedback on contributions</p>
</li>
<li><p>Learning from the experienced contributors</p>
</li>
<li><p>Mentoring other contributors and taking part in pair programming.</p>
</li>
<li><p>Attending and being part of community events.</p>
</li>
</ol>
<p>In addition to this remember to be patient, stay humble, listen actively, celebrate others, and take part in discussions about the future of the project.</p>
<h2 id="heading-beyond-code-non-coding-contributions">Beyond Code: Non-Coding Contributions</h2>
<p>The good thing about opens-source projects is that they can often accommodate people with all kinds of skillsets. Contributing extends beyond just writing code. Non-coding skills are also important to the success of the open-source projects.</p>
<p>If you are looking for different ways to get involved in open-source and don't have coding skills, this section is for you.</p>
<h3 id="heading-update-the-documentation">Update the Documentation</h3>
<p>Good documentation is the backbone of any successful project, not only in open-source but even in the real-world products. Clear and detailed documentation will help users and developers understand the project easily.</p>
<p>Some ways you can contribute to the documentation include:</p>
<ul>
<li><p><strong>Writing tutorials</strong> - You can opt to write step-by-step tutorials that will guide users through steps such as installation, setup, usage and troubleshooting.</p>
</li>
<li><p><strong>API Documentation</strong> - Document the project's APIs, and provide code examples for the developers who might want to integrate the project.</p>
</li>
<li><p><strong>User guides</strong> - Write user-friendly guides that break down the complex concepts in simple and easy to understand sections.</p>
</li>
</ul>
<h3 id="heading-contribute-to-the-design-and-user-experience-ux">Contribute to the Design and User Experience (UX)</h3>
<p>Any project that is made for an end user will greatly benefit from a well-designed user interface. If you have some skills in the design field, you can contribute by:</p>
<ul>
<li><p><strong>Improving UI/UX</strong> - improve the project's look by suggesting more user-friendly designs and creating mockups for the same.</p>
</li>
<li><p><strong>Creating Icons and Graphics</strong> - design logos, icons, banners and other visual assets that will help promote the project's branding.</p>
</li>
<li><p><strong>User Testing</strong> - take part in testing the designs and provide feedback.</p>
</li>
</ul>
<h3 id="heading-help-with-translation-and-localization">Help with Translation and Localization</h3>
<p>Many projects are trying to reach a global audience, and as a native speaker of your language you can help with this.</p>
<p>Contribution by translation and localization ensures that the projects can easily be accessible by people from different backgrounds all around the world. As a contributor you can help by:</p>
<ul>
<li><p><strong>Translating Content</strong> - you can translate the documentation, user interface, and any other relevant content.</p>
</li>
<li><p><strong>Cultural Adaptation</strong> - whenever you translate a project, be sure that the content is relevant to the culture and aligns with local contexts.</p>
</li>
</ul>
<h3 id="heading-participate-in-quality-assurance-and-testing">Participate in Quality Assurance and Testing</h3>
<p>It may not seem like much, but testing is crucial for maintaining any good open-source project. The good thing about testing is that even though you are not a developer you can contribute by:</p>
<ul>
<li><p><strong>User Testing</strong> - this involves testing the projects under different use cases and giving feedback on any encountered bugs, glitches, and issues. This feedback will help make the project better for the next development face.</p>
</li>
<li><p><strong>Beta Testing</strong> - this involves being part of testing products before they are officially released. Help identify any issues that the end user might encounter.</p>
</li>
</ul>
<h3 id="heading-engage-with-the-community">Engage with the Community</h3>
<p>Having a strong community creates a safe space where contributors can focus on major things like improving the software's quality and ensuring the long-term sustainability of the project. You can contribute by:</p>
<ul>
<li><p><strong>Moderation</strong> - you can offer to moderate discussion forums, chat rooms, and community platforms to ensure a positive and inclusive environment.</p>
</li>
<li><p><strong>Answering Questions</strong> - you can assist other community members by answering any questions that they may have.</p>
</li>
</ul>
<h3 id="heading-do-marketing-and-outreach">Do Marketing and Outreach</h3>
<p>The more an open source project is visible to the community, the better - and this includes visibility on social platforms. If you have marketing or communication skills you can contribute by:</p>
<ul>
<li><p>Promoting the projects on social media platforms.</p>
</li>
<li><p>Writing tutorials and articles that highlight features offered by different projects, along with their importances and use cases.</p>
</li>
</ul>
<h3 id="heading-help-with-fundraising-and-donations">Help with Fundraising and Donations</h3>
<p>Lack of adequate funds to support the project's growth and sustainability may lead to its collapse before you even know it. A good way to address such a problem is by:</p>
<ul>
<li><p><strong>Fundraising initiatives</strong> - organizing fundraising campaigns to support the project financially.</p>
</li>
<li><p><strong>Sponsorship outreach</strong> - applying for grants, seeking sponsorship, and joining incubator programs.</p>
</li>
</ul>
<h2 id="heading-best-practices-for-quality-contributions">Best Practices for Quality Contributions</h2>
<p>Contributing to open-source is not just about writing code, it's about creating high-quality and valuable contributions that will make the project easily accessible to others.</p>
<p>Here are some best practices that will help you contribute code that is clean, easy to maintain, and follows the industry standards.</p>
<h3 id="heading-write-clean-and-maintainable-code">Write Clean and Maintainable Code</h3>
<p><a target="_blank" href="https://www.freecodecamp.org/news/how-to-write-clean-code/">Clean code</a> can be described as code that is easy to read, understand, and maintain.</p>
<p>By writing clean code you will not only make it easier for others to read through but also for your future self.</p>
<p>When trying to write clean code, here are some key best practices:</p>
<ul>
<li><p>Use meaningful variable, function, and class names.</p>
</li>
<li><p>Break down the code into smaller managable sections.</p>
</li>
<li><p>Make use of comments to provide additional context.</p>
</li>
<li><p>Maintain consistency in your coding style.</p>
</li>
<li><p>Don't Repeat Yourself (DRY)</p>
</li>
</ul>
<h3 id="heading-test-and-document-your-code">Test and Document Your Code</h3>
<ul>
<li><p>Always write unit tests, integration tests, and end-to-end tests to ensure that the code works correctly.</p>
</li>
<li><p>Remember to always document your development progress. This includes the code's purpose, usage instruction, and so on.</p>
</li>
</ul>
<h2 id="heading-how-to-handle-challenges">How to Handle Challenges</h2>
<p>Being a new person in any field, you are bound to encounter different challenges that may make you question your desire to contribute.</p>
<p>But you can also see the challenges as stepping stones rather than roadblocks, preparing you to be a better contributor.</p>
<h3 id="heading-how-to-handle-rejection-and-criticism">How to handle rejection and criticism</h3>
<p>Rejection and criticism can be tough to handle, especially for beginners. Not everyone in a community can be as welcoming as we'd like, but just remember – this experience is still an opportunity of focus and improvement.</p>
<p>In case you encounter rejection and criticism, here are a few things to help you overcome them:</p>
<ul>
<li><p><strong>Maintain a growth mindset</strong> - approach the rejection with an open mind and view it as a chance for you to learn and improve on your skills.</p>
</li>
<li><p><strong>Ask for feedback</strong> - in a case you have made a contribution and it has been rejected, always ask for feedback. This will help guide your future contributions while at the same time improving your skills</p>
</li>
<li><p><strong>Learn from others</strong> - before making your contributions, take time to learn from what other experienced contributors are doing. This can help you know how to structure your code, write documentation, and how to address issues. In return you will be on the safe side while making your contributions.</p>
</li>
<li><p><strong>Be persistent</strong> - use rejection as a motivation to refine your work and resubmit again.</p>
</li>
</ul>
<h3 id="heading-how-to-ask-for-help">How to ask for help</h3>
<p>Many beginners, not only in the open-source world but in other fields as well, may be hesitant to ask for help. This is often because they don't want to appear to be inexperienced.</p>
<p>If you find yourself feeling this way, you may be forgetting that you're new to the field, and asking for assistance is part of the learning process. Even if you're a more seasoned contributor, you may still feel insecure at times (imposter syndrome, anyone?) - and this is ok. Everyone has their doubts at times. Just keep pushing forward.</p>
<p>As a beginner in open-source, to ensure that you receive the help you need, here are some tips:</p>
<ul>
<li><p><strong>Do your research</strong> - attempt to solve the issue by yourself first before seeking help. This demonstrates your commitment to learning and problem solving skills.</p>
</li>
<li><p><strong>Be specific</strong> - provide detailed info about the problem you are facing. This can include mentioning the steps you have taken so far, the result you have gotten, highlighting the errors you faced, and so on. The more detailed the question, the easier it is for others to help you.</p>
</li>
</ul>
<h3 id="heading-strategies-for-overcoming-common-challenges">Strategies for Overcoming Common Challenges</h3>
<ol>
<li><p>Time management - balancing between open-source and personal work can be challenging sometimes. Be sure to set realistic goals and avoid overcommitting.</p>
</li>
<li><p>Impostor syndrome - this is where you feel inadequate despite there being solid evidence of your skills. Remember that we all begin somewhere – just try to appreciate your learning journey and focus on your progress.</p>
</li>
<li><p>Large code bases can be overwhelming to beginners. As a good practice, start small and work your way up as you gain more confidence and familiarize yourself with the codebase.</p>
</li>
<li><p>Burnout prevention - prioritize self-care, take breaks when necessary, and always remember that making small steps is more valuable than overwhelming yourself with a task.</p>
</li>
</ol>
<h2 id="heading-how-to-showcase-your-open-source-contributions">How to Showcase Your Open-Source Contributions</h2>
<p>Just like in any other field of work, you need to market yourself. And one of the best ways to do that is by showcasing your projects and contributions online. It's time to shine a spotlight on your work.</p>
<p>In return, this may attract potential employers, collaborators, and give you recognition in the broader tech ecosystem.</p>
<h3 id="heading-build-an-online-portfolioprofile">Build an online portfolio/profile</h3>
<p>The most common way to showcase any form of work online is through personal portfolio and here is how you can achieve this to showcase your open-source contributions:</p>
<p>Begin by selecting a platform that best works for you. This might include GitHub pages, your personal website, and platforms like Behance or Dribbble for designer-related projects.</p>
<p>Now that you have a platform, organize you your work in categories including a brief description, role played, and any challangages you might have encountered.</p>
<p>Remember to add code samples for different projects you have wokred on and a brief explanation of what the project/code does.</p>
<p>Finally, add a short bio that highlights your passion for open source and technology. Make it engaging and relatable.</p>
<h3 id="heading-highlight-your-contributions-on-your-resumesocial-media-platforms">Highlight your contributions on your résumé/social media platforms</h3>
<p>This is mostly helpful when potential employers are reviewing your résumé or GitHub/LinkedIn profile. Your contributions may set you apart from other applicants.</p>
<p>Here is how you can utilize this to stand out:</p>
<ul>
<li><p>Have a dedicated section where you can list all your open-source contributions and a brief description of your involvement.</p>
</li>
<li><p>Quantify the impact that you contribution played to the success of the project.</p>
</li>
<li><p>Highlight the skills you gained through contributing to open-source.</p>
</li>
<li><p>If you have an online profile, be sure to include a link of it on your resume, this will help recruiters explore your contribution in depth.</p>
</li>
</ul>
<h3 id="heading-networking">Networking</h3>
<p>Networking can open doors and connect you with multiple opportunities.</p>
<p>Here is how you can leverage your open-source experience for networking purposes:</p>
<ul>
<li><p>Talk about your contributions to open-source projects. This can be through sharing insights, asking questions, and so on.</p>
</li>
<li><p>Attend meetups and conferences related to technologies you have worked with or have experince in.</p>
</li>
<li><p>Connect with fellow contributors on platforms such as GitHub.</p>
</li>
<li><p>Take part in hackathons, workshops, mentorships and collaborative coding events with people os same interest.</p>
</li>
<li><p>Share your thought by writing tutorials about your open-source experiences, challenges you've overcome, and lessons you've learned.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>As you come to the end of this guide, take a moment to reflect on the journey. You have gained valuable insights while at the same time discovering how impactful you contributions can be no matter how small they are.</p>
<p>If you have contributed to open-source before, think back to when you first began your open-source journey. Remember the joy you felt when your first PR was merged, the satisfaction you had when you solved that bug, wrote that line of code, resolved that issue, or updated that documentation.</p>
<p>All this has left a mark on the projects you have worked on. Be proud of yourself 😊.</p>
<p>Remember that the open-source community thrives on diversity, and every contribution, no matter how small, adds value. By participating in open source, you're contributing to a global movement that values transparency, cooperation, and the free exchange of knowledge.</p>
<p>Here's to your continued success in open-source contributions, learning, and making a difference.</p>
<p>Happy coding! 🚀🌍</p>
<h2 id="heading-additional-resources">Additional Resources</h2>
<ul>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/open-source-projects-every-dev-should-know/">Open Source Projects Every Developer Should Know About</a></p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/automate-open-source-projects-with-github-actions/">How to Use GitHub Actions to Automate Open-Source Projects</a></p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/github-search-tips/">GitHub Search Tips – How to Search Issues, Repos, and More Effectively on GitHub</a></p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/how-to-write-a-good-readme-file/">How to Write a Good README File for Your GitHub Project</a></p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/developer-communities-to-join-to-grow-your-career/">Developer Communities to Join to Help You Grow Your Tech Career</a></p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/how-to-contribute-to-open-source-projects-beginners-guide/">How to Contribute to Open Source Projects – A Beginner's Guide</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The C Programming Handbook for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ C is one of the oldest, most widely known, and most influential programming languages. It is used in many industries because it is a highly flexible and powerful language. Learning C is a worthwhile endeavor – no matter your starting point or aspirat... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-c-programming-handbook-for-beginners/</link>
                <guid isPermaLink="false">66b1e4bf0938e6258a76bbdd</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ c programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Dionysia Lemonaki ]]>
                </dc:creator>
                <pubDate>Tue, 29 Aug 2023 20:38:16 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1726039032547/73b9df27-a4f7-4ee2-81c0-d1e3db521cdb.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>C is one of the oldest, most widely known, and most influential programming languages.</p>
<p>It is used in many industries because it is a highly flexible and powerful language.</p>
<p>Learning C is a worthwhile endeavor – no matter your starting point or aspirations – because it builds a solid foundation in the skills you will need for the rest of your programming career.</p>
<p>It helps you understand how a computer works underneath the hood, such as how it stores and retrieves information and what the internal architecture looks like.</p>
<p>With that said, C can be a difficult language to learn, especially for beginners, as it can be cryptic.</p>
<p>This handbook aims to teach you C programming fundamentals and is written with the beginner programmer in mind.</p>
<p>There are no prerequisites, and no previous knowledge of any programming concepts is assumed.</p>
<p>If you have never programmed before and are a complete beginner, you have come to the right place.</p>
<p>Here is what you are going to learn in this handbook:</p>
<ul>
<li><p><a class="post-section-overview" href="#chapter-1">Chapter 1: Introduction to C Programming</a></p>
</li>
<li><p><a class="post-section-overview" href="#chapter-2">Chapter 2: Variables and Data Types in C</a></p>
</li>
<li><p><a class="post-section-overview" href="#chapter-3">Chapter 3: Operators in C</a></p>
</li>
<li><p><a class="post-section-overview" href="#chapter-4">Chapter 4: Conditional Statements in C</a></p>
</li>
<li><p><a class="post-section-overview" href="#chapter-5">Chapter 5: Loops in C</a></p>
</li>
<li><p><a class="post-section-overview" href="#chapter-6">Chapter 6: Arrays in C</a></p>
</li>
<li><p><a class="post-section-overview" href="#chapter-7">Chapter 7: Strings in C</a></p>
</li>
<li><p><a class="post-section-overview" href="#further-learning">Further learning: Advanced C Topics</a></p>
</li>
</ul>
<p>Without further ado, let’s get started with learning C!</p>
<h2 id="heading-chapter-1-introduction-to-c-programming">Chapter 1: Introduction to C Programming</h2>
<p>In this introductory chapter, you will learn the main characteristics and use cases of the C programming language.</p>
<p>You will also learn the basics of C syntax and familiarize yourself with the general structure of all C programs.</p>
<p>By the end of the chapter, you will have set up a development environment for C programming so you can follow along with the coding examples in this book on your local machine.</p>
<p>You will have successfully written, compiled, and executed your first simple C program that prints the text "Hello, world!" to the screen.</p>
<p>You will have also learned some core C language features, such as comments for documenting and explaining your code and escape sequences for representing nonprintable characters in text.</p>
<h3 id="heading-what-is-programming">What Is Programming?</h3>
<p>Computers are not that smart.</p>
<p>Even though they can process data tirelessly and can perform operations at a very high speed, they cannot think for themselves. They need someone to tell them what to do next.</p>
<p>Humans tell computers what to do and exactly how to do it by giving them detailed and step-by-step instructions to follow.</p>
<p>A collection of detailed instructions is known as a program.</p>
<p>Programming is the process of writing the collection of instructions that a computer can understand and execute to perform a specific task and solve a particular problem.</p>
<p>A programming language is used to write the instructions.</p>
<p>And the humans who write the instructions and supply them to the computer are known as programmers.</p>
<h4 id="heading-low-level-vs-high-level-vs-middle-level-programming-languages-whats-the-difference">Low-level VS High-Level VS Middle-level Programming Languages – What's The Difference?</h4>
<p>There are three types of programming languages: low-level languages, high-level languages, and middle-level languages.</p>
<p>Low-level languages include machine language (also known as binary) and assembly language.</p>
<p>Both languages provide little to no abstraction from the computer's hardware. The language instructions are closely related to or correspond directly to specific machine instructions.</p>
<p>This 'closeness to the machine' allows for speed, efficiency, less consumption of memory, and fine-grained control over the computer's hardware.</p>
<p>Machine language is the lowest level of programming languages.</p>
<p>The instructions consist of series of <code>0</code>s and <code>1</code>s that correspond directly to a particular computer’s instructions and locations memory.</p>
<p>Instructions are also directly executed by the computer’s processor.</p>
<p>Even though machine language was the language of choice for writing programs in the early days of computing, it is not a human-readable language and is time-consuming to write.</p>
<p>Assembly language allows the programmer to work closely with the machine on a slightly higher level.</p>
<p>It uses mnemonics and symbols that correspond directly to a particular machine’s instruction set instead of using sequences of <code>0</code>s and <code>1</code>s.</p>
<p>Next, high-level languages, like Python and JavaScript, are far removed from the instruction set of a particular machine architecture.</p>
<p>Their syntax resembles the English language, making them easier to work with and understand.</p>
<p>Programs written in high-level languages are also portable and machine-independent. That is, a program can run on any system that supports that language.</p>
<p>With that said, they tend to be slower, consume more memory, and make it harder to work with low-level hardware and systems because of how abstract they are.</p>
<p>Lastly, middle-level languages, like C and C++, act as a bridge between low-level and high-level programming languages.</p>
<p>They allow for closeness and a level of control over computer hardware. At the same time, they also offer a level of abstraction with instructions that are more human-readable and understandable for programmers to write.</p>
<h3 id="heading-what-is-the-c-programming-language">What Is the C Programming Language?</h3>
<p>C is a general-purpose and procedural programming language.</p>
<p>A procedural language is a type of programming language that follows a step-by-step approach to solving a problem.</p>
<p>It uses a series of instructions, otherwise known as procedures or functions, that are executed in a specific order to perform tasks and accomplish goals. These intructions tell the computer step by step what to do and in what order.</p>
<p>So, C programs are divided into smaller, more specific functions that accomplish a certain task and get executed sequentially, one after another, following a top-down approach.</p>
<p>This promotes code readability and maintainability.</p>
<h4 id="heading-a-brief-history-of-the-c-programming-language">A Brief History of the C Programming Language</h4>
<p>C was developed in the early 1970s by Dennis Ritchie at AT&amp;T Bell Laboratories.</p>
<p>The development of C was closely tied to the development of the Unix operating system at Bell Labs.</p>
<p>Historically, operating systems were typically written in Assembly language and without portability in mind.</p>
<p>During the development of Unix, there was a need for a more efficient and portable programming language for writing operating systems.</p>
<p>Dennis Ritchie went on to create a language called B, which was an evolution from an earlier language called BCPL (Basic Combined Programming Language).</p>
<p>It aimed to bridge the gap between the low-level capabilities of Assembly and the high-level languages used at the time, such as Fortran.</p>
<p>B was not powerful enough to support Unix development, so Dennis Ritchie developed a new language that took inspiration from B and BCPL and had some additional features. He named this language C.</p>
<p>C’s simple design, speed, efficiency, performance, and close relationship with a computer’s hardware made it an attractive choice for systems programming. This led to the Unix operating system being rewritten in C.</p>
<h4 id="heading-c-language-characteristics-and-use-cases">C Language Characteristics and Use Cases</h4>
<p>Despite C being a relatively old language (compared to other, more modern, programming languages in use today), it has stood the test of time and still remains popular.</p>
<p>According to the <a target="_blank" href="https://www.tiobe.com/tiobe-index/">TIOBE index</a>, which measures the popularity of programming languages each month, C is the second most popular programming language as of August 2023.</p>
<p>This is because C is considered the "mother of programming languages" and is one of the most foundational languages of computer science.</p>
<p>Most modern and popular languages used today either use C under the hood or are inspired by it.</p>
<p>For example, Python’s default implementation and interpreter, CPython, is written in C. And languages such as C++ and C# are extensions of C and provide additional functionality.</p>
<p>Even though C was originally designed with systems programming in mind, it is widely used in many other areas of computing.</p>
<p>C programs are portable and easy to implement, meaning they can be executed across different platforms with minimal changes.</p>
<p>C also allows for efficient and direct memory manipulation and management, making it an ideal language for performance-critical applications.</p>
<p>And C provides higher-level abstractions along with low-level capabilities, which allows programmers to have fine-grained control over hardware resources when they need to.</p>
<p>These characteristics make C an ideal language for creating operating systems, embedded systems, system utilities, Internet of things (IoT) devices, database systems, and various other applications.</p>
<p>C is used pretty much everywhere today.</p>
<h3 id="heading-how-to-set-up-a-development-environment-for-c-programming-on-your-local-machine">How to Set Up a Development Environment for C Programming on Your Local Machine</h3>
<p>To start writing C programs on your local machine, you will need the following:</p>
<ul>
<li><p>A C Compiler</p>
</li>
<li><p>An Integrated Development Environment (IDE)</p>
</li>
</ul>
<p>C is a compiled programming language, like Go, Java, Swift, and Rust.</p>
<p>Compiled languages are different from interpeted languages, such as PHP, Ruby, Python, and JavaScript.</p>
<p>The difference between compiled and interpeted languages is that a compiled language is directly translated to machine code all at once.</p>
<p>This process is done by a special program called a compiler.</p>
<p>The compiler reads the entire source code, checks it for errors, and then translates the entire program into machine code. This is a language the computer can understand and it's directly associated with the particular instructions of the computer.</p>
<p>This process creates a standalone binary executable file containing sequences of <code>0</code>s and <code>1</code>s which is a more computer-friendly form of the initial source code. This file contains instructions that the computer can understand and run directly.</p>
<p>An interpeted language, on the other hand, doesn’t get translated into machine code all at once and doesn’t produce a binary executable file.</p>
<p>Instead, an interpreter reads and executes the source code one instruction at a time, line by line. The interpreter reads each line, translates it into machine code, and then immediately runs it.</p>
<p>If you are using a Unix or a Unix-like system such as macOS or Linux, you probably have the popular <a target="_blank" href="https://gcc.gnu.org/">GNU Compiler Collection (GCC)</a> already installed on your machine.</p>
<p>If you are running either of those operating systems, open the terminal application and type the following command:</p>
<pre><code class="lang-plaintext">gcc --version
</code></pre>
<p>If you're using macOS and have not installed the command line developer tools, a dialog box will pop-up asking you to install them – so if you see that, go ahead and do so.</p>
<p>If you have already installed the command line tools, you will see an output with the version of the compiler, which will look similar to the following:</p>
<pre><code class="lang-plaintext">Apple clang version 14.0.0 (clang-1400.0.29.202)
</code></pre>
<p>If you are using Windows, you can check out <a target="_blank" href="https://www.codeblocks.org/">Code::Blocks</a> or look into installing <a target="_blank" href="https://learn.microsoft.com/en-us/windows/wsl/install">Linux on Windows with WSL</a>. Feel free to pick whatever programming environment works best for you.</p>
<p>An IDE is where you write, edit, save, run, and debug your C programs. You can think of it like a word processor but for writing code.</p>
<p><a target="_blank" href="https://code.visualstudio.com/">Visual Studio Code</a> is a great editor for writing code, and offers many IDE-like features.</p>
<p>It is free, open-source, supports many programming languages, and is available for all operating systems.</p>
<p>Once you have downloaded Visual Studio Code, install the <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools">C/C++ extension</a>.</p>
<p>It’s also a good idea to enable auto-saving by selecting: "File" -&gt; "Auto Save".</p>
<p>If you want to learn more, you can look through the <a target="_blank" href="https://code.visualstudio.com/docs/languages/cpp">Visual Studio Code documentation for C/C++</a>.</p>
<p>With your local machine all set up, you are ready to write your first C program!</p>
<h3 id="heading-how-to-write-your-first-c-program">How to Write Your First C Program</h3>
<p>To get started, open Visual Studio Code and create a new folder for your C program by navigating to "File" -&gt; "Open" -&gt; "New Folder".</p>
<p>Give this folder a name, for example, <code>c-practice</code>, and then select "Create" -&gt; “Open".</p>
<p>You should now have the <code>c-practice</code> folder open in Visual Studio Code.</p>
<p>Inside the folder you just created, create a new C file.</p>
<p>Hold down the <code>Command</code> key and press <code>N</code> on macOS or hold down the <code>Control</code> and press <code>N</code> for Windows/Linux to create an <code>Untitled-1</code> file.</p>
<p>Hold down the <code>Command</code> key and press <code>S</code> on macOS or hold down the <code>Control</code> key and press <code>S</code> for Windows/Linux, and save the file as a <code>main.c</code> file.</p>
<p>Finally, click "Save".</p>
<p>Make sure that you save the file you created with a <code>.c</code> extension, or it won’t be a valid C file.</p>
<p>You should now have the <code>main.c</code> file you just created open in Visual Studio Code.</p>
<p>Next, add the following 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-comment">// output 'Hello, world!' to the console</span>

  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Hello, world!\n"</span>);
}
</code></pre>
<p>Let’s go over each line and explain what is happening in the program.</p>
<h4 id="heading-what-are-header-files-in-c">What Are Header Files in C?</h4>
<p>Let’s start with the first line, <code>#include &lt;stdio.h&gt;</code>.</p>
<p>The <code>#include</code> part of <code>#include &lt;stdio.h&gt;</code> is a preprocessor command that tells the C compiler to include a file.</p>
<p>Specifically, it tells the compiler to include the <code>stdio.h</code> header file.</p>
<p>Header files are external libraries.</p>
<p>This means that some developers have written some functionality and features that are not included at the core of the C language.</p>
<p>By adding header files to your code, you get additional functionality that you can use in your programs without having to write the code from scratch.</p>
<p>The <code>stdio.h</code> header file stands for standard input-output.</p>
<p>It contains function definitions for input and output operations, such as functions for gathering user data and printing data to the console.</p>
<p>Specifically, it provides functions such as <code>printf()</code> and <code>scanf()</code>.</p>
<p>So, this line is necessary for the function we have later on in our program, <code>printf()</code>, to work.</p>
<p>If you don't include the <code>stdio.h</code> file at the top of your code, the compiler will not understand what the <code>printf()</code> function is.</p>
<h4 id="heading-what-is-the-main-function-in-c">What is the <code>main()</code> function in C?</h4>
<p>Next, <code>int main(void) {}</code> is the main function and starting point of every C program.</p>
<p>It is the first thing that is called when the program is executed.</p>
<p>Every C program must include a <code>main()</code> function.</p>
<p>The <code>int</code> keyword in <code>int main(void) {}</code> indicates the return value of the <code>main()</code> function.</p>
<p>In this case, the function will return an integer number.</p>
<p>And the <code>void</code> keyword inside the <code>main()</code> function indicates that the function receives no arguments.</p>
<p>Anything inside the curly braces, <code>{}</code>, is considered the body of the function – here is where you include the code you want to write. Any code written here will always run first.</p>
<p>This line acts as a boilerplate and starting point for all C programs. It lets the computer know where to begin reading the code when it executes your programs.</p>
<h4 id="heading-what-are-comments-in-c">What Are Comments in C?</h4>
<p>In C programming, comments are lines of text that get ignored by the compiler.</p>
<p>Writing comments is a way to provide additional information and describe the logic, purpose, and functionality of your code.</p>
<p>Comments provide a way to document your code and make it more readable and understandable for anyone who will read and work with it.</p>
<p>Having comments in your source code is also helpful for your future self. So when you come back to the code in a few months and don't remember how the code works, these comments can help.</p>
<p>Comments are also helpful for debugging and troubleshooting. You can temporarily comment out lines of code to isolate problems.</p>
<p>This will allow you to ignore a section of code and concentrate on the piece of code you are testing and working on without having to delete anything.</p>
<p>There are two types of comments in C:</p>
<ul>
<li><p>Single-line comments</p>
</li>
<li><p>Multi-line comments</p>
</li>
</ul>
<p>Single-line comments start with two forward slashes, <code>//</code>, and continue until the end of the line.</p>
<p>Here is the syntax for creating a single-line comment in C:</p>
<pre><code class="lang-c"><span class="hljs-comment">// I am a single-line comment</span>
</code></pre>
<p>Any text written after the forward slashes and on the same line gets ignored by the compiler.</p>
<p>Multi-line comments start with a forward slash, <code>/</code>, followed by an asterisk, <code>*</code>, and end with an asterisk, followed by a forward slash.</p>
<p>As the name suggests, they span multiple lines.</p>
<p>They offer a way to write slightly longer explanations or notes within your code and explain in more detail how it works.</p>
<p>Here is the syntax for creating a multi-line comment in C:</p>
<pre><code class="lang-c"><span class="hljs-comment">/*
This is
a multi-line
comment
*/</span>
</code></pre>
<h3 id="heading-what-is-the-printf-function-in-c">What is the <code>printf()</code> function in C?</h3>
<p>Inside the function's body, the line <code>printf("Hello, World!\n");</code> prints the text <code>Hello, World!</code> to the console (this text is also known as a string).</p>
<p>Whenever you want to display something, use the <code>printf()</code> function.</p>
<p>Surround the text you want to display in double quotation marks, <code>""</code>, and make sure it is inside the parentheses of the <code>printf()</code> function.</p>
<p>The semicolon, <code>;</code>, terminates the statement. All statements need to end with a semicolon in C, as it identifies the end of the statement.</p>
<p>You can think of a semicolon similar to how a full stop/period ends a sentence.</p>
<h3 id="heading-what-are-escape-sequences-in-c">What Are Escape Sequences in C?</h3>
<p>Did you notice the <code>\n</code> at the end of <code>printf("Hello, World!\n");</code>?</p>
<p>It's called an escape sequence, which means that it is a character that creates a newline and tells the cursor to move to the next line when it sees it.</p>
<p>In programming, an escape sequence is a combination of characters that represents a special character within a string.</p>
<p>They provide a way to include special characters that are difficult to represent directly in a string.</p>
<p>They consist of a backslash, <code>\</code>, also known as the escape character, followed by one or more additional characters.</p>
<p>The escape sequence for a newline character is <code>\n</code>.</p>
<p>Another escape sequence is <code>\t</code>. The <code>\t</code> represrents a tab character, and will insert a space within a string.</p>
<h3 id="heading-how-to-compile-and-run-your-first-c-program">How to Compile and Run Your first C Program</h3>
<p>In the previous section, you wrote your first C program:</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-comment">// output 'Hello, world!' to the console</span>

  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Hello, world!\n"</span>);
}
</code></pre>
<p>Any code you write in the C programming language is called source code.</p>
<p>Your computer doesn’t understand any of the C statements you have written, so this source code needs to be translated into a different format that the computer can understand. Here is where the compiler you installed earlier comes in handy.</p>
<p>The compiler will read the program and translate it into a format closer to the computer’s native language and make your program suitable for execution.</p>
<p>You will be able to see the output of your program, which should be <code>Hello, world!</code>.</p>
<p>The compilation of a C program consists of four steps: preprocessing, compilation, assembling, and linking.</p>
<p>The first step is preprocessing.</p>
<p>The preprocessor scans through the source code to find preprocessor directives, which are any lines that start with a <code>#</code> symbol, such as <code>#include</code> .</p>
<p>Once the preprocessor finds these lines, it substitutes them with something else.</p>
<p>For example, when the preprocessor finds the line <code>#include &lt;stdio.h&gt;</code>, the <code>#include</code> tells the preprocessor to include all the code from the <code>stdio.h</code> header file.</p>
<p>So, it replaces the <code>#include &lt;stdio.h&gt;</code> line with the actual contents of the <code>stdio.h</code> file.</p>
<p>The output of this phase is a modified version of the source code.</p>
<p>After preprocessing, the next step is the compilation phase, where the modified source code gets translated into the corresponding assembly code.</p>
<p>If there are any errors, compilation will fail, and you will need to fix the errors to continue.</p>
<p>The next step is the assembly phase, where the assembler converts the generated assembly code statements into machine code instructions.</p>
<p>The output of this phase is an object file, which contains the machine code instructions.</p>
<p>The last step is the linking phase.</p>
<p>Linking is the process of combining the object file generated from the assembly phase with any necessary libraries to create the final executable binary file.</p>
<p>Now, let’s go over the commands you need to enter to compile your <code>main.c</code> file.</p>
<p>In Visual Studio Code, open the built-in terminal by selecting "Terminal" -&gt; "New Terminal".</p>
<p>Inside the terminal, enter the following command:</p>
<pre><code class="lang-plaintext">gcc main.c
</code></pre>
<p>The <code>gcc</code> part of the command refers to the C compiler, and <code>main.c</code> is the file that contains the C code that you want to compile.</p>
<p>Next, enter the following command:</p>
<pre><code class="lang-plaintext">ls
</code></pre>
<p>The <code>ls</code> command lists the contents of the current directory.</p>
<pre><code class="lang-plaintext">a.out  main.c
</code></pre>
<p>The output of this command shows an <code>a.out</code> file – this is the executable file containing the source code statements in their corresponding binary instructions.</p>
<p>The <code>a.out</code> is the default name of the executable file created during the compilation process.</p>
<p>To run this file, enter the following command:</p>
<pre><code class="lang-plaintext">./a.out
</code></pre>
<p>This command tells the computer to look in the current directory, <code>./</code>, for a file named <code>a.out</code>.</p>
<p>The above command generates the following output:</p>
<pre><code class="lang-plaintext">Hello, world!
</code></pre>
<p>You also have the option to name the executable file instead of leaving it with the default <code>a.out</code> name.</p>
<p>Say you wanted to name the executable file <code>helloWorld</code>.</p>
<p>If you wanted to do this, you would need to enter the following command:</p>
<pre><code class="lang-plaintext">gcc -o helloWorld main.c
</code></pre>
<p>This command with the <code>-o</code> option (which stands for output) tells the <code>gcc</code> compiler to create an executable file named <code>helloWorld</code>.</p>
<p>To run the new executable file that you just created, enter the following command:</p>
<pre><code class="lang-plaintext">./helloWorld
</code></pre>
<p>This is the output of the above command:</p>
<pre><code class="lang-plaintext">Hello, world!
</code></pre>
<p>Note that whenever you make a change to your source code file, you have to repeat the process of compiling and running your program from the beginning to see the changes you made.</p>
<h2 id="heading-chapter-2-variables-and-data-types">Chapter 2: Variables and Data Types</h2>
<p>In this chapter, you will learn the basics of variables and data types – the fundamental storage units that allow you to preserve and manipulate data in your programs.</p>
<p>By the end of this chapter, you will know how to declare and initialize variables.</p>
<p>You will also have learned about various data types available in C, such as integers, floating-point numbers, and characters, which dictate how information is processed and stored within a program's memory.</p>
<p>Finally, you'll have learned how to receive user input in your programs, and how to use constants to store values that you don't want to be changed.</p>
<h3 id="heading-what-is-a-variable-in-c">What Is a Variable in C?</h3>
<p>Variables store different kind of data in the computer's memory, and take up a certain amount of space.</p>
<p>By storing information in a variable, you can retrieve and manipule it, perform various calculations, or even use it to make decisions in your program.</p>
<p>The stored data is given a name, and that is how you are able to access it when you need it.</p>
<h3 id="heading-how-to-declare-variables-in-c">How to Declare Variables in C</h3>
<p>Before you can use a variable, you need to declare it – this step lets the compiler know that it should allocate some memory for it.</p>
<p>C is a strongly typed language, so to declare a variable in C, you first need to specify the type of data the variable will hold, such as an integer to store a whole number, a floating-point number for numbers with decimal places, or a char for a single character.</p>
<p>That way, during compilation time, the compiler knows if the variable is able to perform the actions it was set out to do.</p>
<p>Once you have specified the data type, you give the variable a name.</p>
<p>The general syntax for declaring variables looks something like this:</p>
<pre><code class="lang-plaintext">data_type variable_name;
</code></pre>
<p>Let's take the following example:</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;
}
</code></pre>
<p>In the example above, I declared a variable named <code>age</code> that will hold integer values.</p>
<h4 id="heading-what-are-the-naming-conventions-for-variables-in-c">What Are the Naming Conventions for Variables in C?</h4>
<p>When it comes to variable names, they must begin either with a letter or an underscore.</p>
<p>For example, <code>age</code> and <code>_age</code> are valid variable names.</p>
<p>Also, they can contain any uppercase or lowercase letters, numbers, or an underscore character. There can be no other special symbols besides an underscore.</p>
<p>Lastly, variable names are case-sensitive. For example, <code>age</code> is different from <code>Age</code>.</p>
<h3 id="heading-how-to-initialize-variables-in-c">How to Initialize Variables in C</h3>
<p>Once you've declared a variable, it is a good practice to intialize it, which involves assigning an initial value to the variable.</p>
<p>The general syntax for initialzing a variable looks like this:</p>
<pre><code class="lang-plaintext">data_type variable_name = value;
</code></pre>
<p>The assignment operator, <code>=</code>, is used to assign the <code>value</code> to the <code>variable_name</code>.</p>
<p>Let's take the previous example and assign <code>age</code> a value:</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;

    age = <span class="hljs-number">29</span>;
}
</code></pre>
<p>I initialized the variable <code>age</code> by assigning it an integer value of <code>29</code>.</p>
<p>With that said, you can combine the initialization and declaration steps instead of performing them separately:</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-comment">// declaration + initialization</span>
    <span class="hljs-keyword">int</span> age = <span class="hljs-number">29</span>;
}
</code></pre>
<h3 id="heading-how-to-update-variable-values-in-c">How to Update Variable Values in C</h3>
<p>The values of variables can change.</p>
<p>For example, you can change the value of <code>age</code> without having to specify its type again.</p>
<p>Here is how you would change its value from <code>29</code> to <code>30</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-comment">// the variable age with its original value</span>
    <span class="hljs-keyword">int</span> age = <span class="hljs-number">29</span>;

    <span class="hljs-comment">// changing the value of age</span>
    <span class="hljs-comment">// the new value will be 30</span>
    age = <span class="hljs-number">30</span>;
}
</code></pre>
<p>Note that the data type of the new value being assigned must match the declared data type of the variable.</p>
<p>If it doesn't, the program will not run as expected. The compiler will raise an error during compilation time.</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">29</span>;

    <span class="hljs-comment">/*
    trying to assign a floating-point value
    to a variable with type int
    will cause an error in your program
    */</span>
    age = <span class="hljs-number">29.5</span>;
}
</code></pre>
<h3 id="heading-what-are-the-basic-data-types-in-c">What Are the Basic Data Types in C?</h3>
<p>Data types specify the type of form that information can have in C programs. And they determine what kind of operations can be performed on that information.</p>
<p>There are various built-in data types in C such as <code>char</code>, <code>int</code>, and <code>float</code>.</p>
<p>Each of the data types requires different allocation of memory.</p>
<p>Before exploring each one in more detail, let’s first go over the difference between signed and unsigned data types in C.</p>
<p>Signed data types can represent both positive and negative values.</p>
<p>On the other hand, unsigned data types can represent only non-negative values (zero and positive values).</p>
<p>Wondering when to use signed and when to use unsigned data types?</p>
<p>Use signed data types when you need to represent both positive and negative values, such as when working with numbers that can have positive and negative variations.</p>
<p>And use unsigned data types when you want to ensure that a variable can only hold non-negative values, such as when dealing with quantities.</p>
<p>Now, let's look at C data types in more detail.</p>
<h4 id="heading-what-is-the-char-data-type-in-c">What Is the <code>char</code> Data Type in C?</h4>
<p>The most basic data type in C is <code>char</code>.</p>
<p>It stands for "character" and it is one of the simplest and most fundamental data types in the C programming language.</p>
<p>You use it to store a single individual character such as an uppercase and lowercase letter of the ASCII (American Standard Code for Information Interchange) chart.</p>
<p>Some examples of <code>char</code>s are <code>'a'</code> and <code>'Z'</code>.</p>
<p>It can also store symbols such as <code>'!'</code>, and digits such as <code>'7'</code>.</p>
<p>Here is an example of how to create a variable that will hold a <code>char</code> value:</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> initial = <span class="hljs-string">'D'</span>;

 }
</code></pre>
<p>Notice how I used single quotation marks around the single character.</p>
<p>This is because you can't use double quotes when working with <code>char</code>s.</p>
<p>Double quotes are used for strings.</p>
<p>Regarding memory allocation, a signed <code>char</code> lets you store numbers ranging from <code>[-128 to 127</code>], and uses at least 1 byte (or 8 bits) of memory.</p>
<p>An unsigned char stores numbers ranging from <code>[0 to 255]</code>.</p>
<h4 id="heading-what-is-the-int-data-type-in-c">What Is the <code>int</code> Data Type in C?</h4>
<p>An <code>int</code> is a an integer, which is also known as a whole number.</p>
<p>It can hold a positive or negative value or <code>0</code>, but it can't hold numbers that contain decimal points (like <code>3.5</code>).</p>
<p>Some examples of integers are <code>0</code>, <code>-3</code>,and <code>9</code>.</p>
<p>Here is how you create a variable that will hold an <code>int</code> value:</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">29</span>;
 }
</code></pre>
<p>When you declare an <code>int</code>, the computer allocates at least 2 bytes (or 16 bits) of memory.</p>
<p>With that said, on most modern systems, an <code>int</code> typically allocates 4 bytes (or 32 bits) of memory.</p>
<p>The range of available numbers for a signed <code>int</code> is <code>[-32,768 to 32,767]</code> when it takes up 2 bytes and <code>[-2,147,483,648 to 2,147,483,647]</code> when it takes up 4 bytes of memory.</p>
<p>The range of numbers for an unsigned <code>int</code> doesn't include any of the negative numbers in the range mentioned for signed <code>int</code>s.</p>
<p>So, the range of numbers for unsigned <code>ints</code> that take up 2 bytes of memory is <code>[0 to 65,535]</code> and the range is <code>[0 to 4,294,967,295]</code> for those that take up 4 bytes.</p>
<p>To represent smaller numbers, you can use another data type – the <code>short int</code>. It typically takes up 2 bytes (or 16 bits) of memory.</p>
<p>A signed <code>short int</code> allows for numbers in a range from <code>[-32,768 to 32,767]</code>.</p>
<p>An unsigned <code>short int</code> allows for numbers in a range from <code>[0 to 65,535]</code>.</p>
<p>Use a <code>short</code> when you want to work with smaller integers, or when memory optimisation is critically important.</p>
<p>If you need to work with larger integers, you can also use other data types like <code>long int</code> or <code>long long int</code>, which provide a larger range and higher precision.</p>
<p>A <code>long int</code> typically takes up at least 4 bytes of memory (or 32 bits).</p>
<p>The values for a signed <code>long int</code> range from <code>[-2,147,483,648 to 2,147,483,647]</code>.</p>
<p>And the values for an unsigned <code>long int</code> range from <code>[0 to 4,294,967,295]</code>.</p>
<p>The <code>long long int</code> data type is able to use even larger numbers than a <code>long int</code>. It usually takes up 8 bytes (or 64 bits) of memory.</p>
<p>A signed <code>long long int</code> allows for a range from <code>[-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807]</code></p>
<p>And an unsigned <code>long long int</code> has a range of numbers from <code>[0 to 18,446,744,073,709,551,615]</code>.</p>
<h4 id="heading-what-is-the-float-data-type-in-c">What Is The <code>float</code> Data Type in C?</h4>
<p>The <code>float</code> data type is used to hold numbers with a decimal value (which are also known as real numbers).</p>
<p>It holds 4 bytes (or 32 bits) of memory and it is a single-precision floating-point type.</p>
<p>Here is how you create a variable that will hold a <code>float</code> value:</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">float</span> temperature = <span class="hljs-number">68.5</span>;
 }
</code></pre>
<p>A <code>double</code> is a floating point value and is the most commonly used floating-point data type in C.</p>
<p>It holds 8 bytes (or 64 bits) of memory, and it is a double-precision floating-point type.</p>
<p>Here is how you create a variable that will hold a <code>double</code> value:</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">double</span> number = <span class="hljs-number">3.14159</span>;
 }
</code></pre>
<p>When choosing which floating-point data type to use, consider the trade-off between memory usage and precision.</p>
<p>A <code>float</code> has less precision that a <code>double</code> but consumes less memory.</p>
<p>Use a <code>float</code> when memory usage is a concern (such as when working with a system with limited resources) or when you need to perform calculations where high precision is not critical.</p>
<p>If you require higher precision and accuracy for your calculations and memory usage is not critical, you can use a <code>double</code>.</p>
<h3 id="heading-what-are-format-codes-in-c">What Are Format Codes in C?</h3>
<p>Format codes are used in input and output functions, such as <code>scanf()</code> and <code>printf()</code>, respectively.</p>
<p>They act as placeholders and substitutes for variables.</p>
<p>Specifically, they specify the expected format of input and output.</p>
<p>They tell the program how to format or interpret the data being passed to or read from the <code>scanf()</code> and <code>printf()</code> functions.</p>
<p>The syntax for format codes is the <code>%</code> character and the format specifier for the data type of the variable.</p>
<p>Let's take the following example:</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">29</span>;

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"My age is %i\n"</span>, age);  <span class="hljs-comment">// My age is 29</span>
}
</code></pre>
<p>In the example above, <code>age</code> is the variable in the program. It is of type <code>int</code>.</p>
<p>The format code – or placeholder – for integer values is <code>%i</code>. This indicates that an integer should be printed.</p>
<p>In the program's output, <code>%i</code> is replaced with the value of <code>age</code>, which is <code>29</code>.</p>
<p>Here is a table with the format specifiers for each data type:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>FORMAT SPECIFIER</td><td>DATA TYPE</td></tr>
</thead>
<tbody>
<tr>
<td>%c</td><td>char</td></tr>
<tr>
<td>%c</td><td>unsigned char</td></tr>
<tr>
<td>%i, &amp;d</td><td>int</td></tr>
<tr>
<td>%u</td><td>unsigned int</td></tr>
<tr>
<td>%hi, %hd</td><td>short int</td></tr>
<tr>
<td>%hu</td><td>unsigned short int</td></tr>
<tr>
<td>%li or %ld</td><td>long int</td></tr>
<tr>
<td>%lu</td><td>unsigned long int</td></tr>
<tr>
<td>%lli or %lld</td><td>long long int</td></tr>
<tr>
<td>%llu</td><td>unsigned long long int</td></tr>
<tr>
<td>%f</td><td>float</td></tr>
<tr>
<td>%lf</td><td>double</td></tr>
<tr>
<td>%Lf</td><td>long double</td></tr>
</tbody>
</table>
</div><h3 id="heading-how-to-recieve-user-input-using-the-scanf-function">How to Recieve User Input Using the <code>scanf()</code> Function</h3>
<p>Earlier you saw how to print something to the console using the <code>printf()</code> function.</p>
<p>But what happens when you want to receive user input? This is where the <code>scanf()</code> function comes in.</p>
<p>The <code>scanf()</code> function reads user input, which is typically entered via a keyboard.</p>
<p>The user enters a value, presses the Enter key, and the value is saved in a variable.</p>
<p>The general syntax for using <code>scanf()</code> looks something similar to the following:</p>
<pre><code class="lang-c"><span class="hljs-built_in">scanf</span>(<span class="hljs-string">"format_string"</span>, &amp;variable);
</code></pre>
<p>Let's break it down:</p>
<ul>
<li><p><code>format_string</code> is the string that lets the computer know what to expect. It specifies the expected format of the input. For example, is it a word, a number, or something else?</p>
</li>
<li><p><code>&amp;variable</code> is the pointer to the variable where you want to store the value gathered from the user input.</p>
</li>
</ul>
<p>Let's take a look at an example of <code>scanf()</code> in action:</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> number;

  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Please enter your age: "</span>);

  <span class="hljs-built_in">scanf</span>(<span class="hljs-string">"%i"</span>, &amp;number);

  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Your age is %i\n"</span>, number);
}
</code></pre>
<p>In the example above, I first have to include the <code>stdio.h</code> header file, which provides input and output functions in C.</p>
<p>Then, in the <code>main()</code> function, I declare a variable named <code>number</code> that will hold integer values. This variable will store the user input.</p>
<p>Then, I prompt the user to enter a number using the <code>printf()</code> function.</p>
<p>Next, I use <code>scanf()</code> to read and save the value that the user enters.</p>
<p>The format specifier <code>%i</code> lets the computer known that it should expect an integer input.</p>
<p>Note also the <code>&amp;</code> symbol before the variable name. Forgetting to add it will cause an error.</p>
<p>Lastly, after receiving the input, I display the received value to the console using another <code>printf()</code> function.</p>
<h3 id="heading-what-are-constants-in-c">What are Constants in C?</h3>
<p>As you saw earlier on, variable values can be changed throughout the life of a program.</p>
<p>With that said, there may be times when you don’t want a value to be changed. This is where constants come in handy.</p>
<p>In C, a constant is a variable with a value that cannot be changed after declaration and during the program's execution.</p>
<p>You can create a constant in a similar way to how you create variables.</p>
<p>The differences between constants and variables is that with constants you have to use the <code>const</code> keyword before mentioning the data type.</p>
<p>And when working with constants, you should always specify a value.</p>
<p>The general syntax for declaring constants in C looks like this:</p>
<pre><code class="lang-plaintext">const data_type constant_name = value;
</code></pre>
<p>Here, <code>data_type</code> represents the data type of the constant, <code>constant_name</code> is the name you choose for the constant, and <code>value</code> is the value of the constant.</p>
<p>It is also best practice to use all upper case letters when declaring a constant’s name.</p>
<p>Let’s see an example of how to create a constant in 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-keyword">const</span> <span class="hljs-keyword">int</span> LUCKY_NUM = <span class="hljs-number">7</span>;

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"My lucky number is: %i\n"</span>, LUCKY_NUM);
}
</code></pre>
<p>In this example, <code>LUCKY_NUM</code> is defined as a constant with a value of <code>7</code>.</p>
<p>The constant's name, <code>LUCKY_NUM</code>, is in uppercase letters, as this is a best practice and convention that improves the readability of your code and distinguishes constants from variables.</p>
<p>Once defined, it cannot be modified in the program.</p>
<p>If you try to change its value, the C compiler will generate an error indicating that you are attempting to modify a constant.</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">const</span> <span class="hljs-keyword">int</span> LUCKY_NUM = <span class="hljs-number">7</span>;

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"My lucky number is: %i\n"</span>, LUCKY_NUM);

    LUCKY_NUM = <span class="hljs-number">13</span>; <span class="hljs-comment">// this will cause an error</span>

}
</code></pre>
<h2 id="heading-chapter-3-operators">Chapter 3: Operators</h2>
<p>Operators are essential building blocks in all programming languages.</p>
<p>They let you perform various operations on variables and values using symbols.</p>
<p>And they let you compare variables and values against each other for decision-making computatons.</p>
<p>In this chapter, you will learn about the most common operators in C programming.</p>
<p>You will first learn about arithmetic operators, which allow you to perform basic mathematical calculations.</p>
<p>You will then learn about relational (also known as comparisson operators), which help you compare values.</p>
<p>And you will learn about logical operators, which allow you to make decisions based on conditions.</p>
<p>After understanding these fundamental operators, you'll learn about some additional operators, such as assignment operators, and increment and decrement operators.</p>
<p>By the end of this chapter, you will have a solid grasp of how to use different operators to manipulate data.</p>
<h3 id="heading-what-are-the-arithmetic-operators-in-c">What Are the Arithmetic Operators in C?</h3>
<p>Arithmetic operators are used to perform basic arithmetic operations on numeric data types.</p>
<p>Operations include addition, subtraction, multiplication, division, and calculating the remainder after division.</p>
<p>These are the main arithmetic operators in C:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Operator</td><td>Operation</td></tr>
</thead>
<tbody>
<tr>
<td>+</td><td>Addition</td></tr>
<tr>
<td>-</td><td>Subtraction</td></tr>
<tr>
<td>*</td><td>Multiplication</td></tr>
<tr>
<td>/</td><td>Division</td></tr>
<tr>
<td>%</td><td>Remainder after division (modulo)</td></tr>
</tbody>
</table>
</div><p>Let's see examples of each one in action.</p>
<h4 id="heading-how-to-use-the-addition-operator">How to Use the Addition (<code>+</code>) Operator</h4>
<p>The addition operator adds two operands together and returns their sum.</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> a = <span class="hljs-number">5</span>;

    <span class="hljs-keyword">int</span> b = <span class="hljs-number">3</span>;

    <span class="hljs-keyword">int</span> sum = a + b;

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Sum: %i\n"</span>, sum); <span class="hljs-comment">// Output: Sum: 8</span>
}
</code></pre>
<h4 id="heading-how-to-use-the-subtraction-operator">How to Use the Subtraction (<code>-</code>) Operator</h4>
<p>The subtraction operator subtracts the second operand from the first operand and returns their difference.</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> a = <span class="hljs-number">10</span>; 

    <span class="hljs-keyword">int</span> b = <span class="hljs-number">5</span>;

    <span class="hljs-keyword">int</span> difference = a - b;

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Difference: %i\n"</span>, difference); <span class="hljs-comment">// Output: Difference: 5</span>
}
</code></pre>
<h4 id="heading-how-to-use-the-multiplication-operator">How to Use the Multiplication (<code>*</code>) Operator</h4>
<p>The multiplication operator multiplies two operands and returns their product.</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> a = <span class="hljs-number">4</span>;

    <span class="hljs-keyword">int</span> b = <span class="hljs-number">3</span>;

    <span class="hljs-keyword">int</span> product = a * b;

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Product: %i\n"</span>, product); <span class="hljs-comment">// Output: Product: 12</span>
}
</code></pre>
<h4 id="heading-how-to-use-the-division-operator">How to Use the Division (<code>/</code>) Operator</h4>
<p>The division operator divides the first operand by the second operand and returns their quotient.</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> a = <span class="hljs-number">10</span>;

    <span class="hljs-keyword">int</span> b = <span class="hljs-number">2</span>;

    <span class="hljs-keyword">int</span> quotient = a / b;

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Quotient: %i\n"</span>, quotient); <span class="hljs-comment">// Output: Quotient: 5</span>
}
</code></pre>
<h4 id="heading-how-to-use-the-modulo-operator">How to Use the Modulo (<code>%</code>) Operator</h4>
<p>The modulo operator returns the remainder of the first operand when divided by the second operand.</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> a = <span class="hljs-number">10</span>;

    <span class="hljs-keyword">int</span> b = <span class="hljs-number">3</span>;

    <span class="hljs-keyword">int</span> remainder = a % b;

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Remainder: %i\n"</span>, remainder); <span class="hljs-comment">// Output: Remainder: 1</span>
}
</code></pre>
<p>The modulo operator is commonly used to determine whether an integer is even or odd.</p>
<p>If the remainder of the operation is <code>1</code>, then the integer is odd. If there is no remainder, then the integer is even.</p>
<h3 id="heading-what-are-the-relational-operators-in-c">What Are The Relational Operators in C?</h3>
<p>Relational operators are used to compare values and return a result.</p>
<p>The result is a Boolean value. A Boolean value is either <code>true</code> (represented by <code>1</code>) or <code>false</code> (represented by <code>0</code>).</p>
<p>These operators are commonly used in decision-making statements such as <code>if</code> statements, and <code>while</code> loops.</p>
<p>These are the relational operators in C:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Operator</td><td>Name of Operator</td></tr>
</thead>
<tbody>
<tr>
<td>\==</td><td>Equal to</td></tr>
<tr>
<td>!=</td><td>Not equal to</td></tr>
<tr>
<td>\&gt;</td><td>Greater than</td></tr>
<tr>
<td>&lt;</td><td>Less than</td></tr>
<tr>
<td>\&gt;=</td><td>Greater than or equal to</td></tr>
<tr>
<td>&lt;=</td><td>Less than or equal to</td></tr>
</tbody>
</table>
</div><p>Let’s see an example of each one in action.</p>
<h4 id="heading-how-to-use-the-equal-to-operator">How to Use the Equal to (<code>==</code>) Operator</h4>
<p>The equal to operator checks if two values are equal.</p>
<p>It essentially asks the question, "Are these two values equal?"</p>
<p>Note that you use the comparisson operator (two equal signs – <code>==</code>) and not the assignment operator (<code>=</code>) which is used for assigning a value to a variable.</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> a = <span class="hljs-number">5</span>;

    <span class="hljs-keyword">int</span> b = <span class="hljs-number">5</span>;

    <span class="hljs-keyword">int</span> result = (a == b);

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Result: %i\n"</span>, result); <span class="hljs-comment">// Output: Result: 1</span>
}
</code></pre>
<p>The result is <code>1</code> (true), because <code>a</code> and <code>b</code> are equal.</p>
<h4 id="heading-how-to-use-the-not-equal-to-operator">How to Use the Not equal to (<code>!=</code>) Operator</h4>
<p>The not equal to operator checks if two values are NOT equal.</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> a = <span class="hljs-number">5</span>; 

    <span class="hljs-keyword">int</span> b = <span class="hljs-number">3</span>;

    <span class="hljs-keyword">int</span> result = (a != b);

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Result: %i\n"</span>, result); <span class="hljs-comment">// Output: Result: 1</span>
}
</code></pre>
<p>The result is <code>1</code> (true), because <code>a</code> and <code>b</code> are not equal.</p>
<h4 id="heading-how-to-use-the-greater-than-gt-operator">How to Use the Greater than (<code>&gt;</code>) Operator</h4>
<p>This operator compares two values to check if one is greater than the other.</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> a = <span class="hljs-number">10</span>;

    <span class="hljs-keyword">int</span>  b = <span class="hljs-number">5</span>;

    <span class="hljs-keyword">int</span> result = (a &gt; b);

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Result: %i\n"</span>, result); <span class="hljs-comment">// Output: Result: 1</span>
}
</code></pre>
<p>The result is <code>1</code> (true), because <code>a</code> is greater than <code>b</code>.</p>
<h4 id="heading-how-to-use-the-less-than-lt-operator">How to Use the Less than (<code>&lt;</code>) Operator</h4>
<p>This operator compares two values to check if one is less than the other.</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> a = <span class="hljs-number">10</span>;

    <span class="hljs-keyword">int</span> b = <span class="hljs-number">5</span>;

    <span class="hljs-keyword">int</span> result = (a &lt; b);

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Result: %i\n"</span>, result); <span class="hljs-comment">// Output: Result: 0</span>
}
</code></pre>
<p>The result is <code>0</code> (false), because <code>a</code> is not less than <code>b</code>.</p>
<h4 id="heading-how-to-use-the-greater-than-or-equal-to-gt-operator">How to Use the Greater than or Equal to (<code>&gt;=</code>) Operator</h4>
<p>This operator compares two values to check if one is greater than or equal to the other.</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> a = <span class="hljs-number">5</span>;

    <span class="hljs-keyword">int</span>  b = <span class="hljs-number">5</span>;

    <span class="hljs-keyword">int</span> result = (a &gt;= b);

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Result: %i\n"</span>, result); <span class="hljs-comment">// Output: Result: 1</span>
}
</code></pre>
<p>The result is <code>1</code> (true), because <code>a</code> is equal to <code>b</code>.</p>
<h4 id="heading-how-to-use-the-less-than-or-equal-to-lt-operator">How to Use the Less than or equal to (<code>&lt;=</code>) Operator</h4>
<p>This operator compares two values to check if one is less than or equal the other.</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> a = <span class="hljs-number">1</span>;

    <span class="hljs-keyword">int</span> b = <span class="hljs-number">5</span>;

    <span class="hljs-keyword">int</span> result = (a &lt;= b);

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Result: %i\n"</span>, result); <span class="hljs-comment">// Output: Result: 1</span>
}
</code></pre>
<p>The result is <code>1</code> (true), because <code>a</code> is less than <code>b</code>.</p>
<h3 id="heading-logical-operators">Logical Operators</h3>
<p>Logical operators operate on Boolean values and return a Boolean value.</p>
<p>Here are the logical operators used in C:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Operator</td><td>Name of Operator</td></tr>
</thead>
<tbody>
<tr>
<td><code>&amp;&amp;</code></td><td>Logical AND</td></tr>
<tr>
<td>`</td><td></td></tr>
<tr>
<td><code>!</code></td><td>Logical NOT</td></tr>
</tbody>
</table>
</div><p>Let's go into more detail on each one in the following sections.</p>
<h4 id="heading-how-to-use-the-and-ampamp-operator">How to Use the AND (<code>&amp;&amp;</code>) Operator</h4>
<p>The logical AND (<code>&amp;&amp;</code>) operator checks whether all operands are <code>true</code>.</p>
<p>The result is <code>true</code> only when all operands are <code>true</code>.</p>
<p>Here is the truth table for the AND (<code>&amp;&amp;</code>) operator when you are working with two operands:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>FIRST OPERAND</td><td>SECOND OPERAND</td><td>RESULT</td></tr>
</thead>
<tbody>
<tr>
<td>true</td><td>true</td><td>true</td></tr>
<tr>
<td>true</td><td>false</td><td>false</td></tr>
<tr>
<td>false</td><td>true</td><td>false</td></tr>
<tr>
<td>false</td><td>false</td><td>false</td></tr>
</tbody>
</table>
</div><p>Let's take the following example:</p>
<p>The result of <code>(10 == 10) &amp;&amp; (20 == 20)</code> is <code>true</code> because both operands are <code>true</code>.</p>
<p>Let's look at another example:</p>
<p>The result of <code>(10 == 20) &amp;&amp; (20 == 20)</code> is <code>false</code> because one of the operands is <code>false</code>.</p>
<p>When the first operand is <code>false</code>, the second operand is not evaluated (since there's no point - it's already determined that the first operand is false, so the result can only be <code>false</code>).</p>
<h4 id="heading-how-to-use-the-or-operator">How to Use the OR (<code>||</code>) Operator</h4>
<p>The logical OR (<code>||</code>) operator checks if at least one of the operands is <code>true</code>.</p>
<p>The result is <code>true</code> only when at least one of the operands is <code>true</code>.</p>
<p>Here is the truth table for the OR (<code>||</code>) operator when you are working with two operands:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>FIRST OPERAND</td><td>SECOND OPERAND</td><td>RESULT</td></tr>
</thead>
<tbody>
<tr>
<td>true</td><td>true</td><td>true</td></tr>
<tr>
<td>true</td><td>false</td><td>true</td></tr>
<tr>
<td>false</td><td>true</td><td>true</td></tr>
<tr>
<td>false</td><td>false</td><td>false</td></tr>
</tbody>
</table>
</div><p>Let's look at an example:</p>
<p>The result of <code>(10 == 20) || (20 == 20)</code> is <code>true</code> because one of the operands is <code>true</code>.</p>
<p>Let's look at another example:</p>
<p>The result of <code>(20 == 20) || (10 == 20)</code> is <code>true</code> because one of the operands is <code>true</code></p>
<p>If the first operand is <code>true</code>, then the second operator is not evaluated.</p>
<h3 id="heading-how-to-use-the-not-operator">How to Use the NOT (<code>!</code>) Operator</h3>
<p>The logical NOT (<code>!</code>) operator negates the operand.</p>
<p>If the operand is <code>true</code>, it returns <code>false</code>.</p>
<p>And if it is <code>false</code>, it returns <code>true</code>.</p>
<p>You may want to use the NOT operator when when you want to flip the value of a condition and return the opposite of what the condition evaluates to.</p>
<p>Here is the truth table for the NOT(<code>!</code>) operator:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>OPERAND</td><td>RESULT</td></tr>
</thead>
<tbody>
<tr>
<td>true</td><td>false</td></tr>
<tr>
<td>false</td><td>true</td></tr>
</tbody>
</table>
</div><p>Let's look at an example:</p>
<p>The result of <code>!(10 == 10)</code> is <code>false</code>.</p>
<p>The condition <code>10 == 10</code> is <code>true</code>, but the <code>!</code> operator negates it so the result is <code>false</code>.</p>
<p>And let's look at another example:</p>
<p>The result of <code>!(10 == 20)</code> is <code>true</code>.</p>
<p>The condition <code>10 == 20</code> is false, but the <code>!</code> operator negates it.</p>
<h3 id="heading-what-is-the-assignement-operator-in-c">What Is the Assignement Operator in C?</h3>
<p>The assignment operator is used to assign a value to a variable.</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-comment">// declare an integer variable named num</span>
    <span class="hljs-keyword">int</span> num;

    <span class="hljs-comment">// assign the value 10 to num</span>
    num = <span class="hljs-number">10</span>;

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"num: %i\n"</span>, num); <span class="hljs-comment">// Output: num: 10</span>

}
</code></pre>
<p>In the example above, the value <code>10</code> is assigned to the variable <code>num</code> using the assignment operator.</p>
<p>The assignment operator works by evaluating the expression on the right-hand side and then storing its result in the variable on the left-hand side.</p>
<p>The type of data assigned should match the data type of the variable.</p>
<h4 id="heading-how-to-use-compound-assignment-operators">How to Use Compound Assignment Operators</h4>
<p>Compound assignment operators are shorthand notations.</p>
<p>They allow you to modify a variable by performing an operation on it and then storing the result of the operation back into the same variable in a single step.</p>
<p>This can make your code more concise and easier to read.</p>
<p>Some common compound assignment operators in C include:</p>
<ul>
<li><p><code>+=</code>: Addition and assignment</p>
</li>
<li><p><code>=</code>: Subtraction and assignment</p>
</li>
<li><p><code>=</code>: Multiplication and assignment</p>
</li>
<li><p><code>/=</code>: Division and assignment</p>
</li>
<li><p><code>%=</code>: Modulo and assignment</p>
</li>
</ul>
<p>Let’s see an example of how the <code>+=</code> operator works:</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> num = <span class="hljs-number">10</span>;

  num += <span class="hljs-number">5</span>; 

  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Num: %i\n"</span>, num); <span class="hljs-comment">// Num: 15</span>
}
</code></pre>
<p>In the example above, I created a variable named <code>num</code> and assigned it an initial value of <code>10</code>.</p>
<p>I then wanted to increment the variable by <code>5</code>. To do this, I used the <code>+=</code> compound operator.</p>
<p>The line <code>num += 5</code> increments the value of <code>num</code> by 5, and the result (15) is stored back into <code>num</code> in one step.</p>
<p>Note that the <code>num += 5;</code> line works exactly the same as doing <code>num = num + 5</code>, which would mean <code>num = 10 + 5</code>, but with fewer lines of code.</p>
<h3 id="heading-what-are-the-increment-and-decrement-operators-in-c">What Are the Increment and Decrement Operators in C?</h3>
<p>The increment <code>++</code> and decrement <code>--</code> operators increment and decrement a variable by one, respectively.</p>
<p>Let’s look at an example of how to use the <code>++</code> operator:</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> num = <span class="hljs-number">10</span>;
  num++;

  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Num: %i\n"</span>, num); <span class="hljs-comment">// Num: 11</span>

}
</code></pre>
<p>The initial value of the variable <code>num</code> is <code>10</code>.</p>
<p>By using the <code>++</code> increment operator, the value of <code>num</code> is set to <code>11</code>.</p>
<p>This is like perfoming <code>num = num + 1</code> but with less code.</p>
<p>The shorthand for decrementing a variable by one is <code>--</code>.</p>
<p>If you wanted to decrement <code>num</code> by one, you would do the following:</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> num = <span class="hljs-number">10</span>;
  num--;

  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Num: %i\n"</span>, num); <span class="hljs-comment">// Num: 9</span>

}
</code></pre>
<p>The initial value of the variable <code>num</code> is <code>10</code>.</p>
<p>By using the <code>--</code> increment operator, the value of <code>num</code> is now set to <code>9</code>.<br>This is like perfoming <code>num = num - 1</code>.</p>
<h2 id="heading-chapter-4-conditional-statements">Chapter 4: Conditional Statements</h2>
<p>The examples you have seen so far all execute line by line, from top to bottom.</p>
<p>They are not flexible and dynamic and do not adapt according to user behavior or specific situations.</p>
<p>In this chapter, you will learn how to make decisions and control the flow of a program.</p>
<p>You get to set the rules on what happens next in your programs by setting conditions using conditional statements.</p>
<p>Conditional statements take a specific action based on the result of a comparisson that takes place.</p>
<p>The program will decide what the next steps should be based on whether the conditions are met or not.</p>
<p>Certain parts of the program may not run depending on the results or depending on certain user input. The user can go down different paths depending on the various forks in the road that come up during a program's life.</p>
<p>First, you will learn about the <code>if</code> statement – the foundational building block of decision-making in C.</p>
<p>You will also learn about the <code>else if</code> and <code>else</code> statements that are added to the <code>if</code> statement to provide additional flexibility to the program.</p>
<p>You will then learn about the ternary operator which allows you to condense decision-making logic into a single line of code and improve the readability of your program.</p>
<h3 id="heading-how-to-create-an-if-statement-in-c">How to Create an <code>if</code> statement in C</h3>
<p>The most basic conditional statement in C is the <code>if</code> statement.</p>
<p>It makes a decision based on a condition.</p>
<p>If the given condition evaluates to <code>true</code> only then is the code inside the <code>if</code> block executed.</p>
<p>If the given condition evaluates to <code>false</code>, the code inside the <code>if</code> block is ignored and skipped.</p>
<p>The general syntax for an <code>if</code> statement in C is the following:</p>
<pre><code class="lang-c"><span class="hljs-keyword">if</span> (condition) {
  <span class="hljs-comment">// run this code if condition is true</span>
}
</code></pre>
<p>Let's look at an example:</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-comment">// variable age</span>
   <span class="hljs-keyword">int</span> age;

   <span class="hljs-comment">// prompt user to enter their age</span>
   <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Please enter your age: "</span>);

   <span class="hljs-comment">// store user's answer in the variable</span>
   <span class="hljs-built_in">scanf</span>(<span class="hljs-string">"%i"</span>, &amp;age);

    <span class="hljs-comment">// check if age is less than 18</span>
    <span class="hljs-comment">// if it is, then and only then, print a message to the console</span>

   <span class="hljs-keyword">if</span> (age &lt; <span class="hljs-number">18</span>) {
       <span class="hljs-built_in">printf</span>(<span class="hljs-string">"You need to be over 18 years old to continue\\n"</span>);
   }
}
</code></pre>
<p>In the above code, I created a variable named <code>age</code> that holds an integer value.</p>
<p>I then prompted the user to enter their age and stored the answer in the variable <code>age</code>.</p>
<p>Then, I created a condition that checks whether the value contained in the variable <code>age</code> is less than 18.</p>
<p>If so, I want a message printed to the console letting the user know that to proceed, the user should be at least 18 years of age.</p>
<p>When asked for my age and I enter <code>16</code>, I'd get the following output:</p>
<pre><code class="lang-plaintext">#output

Please enter your age: 16
You need to be over 18 years old to continue
</code></pre>
<p>The condition (<code>age &lt; 18</code>) evaluates to <code>true</code> so the code in the <code>if</code> block executes.</p>
<p>Then, I re-compile and re-run the program.</p>
<p>This time, when asked for my age, say I enter <code>28</code>, but I don't get any output:</p>
<pre><code class="lang-plaintext">#output

Please enter your age: 28
</code></pre>
<p>This is because the condition evaluates to <code>false</code> and therefore the body of the <code>if</code> block is skipped.</p>
<p>I have also not specified what should happen in the case that the user's age is greater than 18.</p>
<p>To specify what happens in case the user's age is greater than 18, I can use an <code>if else</code> statement.</p>
<h3 id="heading-how-to-create-an-if-else-statement-in-c">How to Create an <code>if else</code> statement in C</h3>
<p>You can add an <code>else</code> clause to an <code>if</code> statement to provide code that will execute only when the <code>if</code> statement evaluates to <code>false</code>.</p>
<p>The <code>if else</code> statement essentially means that "<code>if</code> this condition is true do the following thing, <code>else</code> do this thing instead".</p>
<p>If the condition inside the parentheses evaluates to <code>true</code>, the code inside the <code>if</code> block will execute.</p>
<p>But if that condition evaluates to <code>false</code>, the code inside the <code>else</code> block will execute.</p>
<p>The <code>else</code> keyword is the solution for when the <code>if</code> condition is false and the code inside the <code>if</code> block doesn't run. It provides an alternative.</p>
<p>The general syntax looks like this:</p>
<pre><code class="lang-c"><span class="hljs-keyword">if</span> (condition) {
  <span class="hljs-comment">// run this code if condition is true</span>
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">// if the condition above is false, run this code</span>
}
</code></pre>
<p>Now, let's revisit the example from the previous section, and specify what should happen if the user's age is greater than 18:</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-built_in">printf</span>(<span class="hljs-string">"Please enter your age: "</span>);

   <span class="hljs-built_in">scanf</span>(<span class="hljs-string">"%i"</span>, &amp;age);


    <span class="hljs-comment">// if the condition in the parentheses is true the code inside the curly braces will execute</span>
    <span class="hljs-comment">// otherwise it is skipped</span>
    <span class="hljs-comment">// and the code in the else block will execute</span>

   <span class="hljs-keyword">if</span> (age &lt; <span class="hljs-number">18</span>) {
       <span class="hljs-built_in">printf</span>(<span class="hljs-string">"You need to be over 18 years old to continue\n"</span>);
   } <span class="hljs-keyword">else</span> {
      <span class="hljs-built_in">printf</span>(<span class="hljs-string">"You are over 18 so you can continue \n"</span>);
  }

   }
</code></pre>
<p>If the condition is <code>true</code> the code in the <code>if</code> block runs:</p>
<pre><code class="lang-plaintext">#output

Please enter your age: 14
You need to be over 18 years old to continue
</code></pre>
<p>If the condition is <code>false</code> the code in the <code>if</code> block is skipped and the code in the <code>else</code> block runs instead:</p>
<pre><code class="lang-plaintext">#output

Please enter your age: 45
You are over 18 so you can continue
</code></pre>
<h3 id="heading-how-to-create-an-else-if-statement-in-c">How to Create an <code>else if</code> statement in C</h3>
<p>But what happens when you want to have more than one condition to choose from?</p>
<p>If you wish to chose between more than one option you can introduce an <code>else if</code> statement.</p>
<p>An <code>else if</code> statement essentially means that "If this condition is true, do the following. If it isn't, do this instead. However, if none of the above are true and all else fails, finally do this."</p>
<p>The general syntax looks something like the following:</p>
<pre><code class="lang-plaintext">if (condition) {
   // if condition is true run this code
} else if(another_condition) {
   // if the above condition was false and this condition is true,
   // run the code in this block
} else {
   // if the two above conditions are false run this code
}
</code></pre>
<p>Let's see how an <code>else if</code> statement works.</p>
<p>Say you have the following example:</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-built_in">printf</span>(<span class="hljs-string">"Please enter your age: "</span>);

   <span class="hljs-built_in">scanf</span>(<span class="hljs-string">"%i"</span>, &amp;age);

   <span class="hljs-keyword">if</span> (age &lt; <span class="hljs-number">18</span>) {
       <span class="hljs-built_in">printf</span>(<span class="hljs-string">"You need to be over 18 years old to continue\n"</span>);
   }  <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (age &lt; <span class="hljs-number">21</span>) {
       <span class="hljs-built_in">printf</span>(<span class="hljs-string">"You need to be over 21\n"</span>);
   } <span class="hljs-keyword">else</span> {
      <span class="hljs-built_in">printf</span>(<span class="hljs-string">"You are over 18 and older than 21 so you can continue \n"</span>);
  }

   }
</code></pre>
<p>If the first <code>if</code> statement is true, the rest of the block will not run:</p>
<pre><code class="lang-plaintext">#output

Please enter your age: 17
You need to be over 18 years old to continue
</code></pre>
<p>If the first <code>if</code> statement is false, then the program moves on to the next condition.</p>
<p>If that is true the code inside the <code>else if</code> block executes and the rest of the block doesn't run:</p>
<pre><code class="lang-plaintext">#output

Please enter your age: 20
You are need to be over 21
</code></pre>
<p>If both of the previous conditions are all false, then the last resort is the <code>else</code> block which is the one to execute:</p>
<pre><code class="lang-plaintext">#output

Please enter your age: 22
You are over 18 and older than 21 so you can continue
</code></pre>
<h3 id="heading-how-to-use-the-ternary-operator-in-c">How to Use the Ternary Operator in C</h3>
<p>The ternary operator (also known as the conditional operator) allows you to write an <code>if else</code> statement with fewer lines of code.</p>
<p>It can provide a way of writing more readable and concise code and comes in handy when writing simple conditional expressions.</p>
<p>You would want to use it when you are making making simple decisions and want to keep your code concise and on one line.</p>
<p>However, it's best to stick to a regular <code>if-else</code> statement when you are dealing with more complex decisions as the ternary operator could make your code hard to read.</p>
<p>The general syntax for the ternary operator looks something similar to the following:</p>
<pre><code class="lang-plaintext">condition ? expression_if_true : expression_if_false;
</code></pre>
<p>Let's break it down:</p>
<ul>
<li><p><code>condition</code> is the condition you want to evaluate. This condition will evaluate to either <code>true</code> of <code>false</code></p>
</li>
<li><p><code>?</code> separates the condition from the two possible expressions</p>
</li>
<li><p><code>expression_if_true</code> is executed if the <code>condition</code> evaluates to <code>true</code></p>
</li>
<li><p><code>:</code> separates the <code>expression_if_true</code> from the <code>expression_if_false</code></p>
</li>
<li><p><code>expression_if_false</code> is executed if the <code>condition</code> evaluates to <code>false</code>.</p>
</li>
</ul>
<p>Let's take a look at an example:</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> x = <span class="hljs-number">10</span>;

    <span class="hljs-keyword">int</span> y = (x &gt; <span class="hljs-number">5</span>) ? <span class="hljs-number">100</span> : <span class="hljs-number">200</span>;

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"x: %i\n"</span>, x); <span class="hljs-comment">// x: 10</span>

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"y: %i\n"</span>, y);  <span class="hljs-comment">// y: 100</span>
   }
</code></pre>
<p>In the example above, the condition is <code>(x &gt; 5)</code>.</p>
<p>If <code>x</code> is greater than 5, the condition evaluates to <code>true</code>. And when the condition is <code>true</code>, the value assigned to <code>y</code> will be <code>100</code>.</p>
<p>If the condition evaluates to <code>false</code>, the value assigned to <code>y</code> will be <code>200</code>.</p>
<p>So, since <code>x</code> is greater than 5 (<code>x = 10</code>), <code>y</code> is assigned the value <code>100</code>.</p>
<h2 id="heading-chapter-5-loops">Chapter 5: Loops</h2>
<p>In this chapter you will learn about loops, which are essential for automating repetitive tasks without having to write the same code multiple times.</p>
<p>Loops allow you to execute a specific block of code instructions repeatedly over and over again until a certain condition is met.</p>
<p>You will learn about the different types of loops, such as the <code>for</code> , <code>while</code> and <code>do-while</code> loops, and understand their syntax and when you should use each one.</p>
<p>You will also learn about the <code>break</code> statement, which allows you to control the execution flow within loops in specific ways.</p>
<h3 id="heading-how-to-create-a-for-loop-in-c">How to Create a <code>for</code> Loop in C</h3>
<p>A <code>for</code> loop allows you to execute a block of code repeatedly based on a specified condition.</p>
<p>It's useful when you know how many times you want to repeat a certain action.</p>
<p>The general syntax for a <code>for</code> loop looks like this:</p>
<pre><code class="lang-plaintext">for (initialization; condition; increment/decrement) {
    // Code to be executed in each iteration
}
</code></pre>
<p>Let's break it down:</p>
<ul>
<li><p><code>initialization</code> is the step where you initialize a loop control variable. It's typically used to set the starting point for your loop.</p>
</li>
<li><p><code>condition</code> is the condition that is evaluated before each iteration. If the condition is <code>true</code>, the loop continues. If it's <code>false</code>, the loop terminates. The loop will run as long as the condition remains true.</p>
</li>
<li><p><code>increment/decrement</code> is the part responsible for changing the loop control variable after each iteration. It can be an increment (<code>++</code>), a decrement (<code>--</code>), or any other modification.</p>
</li>
<li><p><code>Code to be executed in each iteration</code> is the block of code inside the <code>for</code> loop's body that gets executed in each iteration if the condition is <code>true</code>.</p>
</li>
</ul>
<p>Let's see an example of how a <code>for</code> loop works.</p>
<p>Say you want to print the numbers from 1 to 5 to the console:</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> </span>{

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt;= <span class="hljs-number">5</span>; i++) {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Iteration %i\n"</span>, i);
    }

}
</code></pre>
<p>Output:</p>
<pre><code class="lang-plaintext">Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
</code></pre>
<p>In the example above, I first initialize the loop control variable <code>i</code> with a value of <code>1</code>.</p>
<p>The condition <code>i &lt;= 5</code> is true, so the loop's body is executed and <code>"Iteration 1"</code> is printed.</p>
<p>After each iteration, the value of <code>i</code> is incremented by <code>1</code>. So, <code>i</code> is incremented to <code>2</code>.</p>
<p>The condition is still <code>true</code>, so <code>"Iteration 2"</code> is printed.</p>
<p>The loop will continue as long as <code>i</code> is less than or equal to <code>5</code>.</p>
<p>When <code>i</code> becomes <code>6</code>, the condition evaluates to <code>false</code> and the loop terminates.</p>
<h3 id="heading-how-to-create-a-while-loop-in-c">How to Create a <code>while</code> Loop in C</h3>
<p>As you saw in the previous section, a <code>for</code> loop is used when you know the exact number of iterations you want the loop to perform.</p>
<p>The <code>while</code> loop is useful when you want to repeat an action based on a condition but don't know the exact number of iterations beforehand.</p>
<p>Here is the general syntax of a <code>while</code> loop:</p>
<pre><code class="lang-plaintext">while (condition) {
    // Code to be executed in each iteration
}
</code></pre>
<p>With a <code>while</code> loop, the condition is evaluated before each iteration. If the condition is <code>true</code>, the loop continues. If it's false, the loop terminates.</p>
<p>The <code>while</code> loop will continue as long as the condition evaluates to <code>true</code>.</p>
<p>Something to note with <code>while</code> loops is that the code in the loop's body is not guaranteed to run even at least one time if a condition is not met.</p>
<p>Let's see an example of how a <code>while</code> loop works:</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> </span>{

    <span class="hljs-keyword">int</span> count = <span class="hljs-number">1</span>;

    <span class="hljs-keyword">while</span> (count &lt;= <span class="hljs-number">5</span>) {

        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Iteration %i\n"</span>, count);

        count++;
    }

}
</code></pre>
<p>Output:</p>
<pre><code class="lang-plaintext">Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
</code></pre>
<p>In the example above, I first initialize a variable <code>count</code> with a value of <code>1</code>.</p>
<p>Before it runs any code, the <code>while</code> loop checks a condition.</p>
<p>The condition <code>count &lt;= 5</code> is <code>true</code> because count is initially <code>1</code>. So, the loop's body is executed and <code>"Iteration 1"</code> is printed.</p>
<p>Then, <code>count</code> is incremented to <code>2</code>.</p>
<p>The condition is still <code>true</code>, so <code>"Iteration 2"</code> is printed.</p>
<p>The loop will continue as long as count is less than or equal to 5.</p>
<p>This process continues until count becomes <code>6</code>, at which point the condition becomes <code>false</code>, and the loop terminates.</p>
<p>Something to be aware of when working with <code>while</code> loops is accidentally creating an infinite loop:</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">while</span>(<span class="hljs-literal">true</span>)
    {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Hello world"</span>);
    }
}
</code></pre>
<p>In this case the condition always evaluates to <code>true</code>.</p>
<p>After printing the line of code inside the curly braces, it continuously checks wether it should run the code again.</p>
<p>As the answer is always yes (since the condition it needs to check is always true each and every time), it runs the code again and again and again.</p>
<p>The way to stop the program and escape from the endless loop is running <code>Ctrl C</code> in the terminal.</p>
<h3 id="heading-how-to-create-a-do-while-loop-in-c">How to Create a <code>do-while</code> Loop in C</h3>
<p>As mentioned in the previous section, the code in the <code>while</code> loop's body is not guaranteed to run even at least one time if the condition is not met.</p>
<p>A <code>do-while</code> loop executes a block of code repeatedly for as long as a condition remains <code>true</code>.</p>
<p>However, in contrast to a <code>while</code> loop, it is guaranteed to run at least once, regardless of whether the condition is <code>true</code> or <code>false</code> from the beginning.</p>
<p>So, the <code>do-while</code> loop is useful when you want to ensure that the loop's body is executed at least once before the condition is checked.</p>
<p>The general syntax for a <code>do-while</code> loop looks like this:</p>
<pre><code class="lang-plaintext">do {
    // Code to be executed in each iteration
} while (condition);
</code></pre>
<p>Let's take a look at an example that demonstrates how a <code>do-while</code> loop works:</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> </span>{

    <span class="hljs-keyword">int</span> count = <span class="hljs-number">1</span>;

    <span class="hljs-keyword">do</span> {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Iteration %i\n"</span>, count);

        count++;

    } <span class="hljs-keyword">while</span> (count &lt;= <span class="hljs-number">5</span>);

}
</code></pre>
<p>Output:</p>
<pre><code class="lang-plaintext">Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
</code></pre>
<p>In the example above I initialize a variable <code>count</code> with a value of <code>1</code>.</p>
<p>A <code>do-while</code> loop first does something and then checks a condition.</p>
<p>So, the block of code inside the loop is executed at least one time.</p>
<p>The string <code>"Iteration 1"</code> is printed and then <code>count</code> is incremented to <code>2</code>.</p>
<p>The condition <code>count &lt;= 5</code> is then checked and it evaluates to <code>true</code>, so the loop continues.</p>
<p>The loop will continue as long as <code>count</code> is less than or equal to 5.</p>
<p>After the iteration where <code>count</code> is <code>6</code>, the condition becomes <code>false</code>, and the loop terminates.</p>
<h3 id="heading-how-to-use-the-break-statement-in-c">How to Use the <code>break</code> Statement in C</h3>
<p>The <code>break</code> statement is used to immediately exit a loop and terminate its execution.</p>
<p>It's a control flow statement that allows you to interrupt the normal loop execution and move on to the code after the loop.</p>
<p>The <code>break</code> statement is especially useful when you want to exit a loop under specific conditions, even if the loop's termination condition hasn't been met.</p>
<p>You might use it when you encounter a certain value, or when a specific condition is met.</p>
<p>Here's how to use a <code>break</code> statement in a loop:</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> </span>{
    <span class="hljs-keyword">int</span> target = <span class="hljs-number">5</span>;

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt;= <span class="hljs-number">10</span>; i++) {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Current value: %i\n"</span>, i);

        <span class="hljs-keyword">if</span> (i == target) {
            <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Target value reached. Exiting loop.\n"</span>);
            <span class="hljs-keyword">break</span>; <span class="hljs-comment">// Exit the loop</span>
        }
    }

}
</code></pre>
<p>Output:</p>
<pre><code class="lang-plaintext">Current value: 1
Current value: 2
Current value: 3
Current value: 4
Current value: 5
Target value reached. Exiting loop.
</code></pre>
<p>In the example above, a <code>for</code> loop is set to iterate from <code>1</code> to <code>10</code>.</p>
<p>Inside the loop, the current value of <code>i</code> is printed on each iteration.</p>
<p>There is also an <code>if</code> statement that checks if the current value of <code>i</code> matches the target value, which is set to <code>5</code>.</p>
<p>If <code>i</code> matches the target value, the <code>if</code> statement is triggered and a message is printed.</p>
<p>As a result, the <code>break</code> statement exits the current loop immediately and prematurely.</p>
<p>The program will continue executing the code that is after the loop.</p>
<h2 id="heading-chapter-6-arrays">Chapter 6: Arrays</h2>
<p>Arrays offer a versatile and organized way to store multiple pieces of related data that are arranged in an ordered sequence.</p>
<p>They allow you to store multiple values of the same data type under a single identifier and perform repetitive tasks on each element.</p>
<p>In this chapter, you will learn how to declare and initialize arrays. You will also learn how to access individual elements within an array using index notation and modify them.</p>
<p>In addition, you will learn how to use loops to iterate through array elements and perform operations on each element.</p>
<h3 id="heading-how-to-declare-and-initialize-an-array-in-c">How to Declare and Initialize an Array in C</h3>
<p>To declare an array in C, you first specify the data type of the elements the array will store.</p>
<p>This means you can create arrays of type <code>int</code>, <code>float</code>, <code>char</code>, and so on.</p>
<p>You then specify the array's name, followed by the array's size in square brackets.</p>
<p>The size of the array is the number of elements that it can hold. This number must be a positive integer.</p>
<p>Keep in mind that arrays have a fixed size, and once declared, you cannot change it later on.</p>
<p>Here is the general syntax for declaring an array:</p>
<pre><code class="lang-c">data_type array_name[array_size];
</code></pre>
<p>Here is how to declare an array of integers:</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> </span>{

   <span class="hljs-keyword">int</span> grades[<span class="hljs-number">5</span>];
}
</code></pre>
<p>In the example above, I created an array named <code>grades</code> that can store <code>5</code> <code>int</code> numbers.</p>
<p>After declaring an array, you can initialize it with initial values.</p>
<p>To do this, use the assignment operator, <code>=</code>, followed by curly braces, <code>{}</code>.</p>
<p>The curly braces will enclose the values, and each value needs to be separated by a comma.</p>
<p>Here is how to initialize the <code>grades</code> array:</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> </span>{

   <span class="hljs-keyword">int</span> grades[<span class="hljs-number">5</span>] = {<span class="hljs-number">50</span>, <span class="hljs-number">75</span>, <span class="hljs-number">100</span>, <span class="hljs-number">67</span>, <span class="hljs-number">90</span>};
}
</code></pre>
<p>Keep in mind that the number of values should match the array size, otherwise you will encounter errors.</p>
<p>Something to note here is that you can also partially initialize the array:</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> </span>{

   <span class="hljs-keyword">int</span> grades[<span class="hljs-number">5</span>] = {<span class="hljs-number">50</span>, <span class="hljs-number">75</span>, <span class="hljs-number">100</span>};
}
</code></pre>
<p>In this case, the remaining two elements will be set to <code>0</code>.</p>
<p>Another way to initialize arrays is to omit the array's length inside the square brackets and only assign the initial values, like so:</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> </span>{

   <span class="hljs-keyword">int</span> grades[] = {<span class="hljs-number">50</span>, <span class="hljs-number">75</span>, <span class="hljs-number">100</span>, <span class="hljs-number">67</span>, <span class="hljs-number">90</span>};
}
</code></pre>
<p>In this example, the array's size is <code>5</code> because I assigned it <code>5</code> values.</p>
<h4 id="heading-how-to-find-the-length-of-an-array-in-c-using-the-sizeof-operator">How to Find the Length of an Array in C Using the <code>sizeof()</code> Operator</h4>
<p>The <code>sizeof</code> operator comes in handy when you need to calculate the size of an array.</p>
<p>Let's see an example of the <code>sizeof</code> operator in action:</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> </span>{

    <span class="hljs-keyword">int</span> grades[] = {<span class="hljs-number">50</span>, <span class="hljs-number">75</span>, <span class="hljs-number">100</span>, <span class="hljs-number">67</span>, <span class="hljs-number">90</span>};

    <span class="hljs-comment">// calculate the size of the array</span>
    <span class="hljs-keyword">int</span> array_size = <span class="hljs-keyword">sizeof</span>(grades);

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Size of array: %i bytes\n"</span>, array_size);
}
</code></pre>
<p>Output:</p>
<pre><code class="lang-plaintext">Size of array: 20 bytes
</code></pre>
<p>In the example above, <code>sizeof(grades)</code> calculates the total size of the array in bytes.</p>
<p>In this case, the array has five integers.</p>
<p>As mentioned in a previous chapter, on most modern systems an <code>int</code> typically occupies 4 bytes of memory. Therefore, the total size is <code>5 x 4 = 20</code> bytes of memory for the entire array.</p>
<p>Here is how you can check how much memory each <code>int</code> occupies using the <code>sizeof</code> operator:</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> </span>{

    <span class="hljs-keyword">int</span> grades[] = {<span class="hljs-number">50</span>, <span class="hljs-number">75</span>, <span class="hljs-number">100</span>, <span class="hljs-number">67</span>, <span class="hljs-number">90</span>};

    <span class="hljs-comment">// calculate the size of a single array element</span>
    <span class="hljs-keyword">int</span> element_size = <span class="hljs-keyword">sizeof</span>(grades[<span class="hljs-number">0</span>]);

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Size of a single element: %i bytes\n"</span>, element_size);

}
</code></pre>
<p>Output:</p>
<pre><code class="lang-plaintext">Size of a single element: 4 bytes
</code></pre>
<p>The <code>sizeof(grades[0])</code> calculates the size of a single element in bytes.</p>
<p>By dividing the total size of the array by the size of a single element, you can calculate the number of elements in the array, which is equal to the array's length:</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> </span>{

    <span class="hljs-keyword">int</span> grades[] = {<span class="hljs-number">50</span>, <span class="hljs-number">75</span>, <span class="hljs-number">100</span>, <span class="hljs-number">67</span>, <span class="hljs-number">90</span>};

     <span class="hljs-keyword">int</span> array_size = <span class="hljs-keyword">sizeof</span>(grades);

     <span class="hljs-keyword">int</span> element_size = <span class="hljs-keyword">sizeof</span>(grades[<span class="hljs-number">0</span>]);

     <span class="hljs-comment">// calculate the length of the array</span>
     <span class="hljs-keyword">int</span> length = array_size / element_size;

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Length of the array: %i elements\n"</span>, length);

}
</code></pre>
<p>Output:</p>
<pre><code class="lang-plaintext">Length of the array: 5 elements
</code></pre>
<h3 id="heading-how-to-access-array-elements-in-c">How to Access Array Elements in C</h3>
<p>You can access each element in an array by specifying its index or its position in the array.</p>
<p>Note that in C, indexing starts at <code>0</code> instead of <code>1</code>.</p>
<p>So, the index of the first element is <code>0</code>, the index of the second element is <code>1</code>, and so on.</p>
<p>The last element in an array has an index of <code>array_size - 1</code>.</p>
<p>To access individual elements in the array, you specify the array's name followed by the element's index number inside square brackets (<code>[]</code>).</p>
<pre><code class="lang-plaintext">array_name[index];
</code></pre>
<p>Let's take a look at the following example:</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> </span>{

   <span class="hljs-keyword">int</span> grades[] = {<span class="hljs-number">50</span>, <span class="hljs-number">75</span>, <span class="hljs-number">100</span>, <span class="hljs-number">67</span>, <span class="hljs-number">90</span>};

   <span class="hljs-comment">// Access each array element using index notation</span>

   <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Element at index 0: %i\n"</span>, grades[<span class="hljs-number">0</span>]);  

   <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Element at index 1: %i\n"</span>, grades[<span class="hljs-number">1</span>]);  

   <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Element at index 2: %i\n"</span>, grades[<span class="hljs-number">2</span>]); 

   <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Element at index 3: %i\n"</span>, grades[<span class="hljs-number">3</span>]); 

   <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Element at index 4: %i\n"</span>, grades[<span class="hljs-number">4</span>]); 
}
</code></pre>
<p>Output:</p>
<pre><code class="lang-plaintext">Element at index 0: 50
Element at index 1: 75
Element at index 2: 100
Element at index 3: 67
Element at index 4: 90
</code></pre>
<p>In the example above, to access each item from the integer array <code>grades</code>, I have to specify the array's name along with the item's position in the array inside square brackets.</p>
<p>Remember that the index starts from <code>0</code>, so <code>grades[0]</code> gives you the first element, <code>grades[1]</code> gives you the second element, and so on.</p>
<p>Note that if you try to access an element with an index number that is higher than <code>array_size - 1</code>, the compiler will return a random number:</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> </span>{

    <span class="hljs-keyword">int</span> grades[] = {<span class="hljs-number">50</span>, <span class="hljs-number">75</span>, <span class="hljs-number">100</span>, <span class="hljs-number">67</span>, <span class="hljs-number">90</span>};


    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Element at index 5: %d\n"</span>, grades[<span class="hljs-number">5</span>]);  

}
</code></pre>
<p>Output:</p>
<pre><code class="lang-plaintext">Element at index 5: 220312136
</code></pre>
<h3 id="heading-how-to-modify-array-elements-in-c">How to Modify Array Elements in C</h3>
<p>Once you know how to access array elements, you can then modify them.</p>
<p>The general syntax for modifying an array element looks like this:</p>
<pre><code class="lang-plaintext">array_name[index] = new_value;
</code></pre>
<p>You can change the value of an element by assigning a new value to it using its index.</p>
<p>Let's take the <code>grades</code> array from earlier on:</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> </span>{

   <span class="hljs-keyword">int</span> grades[] = {<span class="hljs-number">50</span>, <span class="hljs-number">75</span>, <span class="hljs-number">100</span>, <span class="hljs-number">67</span>, <span class="hljs-number">90</span>};
}
</code></pre>
<p>Here is how you would change the value <code>75</code> to <code>85</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> </span>{

   <span class="hljs-keyword">int</span> grades[] = {<span class="hljs-number">50</span>, <span class="hljs-number">75</span>, <span class="hljs-number">100</span>, <span class="hljs-number">67</span>, <span class="hljs-number">90</span>};

   grades[<span class="hljs-number">1</span>] = <span class="hljs-number">85</span>; <span class="hljs-comment">// changing the value at index 1 to 85</span>

   <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Element at index 1: %i\n"</span>, grades[<span class="hljs-number">1</span>]); 
}
</code></pre>
<p>Output:</p>
<pre><code class="lang-plaintext">Element at index 1: 85
</code></pre>
<p>When modifying arrays, keep in mind that the new value must match the declared data type of the array.</p>
<h3 id="heading-how-to-loop-through-an-array-in-c">How to Loop Through an Array in C</h3>
<p>By looping through an array, you can access and perform operations on each element sequentially.</p>
<p>The <code>for</code> loop is commonly used to iterate through arrays.</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> </span>{

    <span class="hljs-keyword">int</span> grades[] = {<span class="hljs-number">50</span>, <span class="hljs-number">75</span>, <span class="hljs-number">100</span>, <span class="hljs-number">67</span>, <span class="hljs-number">90</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++) {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Element at index %i: %i\n"</span>, i, grades[i]);
    }
}
</code></pre>
<p>Output:</p>
<pre><code class="lang-plaintext">Element at index 0: 50
Element at index 1: 75
Element at index 2: 100
Element at index 3: 67
Element at index 4: 90
</code></pre>
<p>When using a <code>for</code> loop to loop through an array, you have to specify the index as the loop variable, and then use the index to access each array element.</p>
<p>The <code>%i</code> placeholders are replaced with the current index <code>i</code> and the value at that index in the grades array, respectively.</p>
<p>You can also use a <code>while</code> loop to iterate through an array:</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> </span>{

    <span class="hljs-keyword">int</span> grades[] = {<span class="hljs-number">50</span>, <span class="hljs-number">75</span>, <span class="hljs-number">100</span>, <span class="hljs-number">67</span>, <span class="hljs-number">90</span>};

    <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">5</span>) {

        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Element at index %i: %i\n"</span>, i, grades[i]);
        i++;
    }
}
</code></pre>
<p>Output:</p>
<pre><code class="lang-plaintext">Element at index 0: 50
Element at index 1: 75
Element at index 2: 100
Element at index 3: 67
Element at index 4: 90
</code></pre>
<p>When using a <code>while</code> loop to loop through an array, you will need an index variable, <code>int i = 0</code>, to keep track of the current position in the array.</p>
<p>The loop checks the condition <code>(i &lt; 5)</code> and prints the index of the grade as well as the actual grade value.</p>
<p>After each grade is shown, the variable <code>i</code> is increased by one, and the loop continues until it has shown all the grades in the list.</p>
<p>A <code>do-while</code> works in a similar way to the <code>while</code> loop, but it is useful when you want to ensure that the loop body is executed at least once before checking the condition:</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> </span>{

     <span class="hljs-keyword">int</span> grades[] = {<span class="hljs-number">50</span>, <span class="hljs-number">75</span>, <span class="hljs-number">100</span>, <span class="hljs-number">67</span>, <span class="hljs-number">90</span>};

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

    <span class="hljs-keyword">do</span> {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Element at index %i: %i\n"</span>, i, grades[i]);

        i++;
    } <span class="hljs-keyword">while</span> (i &lt; <span class="hljs-number">5</span>);
}
</code></pre>
<p>You can also use the <code>sizeof</code> operator to loop through an array.</p>
<p>This method is particularly useful to ensure your loop doesn't exceed the array's length:</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> </span>{

    <span class="hljs-keyword">int</span> grades[] = {<span class="hljs-number">50</span>, <span class="hljs-number">75</span>, <span class="hljs-number">100</span>, <span class="hljs-number">67</span>, <span class="hljs-number">90</span>};

    <span class="hljs-keyword">int</span> length = <span class="hljs-keyword">sizeof</span>(grades) / <span class="hljs-keyword">sizeof</span>(grades[<span class="hljs-number">0</span>]);

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; length; i++) {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Element at index %i: %i\n"</span>, i, grades[i]);
    }

}
</code></pre>
<p>The line <code>int length = sizeof(grades) / sizeof(grades[0]);</code> calculates the length of the <code>grades</code> array.</p>
<p>The length is calculated by dividing the total size (in bytes) of the array by the size of a single element <code>grades[0]</code>. The result is stored in the <code>length</code> variable.</p>
<p>The loop then iterates through the array using this <code>length</code> value.</p>
<p>For each iteration, it prints the index <code>i</code> and the value of the grade at that index <code>grades[i]</code>.</p>
<h2 id="heading-chapter-7-strings">Chapter 7: Strings</h2>
<p>In the previous chapter, you learned the basics of arrays in C.</p>
<p>Now, it's time to learn about strings – a special kind of array.</p>
<p>Strings are everywhere in programming. They are used to represent names, messages, passwords, and more.</p>
<p>In this chapter, you will learn about strings in C and how they are stored as arrays of characters.</p>
<p>You'll also learn the fundamentals of string manipulation.</p>
<p>Specifically, you will learn how to find a string's length and how to copy, concatenate, and compare strings in C.</p>
<h3 id="heading-what-are-strings-in-c">What Are Strings in C?</h3>
<p>A string is a sequence of characters, like letters, numbers, or symbols, that are used to represent text.</p>
<p>In C, strings are actually arrays of characters. And each character in the string has a specific position within the array.</p>
<p>Another unique characteristic of strings in C is that at the end of every one, there is a hidden <code>\0</code> character called the 'null terminator'.</p>
<p>This terminator lets the computer know where the string ends.</p>
<p>So, the string '<code>Hello</code>' in C is stored as '<code>Hello\0</code>' in memory.</p>
<h3 id="heading-how-to-create-strings-in-c">How to Create Strings in C</h3>
<p>One way to create a string in C is to initialize an array of characters.</p>
<p>The array will contain the characters that make up the string.</p>
<p>Here is how you would initialize an array to create the string 'Hello':</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> </span>{
  <span class="hljs-keyword">char</span> word[<span class="hljs-number">6</span>] = {<span class="hljs-string">'H'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'l'</span>, <span class="hljs-string">'l'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'\0'</span>};

}
</code></pre>
<p>Note how I specified that the array should store <code>6</code> characters despite <code>Hello</code> being only <code>5</code> characters long. This is due to the null operator.</p>
<p>Make sure to include the null terminator, <code>\0</code>, as the last character to signify the end of the string.</p>
<p>Let's look at how you would create the string 'Hello world':</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> </span>{
  <span class="hljs-keyword">char</span> phrase[<span class="hljs-number">12</span>] = {<span class="hljs-string">'H'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'l'</span>, <span class="hljs-string">'l'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">' '</span>, <span class="hljs-string">'w'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'r'</span>, <span class="hljs-string">'l'</span>, <span class="hljs-string">'d'</span>, <span class="hljs-string">'\0'</span>};
}
</code></pre>
<p>In this example, there is a space between the word 'Hello' and the word 'world'.</p>
<p>So, the array must include a blank space character.</p>
<p>To print the string, you use the <code>printf()</code> function, the <code>%s</code> format code and the name of the array:</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> </span>{
  <span class="hljs-keyword">char</span> phrase[] = {<span class="hljs-string">'H'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'l'</span>, <span class="hljs-string">'l'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">' '</span>, <span class="hljs-string">'w'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'r'</span>, <span class="hljs-string">'l'</span>, <span class="hljs-string">'d'</span>, <span class="hljs-string">'\0'</span>};

  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%s\n"</span>, phrase);

}
</code></pre>
<p>Another way to create a string in C is to use a string literal.</p>
<p>In this case, you create an array of characters and then assign the string by enclosing it in double quotes:</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> </span>{
  <span class="hljs-keyword">char</span> word[] = <span class="hljs-string">"Hello"</span>;

}
</code></pre>
<p>With string literals, the null terminator (<code>\0</code>) is implied.</p>
<p>Creating strings with string literals is easier, as you don't need to add the null terminator at the end. This method is also much more readable and requires less code.</p>
<p>However, you may want to use character arrays when you want to modify the string's content. String literals are read-only, meaning the content is fixed.</p>
<h3 id="heading-how-to-manipulate-strings-in-c">How to Manipulate Strings in C</h3>
<p>C provides functions that allow you to perform operations on strings, such as copying, concatenating, and comparing, to name a few.</p>
<p>To use these functions, you first need to include the <code>string.h</code> header file by adding the line <code>#include &lt;string.h&gt;</code> at the top of your file.</p>
<h4 id="heading-how-to-find-the-length-of-a-string-in-c">How to Find the Length of a String in C</h4>
<p>To calculate the length of a string, use the <code>strlen()</code> function:</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">&lt;string.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> </span>{
  <span class="hljs-keyword">char</span> phrase[] = <span class="hljs-string">"Hello"</span>;

  <span class="hljs-keyword">int</span> length = <span class="hljs-built_in">strlen</span>(phrase);

  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"String length: %i\n"</span>, length);

}
</code></pre>
<p>Output:</p>
<pre><code class="lang-plaintext">String length: 5
</code></pre>
<p>The <code>strlen()</code> function will return the number of characters that make up the string.</p>
<p>Note that the result does not include the null terminator, <code>\0</code>.</p>
<h4 id="heading-how-to-copy-a-string-in-c">How to Copy a String in C</h4>
<p>To copy one string into another one, you can use the <code>strcpy()</code> function.</p>
<p>You may want to copy a string in C when you need to make changes to it without modifying it. It comes in handy when you need to keep the original string's content intact.</p>
<p>The general syntax for the <code>strcpy()</code> function looks like this:</p>
<pre><code class="lang-plaintext">strcpy(destination_string, original_string);
</code></pre>
<p>The <code>strcpy()</code> function copies <code>original_string</code> into <code>destination_string</code>, including the null terminator (<code>'\0'</code>).</p>
<p>One thing to note here is that you need to make sure the destination array has enough space for the original string:</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">&lt;string.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> </span>{

    <span class="hljs-keyword">char</span> original[] = <span class="hljs-string">"Hello"</span>;

    <span class="hljs-keyword">char</span> destination[<span class="hljs-number">20</span>]; <span class="hljs-comment">// Make sure this array is big enough</span>

    <span class="hljs-built_in">strcpy</span>(destination, original);

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Copied string: %s\n"</span>, destination);
}
</code></pre>
<p>Output:</p>
<pre><code class="lang-plaintext">Copied string: Hello
</code></pre>
<p>The <code>strcpy()</code> function copies the original string into an empty array and returns the copied string, which also includes the null terminator character (<code>'\0'</code>).</p>
<h4 id="heading-how-to-concatenate-strings-in-c">How to Concatenate Strings in C</h4>
<p>You can concatenate (add) two strings together by using the <code>strcat()</code> function.</p>
<p>The general syntax for the <code>strcat()</code> function looks something like the following:</p>
<pre><code class="lang-plaintext">strcat(destination_string, original_string);
</code></pre>
<p>The <code>strcat()</code> function takes the <code>original</code> string and adds it to the end of <code>destination</code> string.</p>
<p>Make sure that the <code>destination_string</code> has enough memory for the <code>original_string</code>.</p>
<p>Something to note here is that <code>strcat()</code> does not create a new string.</p>
<p>Instead, it modifies the original <code>destination_string</code>, by including the <code>original_string</code> at the end.</p>
<p>Let's see an example of how <code>strcat()</code> works:</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">&lt;string.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> greeting[<span class="hljs-number">50</span>] = <span class="hljs-string">"Hello, "</span>;

  <span class="hljs-keyword">char</span> name[] = <span class="hljs-string">"Dionysia"</span>;

  <span class="hljs-built_in">strcat</span>(greeting, name);

  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Message: %s\n"</span>, greeting);

}
</code></pre>
<p>Output:</p>
<pre><code class="lang-plaintext">Message: Hello, Dionysia
</code></pre>
<h4 id="heading-how-to-compare-strings-in-c">How to Compare Strings in C</h4>
<p>To compare two strings for equality, you can use the <code>strcmp()</code> function.</p>
<p>The general syntax for the <code>strcmp()</code> function looks like this:</p>
<pre><code class="lang-plaintext">strcmp(string1, string2);
</code></pre>
<p>The <code>strcmp()</code> function compares <code>string1</code> with <code>string2</code> and returns an integer.</p>
<p>If the return value of <code>strcmp()</code> is <code>0</code>, then it means the two strings are the same:</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">&lt;string.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> </span>{

  <span class="hljs-keyword">char</span> word1[] = <span class="hljs-string">"apples"</span>;
  <span class="hljs-keyword">char</span> word2[] = <span class="hljs-string">"apples"</span>;

  <span class="hljs-keyword">int</span> result = <span class="hljs-built_in">strcmp</span>(word1, word2);

  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Result: %i\n"</span>, result); <span class="hljs-comment">// Result: 0</span>

}
</code></pre>
<p>If the return value of <code>strcmp()</code> is less than <code>0</code>, then it means the first word comes before the second:</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">&lt;string.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> </span>{

  <span class="hljs-keyword">char</span> word1[] = <span class="hljs-string">"apples"</span>;
  <span class="hljs-keyword">char</span> word2[] = <span class="hljs-string">"bananas"</span>;

  <span class="hljs-keyword">int</span> result = <span class="hljs-built_in">strcmp</span>(word1, word2);

  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Result: %i\n"</span>, result); <span class="hljs-comment">// Result: -1</span>

}
</code></pre>
<p>And if the return value of <code>strcmp()</code> is greater than <code>0</code>, then it means the first word comes after the second one:</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">&lt;string.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> </span>{

  <span class="hljs-keyword">char</span> word1[] = <span class="hljs-string">"bananas"</span>;
  <span class="hljs-keyword">char</span> word2[] = <span class="hljs-string">"apples"</span>;

  <span class="hljs-keyword">int</span> result = <span class="hljs-built_in">strcmp</span>(word1, word2);

  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Result: %i\n"</span>, result); <span class="hljs-comment">// Result: 1</span>

}
</code></pre>
<h2 id="heading-further-learning-advanced-c-topics">Further learning: Advanced C Topics</h2>
<p>While this handbook has covered a wide range of topics, there is still so much to learn, as programming is so vast.</p>
<p>Once you have built a solid foundation with the basics of C programming, you may want to explore more advanced concepts.</p>
<p>You may want to move on to learning about functions, for example. They allow you to write instructions for a specific task and reuse that code throughout your program.</p>
<p>You may also want to learn about pointers. Pointers in C are like arrows that show you where a specific piece of information is stored in the computer's memory.</p>
<p>Then, you may want to move on to learning about structures. They're like custom data containers that allow you to group different types of information under one name.</p>
<p>Lastly, you may want to learn how to work with files. Working with files in C allows you to read from and write to files. This is useful for tasks like saving user data, reading configuration settings, or sharing data between different programs.</p>
<p>These suggestions are not a definitive guide – just a few ideas for you to continue your C programming learning journey.</p>
<p>If you are interested in learning more, you can check out the following freeCodeCamp resources:</p>
<ul>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=KJgsSFOSQv0&amp;t=12372s">C Programming Tutorial for Beginners</a></p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/learn-c-programming-classic-book-dr-chuck/">Learn C Programming Using the Classic Book by Kernighan and Ritchie</a></p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/finally-understand-pointers-in-c/">Unlock the Mysteries of Pointers in C</a></p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This marks the end of this introduction to the C programming language.</p>
<p>Thank you so much for sticking with it and making it until the end.</p>
<p>You learned how to work with variables, various data types, and operators.</p>
<p>You also learned how to write conditional statements and loops. And you learned the basics of working with arrays and strings.</p>
<p>Hopefully, you have gained a good understanding of some of the fundamentals of C programming, got some inspiration on what to learn next, and are excited to continue your programming journey.</p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Functions and Scope – a Beginner's Guide ]]>
                </title>
                <description>
                    <![CDATA[ Welcome to the exciting world of JavaScript Functions and Scope. Have you ever wondered how programs remember things and do tasks over and over again? Well, that's where functions and scope come into play. Whether you're a curious beginner or someone... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-functions-and-scope/</link>
                <guid isPermaLink="false">66d45e06230dff01669057bd</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Casmir Onyekani ]]>
                </dc:creator>
                <pubDate>Mon, 28 Aug 2023 14:55:54 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/08/learn-javascript-functions-and-scope-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Welcome to the exciting world of JavaScript Functions and Scope.</p>
<p>Have you ever wondered how programs remember things and do tasks over and over again? Well, that's where functions and scope come into play.</p>
<p>Whether you're a curious beginner or someone looking to strengthen your coding skills, get ready to unlock the secrets of functions and scope.</p>
<p>By the end of this tutorial, you'll be equipped with the knowledge to create more organized, efficient, and dynamic code.</p>
<p>If you're new to JavaScript, I suggest reading my guide to <a target="_blank" href="https://casblog.hashnode.dev/javascript-basics-a-beginners-guide-to-syntax-variables-operators-control-flow-and-loops">JavaScript Basics</a> before diving into this one.</p>
<p>Now, let's get into the fun stuff! 🚀</p>
<h2 id="heading-table-of-contents">Table of Contents:</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-introduction-to-javascript-functions-and-scope">Introduction to JavaScript Functions and Scope</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-declare-and-and-define-functions">How to Declare and and Define Functions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-function-parameters-and-arguments">Function Parameters and Arguments</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-return-statements-and-values-in-functions">Return Statements and Values in Functions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-are-anonymous-functions">What are Anonymous Functions?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-are-function-expressions">What are Function Expressions?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-arrow-functions-and-their-impact-on-this">Arrow Functions and Their Impact on "this"</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-does-function-and-variable-hoisting-work">How Does Function and Variable Hoisting Work?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-an-iife-immediately-invoked-function-expression">What is an IIFE (Immediately Invoked Function Expression)?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-default-parameters-in-a-javascript-function">How to Use Default Parameters in a JavaScript Function</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-rest-parameters-and-the-spread-operator-in-javascript-functions">How to Use Rest Parameters and the Spread Operator in JavaScript Functions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-destructure-function-parameters">How to Destructure Function Parameters</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-are-javascript-recursive-functions">What are JavaScript Recursive Functions?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-function-scope-and-closures-in-javascript">Function Scope and Closures in JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-are-lexical-scope-and-closures">What are Lexical Scope and Closures?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-execution-context-and-the-call-stack">Execution Context and the Call Stack</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-debugging-and-troubleshooting-in-javascript">Debugging and Troubleshooting in JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ol>
<h2 id="heading-introduction-to-javascript-functions-and-scope">Introduction to JavaScript Functions and Scope</h2>
<p>Functions let you group lines of code together and give them a name. They're like special tools that help you organize your code and perform specific actions whenever you need them.</p>
<p>Instead of writing the same code over and over, you can use functions to make your life easier. Consider functions as mini-programs that you can use and reuse to make your code more organized and efficient.</p>
<p>Scope is another fascinating concept that affects how your code works. It's like a set of rules that determine where your variables are allowed to hang out. Sometimes they're free to roam anywhere, and other times they're only allowed to stay within certain boundaries.</p>
<p>Don't stress if it sounds a little fancy. I'm here to explain everything clearly with examples that make sense.</p>
<h3 id="heading-how-to-declare-and-and-define-functions">How to Declare and and Define Functions</h3>
<p>Declaring a function is like announcing its name. Defining it is like giving it a purpose, this is where you put the code that the function will execute.</p>
<p>Here's an example of a simple function:</p>
<pre><code class="lang-js"><span class="hljs-comment">// This code is a function </span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>);
}

greet(<span class="hljs-string">"Cas"</span>); <span class="hljs-comment">// Output: Hello, Cas!</span>
</code></pre>
<p>In the above example, function called <code>greet</code> takes a <code>name</code> parameter and logs a greeting message using a <a target="_blank" href="https://www.freecodecamp.org/news/a-quick-introduction-to-tagged-template-literals-2a07fd54bc1d/">template literal</a>. Then, it calls the <code>greet</code> function with the argument "Cas" and outputs "Hello, Cas!".</p>
<h3 id="heading-function-parameters-and-arguments">Function Parameters and Arguments</h3>
<p>Imagine functions as machines that take inputs (parameters) and produce outputs.</p>
<p>Parameters are like placeholders for these inputs. Arguments are the actual values you give the function.</p>
<p>Here's a code example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params">a, b</span>) </span>{  <span class="hljs-comment">//a, b are parameters</span>
  <span class="hljs-keyword">return</span> a + b;
}

<span class="hljs-keyword">const</span> result = addNumbers(<span class="hljs-number">5</span>, <span class="hljs-number">7</span>);  <span class="hljs-comment">//5,7 are arguments</span>
<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: 12</span>
</code></pre>
<h3 id="heading-return-statements-and-values-in-functions">Return Statements and Values in Functions</h3>
<p>Assume you're sending your friend on a quest. They head out, complete the task, and return with a valuable item. In the world of functions, this "item" is what we call the return value. They're not just doing tasks – they deliver gifts! 🎉</p>
<p>It's the answer, the result, the prize that your function hands over once it's done with its mission.</p>
<p>Let's break it down with an example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">multiply</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-keyword">const</span> result = a * b;
  <span class="hljs-keyword">return</span> result;  <span class="hljs-comment">// The function gives back the 'result' as a gift</span>
}

<span class="hljs-keyword">const</span> product = multiply(<span class="hljs-number">3</span>, <span class="hljs-number">5</span>);  <span class="hljs-comment">// The function is called, and the return value is captured</span>
<span class="hljs-built_in">console</span>.log(product);  <span class="hljs-comment">// Output: 15</span>
</code></pre>
<p>In the above example, the <code>multiply</code> function does its math, packages up the answer (the product of 3 and 5), and hands it over using the <code>return</code> statement.</p>
<p>Whether it's calculations, data processing, or generating valuable information,<br>return values allow your functions to contribute more to your overall code. So, get ready to embrace this concept as you continue your journey through JavaScript functions.</p>
<h3 id="heading-what-are-anonymous-functions">What are Anonymous Functions?</h3>
<p>Sometimes you don't need a named function. An anonymous function doesn't have a name – instead, it's defined directly where it's assigned. Anonymous functions are often used as callbacks or one-time-use functions.</p>
<p>Here's a code example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> multiply = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">x, y</span>) </span>{
  <span class="hljs-keyword">return</span> x * y;
}
</code></pre>
<p>This code defines an anonymous function assigned to the variable <code>multiply</code>, which takes two parameters <code>x</code> and <code>y</code> and returns their product when the function is called.</p>
<h3 id="heading-what-are-function-expressions">What are Function Expressions?</h3>
<p>These come to play when assigning functions to variables, pass functions as arguments to other functions, or return functions from other functions. It's an alternative to the more common function declaration.</p>
<p>Here's a code example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> add = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-keyword">return</span> a + b;
};

<span class="hljs-keyword">const</span> result = add(<span class="hljs-number">5</span>, <span class="hljs-number">3</span>);  <span class="hljs-comment">// Call the function</span>
<span class="hljs-built_in">console</span>.log(result);  <span class="hljs-comment">// Output: 8</span>
</code></pre>
<p>In this example, a function expression named <code>add</code> was defined and assigned to the variable <code>add</code>. The function takes two parameters <code>a</code> and <code>b</code>, and it returns the sum of these two numbers.</p>
<h3 id="heading-arrow-functions-and-their-impact-on-this">Arrow Functions and Their Impact on "this"</h3>
<p>This function behaves differently when it comes to the <code>this</code> keyword. Unlike regular functions, arrow functions don't create their own <code>this</code> context. Instead, they inherit the <code>this</code> value from their surrounding code.</p>
<p>Here's a code example showing that:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">regularFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);  <span class="hljs-comment">// Refers to the caller</span>
}

<span class="hljs-keyword">const</span> arrowFunction = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);  <span class="hljs-comment">// Inherits from where it's defined</span>
};

<span class="hljs-keyword">const</span> obj = {
  <span class="hljs-attr">regular</span>: regularFunction,
  <span class="hljs-attr">arrow</span>: arrowFunction
};

obj.regular();  <span class="hljs-comment">// 'this' refers to 'obj'</span>
obj.arrow();    <span class="hljs-comment">// 'this' still refers to 'obj', despite being in an arrow function</span>
</code></pre>
<p>This code demonstrates the difference between regular functions and arrow functions regarding the usage of the <code>this</code> keyword. Arrow functions inherit the <code>this</code> context from where they are defined, while regular functions refer to the caller.</p>
<p>Another benefit of arrow functions is that they bring concise elegance to JavaScript. They're like a shorthand way of writing functions, perfect for simple tasks. When combined with default parameter values, they make your code even more streamlined.</p>
<p>Here's a code example of an arrow function with a default parameter:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> greet = <span class="hljs-function">(<span class="hljs-params">name = <span class="hljs-string">"friend"</span></span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>);
};

greet();        <span class="hljs-comment">// Output: Hello, friend!</span>
greet(<span class="hljs-string">"Cas"</span>); <span class="hljs-comment">// Output: Hello, Cas!</span>
</code></pre>
<p>In this example, the <code>name</code> parameter has a default value of "friend".</p>
<p>Arrow functions are especially handy when you want a quick way to define a function with default parameters.</p>
<h3 id="heading-how-does-function-and-variable-hoisting-work">How Does Function and Variable Hoisting Work?</h3>
<p>Hoisting is like setting up the stage before the play begins.</p>
<p>In JavaScript, function declarations are hoisted (raised) to the top of their containing scope. This means you can call a function before it's defined in your code.</p>
<p>Here's a code example:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Function declaration (can be called anywhere)</span>
sayHello(); <span class="hljs-comment">// This code works</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHello</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello!"</span>);
}
</code></pre>
<p>The above code snippet works due to hoisting.</p>
<p>However, hoisting doesn't apply to function expressions:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Function expreesion (called before defined)</span>
sayHi();  <span class="hljs-comment">// Error</span>

<span class="hljs-keyword">const</span> sayHi = <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">"Hi!"</span>);
};


<span class="hljs-comment">// Function expression (should be defined before calling)</span>
<span class="hljs-keyword">const</span> sayHello = <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">"Hello!"</span>);
};

sayHello(); <span class="hljs-comment">// This works</span>
</code></pre>
<p>The <code>sayHi</code> function throws an error. Why? Because it's called before defined. This means that you must define a function expression before you attempt to call it.</p>
<p>Hoisting with the <code>let</code> and <code>const</code> Keywords has a slightly different behavior. They experience a <em>temporal dead zone</em>, just like the dancers waiting for their turn backstage.</p>
<p>The temporal dead zone in JavaScript refers to the period between the creation of a variable using the <code>let</code> or <code>const</code> keywords and the point where the variable is actually declared in the code.</p>
<p>During this period, if you try to access the variable, you'll get a reference error. This behavior is a result of how JavaScript's variable hoisting works with these block-scoped declarations.</p>
<p>Here's a code example:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(myName);  <span class="hljs-comment">// Throws an error - myName is not defined</span>
<span class="hljs-keyword">let</span> myName = <span class="hljs-string">"Cas"</span>;
</code></pre>
<p>In the above code, <code>myName</code> is hoisted, but trying to access it before the actual<br>declaration results in an error due to the temporal dead zone.</p>
<p>Note: While function hoisting can be helpful, it's a good practice to define your functions before using them to make your code more readable.</p>
<h3 id="heading-what-is-an-iife-immediately-invoked-function-expression">What is an IIFE (Immediately Invoked Function Expression)?</h3>
<p>Ever wanted to execute a function right after defining it? That's where <strong>IIFEs</strong> come into play. They're like the express lane of JavaScript.</p>
<p>All you need to do is to define the function, wrap it in parentheses, and then add another pair of parentheses to call it immediately. You can personalize your <strong>IIFE</strong> by adding a parameter.</p>
<p>Here's a code example:</p>
<pre><code class="lang-js">(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>);
})(<span class="hljs-string">"Cas"</span>);
</code></pre>
<p>In this example, the <strong>IIFE</strong> takes the name "Cas" as a parameter and dances with it right away.</p>
<h3 id="heading-how-to-use-default-parameters-in-a-javascript-function">How to Use Default Parameters in a JavaScript Function</h3>
<p>In the world of JavaScript functions, flexibility is key. Sometimes, you want your function to handle missing or undefined values without causing errors. That's where default parameter values come to the rescue.</p>
<p>Here's a code example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name = <span class="hljs-string">"Guest"</span></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>);
}

greet();          <span class="hljs-comment">// Output: Hello, Guest!</span>
greet(<span class="hljs-string">"Cas"</span>);   <span class="hljs-comment">// Output: Hello, Cas!</span>
</code></pre>
<p>In the <code>greet</code> function, the <code>name</code> parameter has a default value of "Guest". If you call the function without providing an argument for <code>name</code>, it will use the default value. If you provide an argument, it will override the default value</p>
<h3 id="heading-how-to-use-rest-parameters-and-the-spread-operator-in-javascript-functions">How to Use Rest Parameters and the Spread Operator in JavaScript Functions</h3>
<p>The <a target="_blank" href="https://www.freecodecamp.org/news/javascript-rest-vs-spread-operators/">Rest Parameter and the Spread Operator</a> are two related concepts in JavaScript that deal with handling and manipulating function arguments and arrays.</p>
<p>Imagine you're hosting a party, and you want to gather all the dishes your guests are bringing. The rest parameter is like a magical dish collector that grabs all the items your guests bring and puts them into an array for you to enjoy.</p>
<p>Here's a code example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">partyPlanner</span>(<span class="hljs-params">mainDish, ...sideDishes</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Main dish: <span class="hljs-subst">${mainDish}</span>`</span>);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Side dishes: <span class="hljs-subst">${sideDishes.join(<span class="hljs-string">', '</span>)}</span>`</span>);
}

partyPlanner( <span class="hljs-string">"Jollof rice"</span>, <span class="hljs-string">"Fufu"</span>, <span class="hljs-string">"Pizza"</span>, <span class="hljs-string">"Salad"</span>, <span class="hljs-string">"Kpomo"</span>, <span class="hljs-string">"Fries"</span>);
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// Main dish: Jollof rice</span>
<span class="hljs-comment">// Side dishes: Fufu, Pizza, Salad, Kpomo, Fries</span>
</code></pre>
<p>In this example, the <code>...sideDishes</code> parameter collects all the extra values and packs them into an array, making it easy to work with varying numbers of inputs.</p>
<h3 id="heading-how-to-destructure-function-parameters">How to Destructure Function Parameters</h3>
<p>Let's say you receive a gift box with various items, and you want to unpack them and select the items you need immediately.</p>
<p>Destructuring helps you unpack and use the parts you need from complex data, like objects or arrays.</p>
<p>Here's a code example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printPersonInfo</span>(<span class="hljs-params">{ firstName, lastName, age }</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`First Name: <span class="hljs-subst">${firstName}</span>`</span>);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Last Name: <span class="hljs-subst">${lastName}</span>`</span>);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Age: <span class="hljs-subst">${age}</span>`</span>);
}

<span class="hljs-keyword">const</span> person = {
  <span class="hljs-attr">firstName</span>: <span class="hljs-string">'Cas'</span>,
  <span class="hljs-attr">lastName</span>: <span class="hljs-string">'Nuel'</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">30</span>
};

printPersonInfo(person);
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// First Name: Cas</span>
<span class="hljs-comment">// Last Name: Nuel</span>
<span class="hljs-comment">// Age: 30</span>
</code></pre>
<p>In this example, the <code>printPersonInfo</code> function takes an object parameter. Instead of accessing the object properties using <code>person.firstName</code>, <code>person.lastName</code>, <code>person.Age</code>, we use destructuring within the function parameter list to directly extract the properties. This makes the code cleaner and more readable. When you call <code>printPersonInfo(person)</code>, the function will destructure the <code>person</code> object and print out its properties.</p>
<h3 id="heading-what-are-javascript-recursive-functions">What are JavaScript Recursive Functions?</h3>
<p>This is where a function calls itself to solve a problem by breaking it down into smaller, similar sub-problems.</p>
<p><a target="_blank" href="https://www.freecodecamp.org/news/recursion-in-javascript/">Recursion involves two main components</a>: a <strong>base condition</strong> that defines when the recursion should stop, and a <strong>recursive case</strong> where the function calls itself with modified parameters.</p>
<p>Here's a code example of a recursive function that calculates the factorial of a number:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">factorial</span>(<span class="hljs-params">n</span>) </span>{
  <span class="hljs-comment">// Base condition: factorial of 0 or 1 is 1</span>
  <span class="hljs-keyword">if</span> (n === <span class="hljs-number">0</span> || n === <span class="hljs-number">1</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
  }

  <span class="hljs-comment">// Recursive case: call the function with a smaller sub-problem</span>
  <span class="hljs-keyword">return</span> n * factorial(n - <span class="hljs-number">1</span>);
}

<span class="hljs-keyword">const</span> num = <span class="hljs-number">5</span>;
<span class="hljs-keyword">const</span> result = factorial(num);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Factorial of <span class="hljs-subst">${num}</span> is <span class="hljs-subst">${result}</span>`</span>);
</code></pre>
<p>In this example, the <code>factorial</code> function calculates the factorial of a number <code>n</code>. The base condition checks if <code>n</code> is <strong>0</strong> or <strong>1</strong>. If it is, the function immediately returns <strong>1</strong>, as the factorial of <strong>0</strong> or <strong>1</strong> is <strong>1</strong>. The recursive case multiplies <code>n</code> with the result of calling the <code>factorial</code> function with <code>n - 1</code>.</p>
<p>This creates a chain of recursive calls, each reducing the problem by one and stops when it reaches the base condition. The calculated values are returned up the chain.</p>
<p>For example, when calling <code>factorial(5)</code>:</p>
<ul>
<li><p><code>factorial(5)</code> returns <code>5 * factorial(4)</code></p>
</li>
<li><p><code>factorial(4)</code> returns <code>4 * factorial(3)</code></p>
</li>
<li><p><code>factorial(3)</code> returns <code>3 * factorial(2)</code></p>
</li>
<li><p><code>factorial(2)</code> returns <code>2 * factorial(1)</code></p>
</li>
<li><p><code>factorial(1)</code> returns <code>1</code></p>
</li>
</ul>
<p>These values are then multiplied together, and the final result, which is <strong>120</strong>, is obtained.</p>
<p>Recursion is a powerful technique, but it's essential to have a well-defined base condition to avoid infinite loops. Each recursive call should move towards the base case, ensuring that the problem gets smaller with each iteration.</p>
<h3 id="heading-function-scope-and-closures-in-javascript">Function Scope and Closures in JavaScript</h3>
<p>With scope and closures you can organize your code, create private data, and build powerful functionalities.</p>
<p>It's like having little compartments in your coding toolbox that help you keep things tidy and efficient.</p>
<h4 id="heading-global-vs-local-scope">Global vs. Local Scope</h4>
<p>You can think of global scope as the entire neighborhood where all your houses (variables) live. Variables declared here are accessible from anywhere in your code.</p>
<p>Here's a code example:</p>
<pre><code class="lang-js">
<span class="hljs-keyword">const</span> globalVariable = <span class="hljs-string">"I'm global!"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">globalScopeExample</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(globalVariable);  <span class="hljs-comment">// Accessing the global variable</span>
}

globalScopeExample();  <span class="hljs-comment">// Output: I'm global!</span>
</code></pre>
<p>This code defines a global variable <code>globalVariable</code> with a string value. Then, there's a function <code>globalScopeExample</code> that logs the value of <code>globalVariable</code>. The function is called, resulting in the output of the global variable's value.</p>
<p>On the other hand, local scope is like rooms within your houses. Variables declared inside functions or code blocks are local and can only be accessed within that function or block.</p>
<p>Here's a code example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">localScopeExample</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> localVariable = <span class="hljs-string">"I'm local!"</span>;
  <span class="hljs-built_in">console</span>.log(localVariable);  <span class="hljs-comment">// Accessing the local variable</span>
}

localScopeExample();  <span class="hljs-comment">// Output: I'm local!</span>
<span class="hljs-comment">// console.log(localVariable);  // This would result in an error</span>
</code></pre>
<p>This code defines a function <code>localScopeExample</code> that creates a variable <code>localVariable</code> inside the function and then prints its value. When the function is called, it outputs the value of the <code>localVariable</code>. Attempting to access <code>localVariable</code> outside the function will result in an error</p>
<h3 id="heading-what-are-lexical-scope-and-closures">What are Lexical Scope and Closures?</h3>
<p>Lexical scope is a bit like those Russian nesting dolls. Each doll can access the dolls inside it, but not the other way around.</p>
<p>Similarly, in programming, it means an inner function can access variables from its outer function, but not vice versa.</p>
<p>Here's a code example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">outer</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> outerVar = <span class="hljs-string">"I'm from outer function!"</span>;

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">inner</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(outerVar);  <span class="hljs-comment">// Accessing the outer variable</span>
  }

  inner();
}

outer();  <span class="hljs-comment">// Output: I'm from outer function!</span>
</code></pre>
<p>This code defines an outer function <code>outer</code> which contains a variable <code>outerVar</code>. Inside <code>outer</code>, there's an inner function <code>inner</code> that logs the value of <code>outerVar</code>. When <code>outer</code> is called, it also calls <code>inner</code>, resulting in the output "I'm from outer function!".</p>
<h4 id="heading-how-closures-work-and-why-theyre-important">How Closures Work and Why They're Important</h4>
<p>Closures are like time capsules that hold onto variables even after their functions have finished running. They're a combination of a function and the environment in which it was created.</p>
<p>Here's a code example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">rememberMe</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> secret = <span class="hljs-string">"I'm a secret!"</span>;
  <span class="hljs-keyword">return</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(secret);  <span class="hljs-comment">// This inner function remembers the 'secret'</span>
  };
}

<span class="hljs-keyword">const</span> myClosure = rememberMe();
myClosure();  <span class="hljs-comment">// Output: I'm a secret!</span>
</code></pre>
<p>The code defines a function <code>rememberMe()</code> that creates and returns another function. This returned function, known as a closure, has access to the <code>secret</code> variable from its parent function's scope. When the <code>myClosure</code> function is invoked, it logs the value of the <code>secret</code> variable</p>
<p>Closures are great for creating private data or functions that only a specific part of your code can access.</p>
<p>Let's take another practical example of a closure:</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"></span>) </span>{
  <span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> ++count;
  };
}

<span class="hljs-keyword">const</span> increment = counter();
<span class="hljs-built_in">console</span>.log(increment());  <span class="hljs-comment">// Output: 1</span>
<span class="hljs-built_in">console</span>.log(increment());  <span class="hljs-comment">// Output: 2</span>
</code></pre>
<p>The code creates a <code>counter</code> function that generates an incrementing counter each time it's called, demonstrating closure usage.</p>
<h3 id="heading-execution-context-and-the-call-stack">Execution Context and the Call Stack</h3>
<p>Every time a function is called, JavaScript creates an execution context. A sort of environment for that function to run in. It keeps track of variables, references, and where the function was called from.</p>
<p>Think of it as a backstage area where the function's code runs. All the variables, functions, and parameters are stored here.</p>
<p>Here's a code example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">first</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello from first!"</span>);
  second();  <span class="hljs-comment">// Calling another function</span>
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">second</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello from second!"</span>);
}

first();  <span class="hljs-comment">// Output: Hello from first! Hello from second!</span>
</code></pre>
<p>In the above example, function <code>first</code> calls function <code>second</code>, creating a new execution context for <code>second</code>.</p>
<p>The Call Stack is like a to-do list of functions waiting to be executed. When a function is called, it's added to the top of the stack. When it's done, it's removed.<br>This stack of contexts is what keeps track of where your code is.</p>
<h3 id="heading-debugging-and-troubleshooting-in-javascript">Debugging and Troubleshooting in JavaScript</h3>
<p>While sailing the seas of JavaScript, you're bound to encounter tricky issues<br>that can make your code behave unexpectedly.</p>
<p>But fret not, for I'm here to equip you with the tools, techniques, and strategies needed to steer your ship through these stormy waters.</p>
<p>Let's look at some common bugs and errors.</p>
<h4 id="heading-accidental-global-variables">Accidental Global Variables</h4>
<p>Look at this code example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">oops</span>(<span class="hljs-params"></span>) </span>{
  myVariable = <span class="hljs-string">"I'm global!"</span>;  <span class="hljs-comment">// Oops, forgot 'var', 'let', or 'const'!</span>
}

oops();
<span class="hljs-built_in">console</span>.log(myVariable);  <span class="hljs-comment">// Output: I'm global!</span>
</code></pre>
<p>In this example, <code>myVariable</code> becomes global because you didn't use <code>var</code>, <code>let</code>, or <code>const</code> to declare it.</p>
<h4 id="heading-shadowing">Shadowing</h4>
<p>Look at this code example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> x = <span class="hljs-number">10</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">shadowExample</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> x = <span class="hljs-number">5</span>;  <span class="hljs-comment">// This 'x' is different from the outer 'x'</span>
  <span class="hljs-built_in">console</span>.log(x);  <span class="hljs-comment">// Output: 5</span>
}

shadowExample();
<span class="hljs-built_in">console</span>.log(x);  <span class="hljs-comment">// Output: 10</span>
</code></pre>
<p>In this example, the inner x shadows the outer one, leading to different values within and outside the function.</p>
<h4 id="heading-debugging-tools-and-techniques">Debugging Tools and Techniques</h4>
<p>Modern browsers like Chrome come equipped with developer tools that let you set breakpoints, inspect variables, and step through your code line by line.</p>
<p><strong>Setting breakpoints</strong> involves using the browser's developer tools to pause your code at specific points (breakpoints) and examine the values of variables. This helps you pinpoint where things are going awry.</p>
<p><strong>Console logging</strong> involves inserting <code>console.log()</code> statements to print variable values or messages to the console. This can help you trace the flow of your code and identify unexpected behavior.</p>
<h4 id="heading-strategies-for-identifying-and-resolving-errors">Strategies for Identifying and Resolving Errors</h4>
<p>Dealing with scope issues requires a methodical approach. Here's your compass:</p>
<ul>
<li><p>Start Local: When debugging, start by checking the scope of variables.<br>  Are they in the right place? Are they shadowing other variables?</p>
</li>
<li><p>Step by Step: Use a debugger like browsers Dev tools, Visual Studio Code debugger, Node.js inspector to go through your code step by step. This helps you catch variables at different stages and spot any unexpected changes.</p>
</li>
<li><p>Isolate the Issue: If a function isn't behaving as expected, isolate it and test it separately. This can help you focus on the problematic part.</p>
</li>
<li><p>Review Your Code: Take a fresh look at your code, a second glance may reveal something you missed the first time.</p>
</li>
<li><p>Ask for Help: Don't be afraid to ask for help. Sometimes another set of eyes can spot what you've been missing.</p>
</li>
</ul>
<p>Navigating scope issues might feel like untangling a knot, but with practice, debugging becomes a skill that empowers you to conquer even the trickiest bugs.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, we've explored how functions can act as powerful tools and allow you to create organized and reusable code.</p>
<p>You also learned about scope, which is like a set of rules and dictates where variables can roam freely or stay within boundaries.</p>
<p>From basic function declarations to more advanced concepts like closures and arrow functions, you've also delved into how JavaScript functions work and the nuances of scope.</p>
<p>You've learned about execution context, the call stack, the quirks of hoisting, the use of default parameters, rest parameters, destructuring, and recursive function.</p>
<p>We also discussed debugging, a crucial skill, which equips you to navigate through errors, accidental global variables, and shadowing.</p>
<p>Armed with these insights and strategies, you're now well-prepared to craft more efficient and organized JavaScript code. You should be ready to conquer challenges and create dynamic applications.</p>
<p>To be more equipped on functions, I recommend you watch this <a target="_blank" href="https://www.youtube.com/watch?v=j1laALb8OVM">Mastering JavaScript Functions for Beginners</a> YouTube video.</p>
<p>If you found this guide helpful and enjoyable, please give it a like. For more insightful tutorials, follow me on <a target="_blank" href="https://twitter.com/casweb_dev">X</a> for updates 🙏.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Python Code Example Handbook ]]>
                </title>
                <description>
                    <![CDATA[ Very few programming languages are as universally loved as Python. The brainchild of Dutch programmer Guido van Rossum, Python is easy to learn, powerful, and an utter joy to work with. Thanks to its popularity, video and written resources about Pyth... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-python-code-example-handbook/</link>
                <guid isPermaLink="false">66b0ab5bb30dd4d00547bc18</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ example ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Farhan Hasin Chowdhury ]]>
                </dc:creator>
                <pubDate>Tue, 22 Aug 2023 21:54:38 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/08/Learn-Python-with-Code-Examples-Handbook-Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Very few programming languages are as universally loved as Python. The brainchild of Dutch programmer Guido van Rossum, Python is easy to learn, powerful, and an utter joy to work with.</p>
<p>Thanks to its popularity, video and written resources about Python are plentiful. This handbook, however, tries to be a bit different by not being a definitive guide to the language.</p>
<p>Instead you'll learn about all the topics that I consider to be the language fundamentals with a lot of code examples.</p>
<p>I haven't discussed object-oriented programming in this handbook because I believe it to be a very broad subject deserving of its own separate handbook.</p>
<p>Near the end, I've also listed out some learning resources to further your knowledge of Python and programming in general.</p>
<p>Without any further ado, let's jump in!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></li>
<li><a class="post-section-overview" href="#heading-how-to-setup-python-on-your-computer">How to Setup Python on Your Computer</a></li>
<li><a class="post-section-overview" href="#heading-how-to-install-a-python-ide-on-your-computer">How to Install a Python IDE on Your Computer</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-new-project-on-pycharm">How to Create a New Project on PyCharm</a></li>
<li><a class="post-section-overview" href="#heading-how-to-write-the-hello-world-program-in-python">How to Write the Hello World Program in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-initialize-and-publish-a-git-repository-from-pycharm">How to Initialize and Publish a Git Repository From PyCharm</a></li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-variables-and-different-types-of-data-in-python">How to Work With Variables and Different Types of Data in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-simple-numbers-in-python">How to Work With Simple Numbers in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-take-inputs-from-users-in-python">How to Take Inputs From Users in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-strings-in-python">How to Work With Strings in Python</a></li>
<li><a class="post-section-overview" href="#heading-what-are-the-sequence-types-in-python">What Are the Sequence Types in Python?</a><ul>
<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-ranges-in-python">Ranges in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-indexing-works-in-python">How Indexing Works in Python</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-what-are-the-iterable-types-and-how-to-use-them-for-loops-in-python">What Are the Iterable Types and How to Use them for Loops in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-while-loops-in-python">How to Use While Loops in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-write-nested-loops-in-python">How to Write Nested Loops in Python</a></li>
<li><a class="post-section-overview" href="#heading-what-are-some-common-sequence-type-operations-in-python">What Are Some Common Sequence Type Operations in Python?</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-use-the-in-operator-in-python">How to Use the in Operator in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-and-operators-with-sequence-types-in-python">How to Use the + and * Operators with Sequence Types in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-len-min-and-max-functions-in-python">How to Use the len(), min(), and max() Functions in Python</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-what-are-some-string-type-operations-in-python">What Are Some String Type Operations in Python?</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-capitalize-strings-in-python">How to Capitalize Strings in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-convert-strings-to-lower-case-or-upper-case-in-python">How to Convert Strings to Lower Case or Upper Case in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-count-the-number-of-occurrences-of-a-substring-in-a-string-in-python">How to Count the Number of Occurrences of a Substring in a String in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-split-and-join-strings-in-python">How to Split and Join Strings in Python</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-write-conditional-statements-in-python">How to Write Conditional Statements in Python</a></li>
<li><a class="post-section-overview" href="#heading-what-are-relational-and-logical-operators-in-python">What are Relational and Logical Operators in Python?</a></li>
<li><a class="post-section-overview" href="#heading-what-are-assignment-operators-in-python">What Are Assignment Operators in Python?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-the-set-type-in-python">What Is the Set Type in Python?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-the-mapping-type-in-python">What Is the Mapping Type in Python?</a><ul>
<li><a class="post-section-overview" href="#heading-what-are-dictionary-view-objects-in-python">What Are Dictionary View Objects in Python?</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-write-functions-in-python">How to Write Functions in Python</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-write-anonymous-or-lambda-functions-in-python">How to Write Anonymous or Lambda Functions in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-local-nonlocal-and-global-variables-in-python">How to Work with local, nonlocal and global Variables in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-pass-a-variable-number-of-arguments-to-a-function-using-args-and-kwargs-in-python">How to Pass a Variable Number of Arguments to a Function Using <em>args and *</em>kwargs in Python</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-what-are-modules-in-python">What Are Modules in Python?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-python-documentation-efficiently">How to Use the Python Documentation Efficiently</a></li>
<li><a class="post-section-overview" href="#heading-whats-next">What's Next?</a><ul>
<li><a class="post-section-overview" href="#heading-object-oriented-programming">Object Oriented Programming</a></li>
<li><a class="post-section-overview" href="#heading-algorithms-and-data-structures">Algorithms and Data Structures</a></li>
<li><a class="post-section-overview" href="#heading-django">Django</a></li>
<li><a class="post-section-overview" href="#heading-qt">Qt</a></li>
<li><a class="post-section-overview" href="#heading-pygame">PyGame</a></li>
<li><a class="post-section-overview" href="#heading-data-science">Data Science</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-prerequisites"><strong>Prerequisites</strong></h2>
<p>You don't need to know any other programming language for this book, but knowing one may help you understand the basics of Python.</p>
<p>Other than that you'll need to be efficient enough with your choice of operating system to download and install new software, and gain administrative access if needed.</p>
<h2 id="heading-how-to-setup-python-on-your-computer">How to Setup Python on Your Computer</h2>
<p>Installing Python on your computer is a very straightforward process. In fact, if you're on a Linux system, Python should already be installed.</p>
<p>Open up your terminal window and execute the following command:</p>
<pre><code>python --version
</code></pre><p>If Python is installed on your system, you'll get an output like <code>Python 3.10.4</code> or some other minor version.</p>
<p>Although most of the modern Linux distribution use Python 3 as default, some of the older distributions may still use Python 2 by default.</p>
<p>So if the aforementioned command refers to Python 2, try out the following command:</p>
<pre><code>python3 --version
</code></pre><p>I'd also suggest that you check for updates on your Linux distribution and install any new updates for Python.</p>
<p>Although Python comes preinstalled with macOS as well, I'd suggest that you follow this article by <a target="_blank" href="https://www.freecodecamp.org/news/author/dillionmegida/">Dillion Megida</a> and install a more recent version.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.freecodecamp.org/news/how-to-install-python-3-on-mac-and-update-the-python-version-macos-homebrew-command-guide/">https://www.freecodecamp.org/news/how-to-install-python-3-on-mac-and-update-the-python-version-macos-homebrew-command-guide/</a></div>
<p>Finally, for Windows, I'd suggest you follow an article by <a target="_blank" href="https://www.freecodecamp.org/news/author/fahimbinamin/">Md. Fahim Bin Amin</a> and properly install the latest version of Python.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.freecodecamp.org/news/how-to-install-python-in-windows-operating-system/">https://www.freecodecamp.org/news/how-to-install-python-in-windows-operating-system/</a></div>
<p>As long as you have a Python 3 version installed, you're good to go.</p>
<h2 id="heading-how-to-install-a-python-ide-on-your-computer">How to Install a Python IDE on Your Computer</h2>
<p>Much of your experience as a developer will depend on what program you've chosen to write your code in. A good integrated development environment (IDE) or Code Editor can really boost your productivity.</p>
<p>These days <a target="_blank" href="https://code.visualstudio.com/">Visual Studio Code</a> has become the go to code editor for all languages and platforms. But for the sake of simplicity, we'll use <a target="_blank" href="https://www.jetbrains.com/pycharm/">PyCharm</a> in this book.</p>
<p>If you'd like to use VS Code, have written a full-length article on <a target="_blank" href="https://www.freecodecamp.org/news/how-to-configure-visual-studio-code-for-python-development/">how to configure Visual Studio Code for Python development</a>. Feel free to check that out if you do not mind configuring your editor manually.</p>
<p>The professional edition of the IDE <a target="_blank" href="https://www.jetbrains.com/pycharm/buy/">can cost you $89.00 per year</a> but there is also a free and open-source community edition. Head over to the <a target="_blank" href="https://www.jetbrains.com/pycharm/download/">PyCharm download page</a>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/download-pycharm-page.png" alt="Image" width="600" height="400" loading="lazy">
<em>Download PyCharm page</em></p>
<p>Use the black "Download" button to download the community edition. The file size should be a little larger than 350 megabytes.</p>
<p>On Windows you'll get an executable installer, on macOS you'll get an Apple disc image, and on Linux you'll get a TAR archive.</p>
<p>I won't demonstrate the installation process in this book since it's similar to installing any other software on your machine.</p>
<p>Once installed, you can start the IDE from your start menu/app launcher. On your first launch, you'll be given the chance to configure a few things. I'd suggest you keep the defaults.</p>
<p>Once the configuration wizard ends, you should see the following welcome window:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-469.png" alt="Image" width="600" height="400" loading="lazy">
<em>Welcome to PyCharm screen - with options to start a new project, open a project, or get one from your VCS</em></p>
<p>Picking one IDE or code editor instead of the other one will not affect your experience with following this handbook, so feel free to use whatever you feel comfortable with.</p>
<h2 id="heading-how-to-create-a-new-project-on-pycharm">How to Create a New Project on PyCharm</h2>
<p>If you have the welcome window open from the previous section, click on the "New Project" button.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/start-a-new-project-in-pycharm.png" alt="Image" width="600" height="400" loading="lazy">
<em>Start a new project in PyCharm</em></p>
<p>In the next step, pick a location to store your project:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-472.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In the location input box, the <code>HelloWorld</code> part is the name of the project. Then make sure you have "New environment using Virtualenv" selected. Then, make sure that the correct version of Python is selected from the "Base interpreter" dropdown.</p>
<p><a target="_blank" href="https://virtualenv.pypa.io/">Virtualenv</a> is a program that can create isolated Python environments from a given base interpreter. This is very helpful because later on when you'll work on multiple Python projects, their dependencies may conflict with each other.</p>
<p>Creating isolated environments for each project will solve that issue and it'll also keep your global Python installation free from any unnecessary package installation.</p>
<p>Since this may be your first Python project, I'd suggest you leave the "Create a main.py welcome script" option checked. Once you're happy with your choices, click the "Create" button.</p>
<p>The project creation process shouldn't take very long. Once it's done, the IDE should open the project automatically for you.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-473.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You can use the play button at the top right corner to run the code. The button is configured to run the "main.py" file by default. </p>
<p>That's why you can see "main" written by its side. You can write your custom configuration as well, but that's a topic for a later section.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-474.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You can see the output of your program at the bottom of the IDE. PyCharm comes with support for TODO comments, a built in terminal and more. You'll learn about a bunch of these features as you go forward.</p>
<h2 id="heading-how-to-write-the-hello-world-program-in-python">How to Write the Hello World Program in Python</h2>
<p>Continuing on from the last section, open up the "main.py" file and replace all the preexisting code with the following line of code:</p>
<pre><code class="lang-python">print(<span class="hljs-string">'Hello, World!'</span>)

<span class="hljs-comment"># Hello, World!</span>
</code></pre>
<p>The <code>print()</code> function prints out anything that you pass into the set of parenthesis. You don't have to name your Python file "main.py" specifically. It's just a way to let you know that this is the entry point to this program.</p>
<p>That's all you need to write the simplest executable program in Python. But there is even a better way to do it. Update the code as follows:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(<span class="hljs-string">'Hello, World!'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, World!</span>
</code></pre>
<p>As you keep working on bigger projects, you'll eventually have more than one Python file in your project and this way of writing a script can be useful.</p>
<p>To simulate a bigger project, create another Python file by right clicking on the "HelloWorld" project name and selecting "Python File" under the "New" sub menu.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Name your file something like "library" and press enter while "Python file" is highlighted in the list of file types.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>A new file with the name "library.py" will show up on your project folder. Put the following line of code inside the file:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">greet</span>():</span>
    print(<span class="hljs-string">'Hello, World!'</span>)
</code></pre>
<p>This is a very simple function that prints out "Hello, World!" on the console. You can <code>import</code> and use this function in your "main.py" file.</p>
<p>To do so, update the code for "main.py" file as follows:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> library <span class="hljs-keyword">import</span> greet


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    greet()


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, World!</span>
</code></pre>
<p>You're importing the <code>greet()</code> function from the "library.py" file and executing that inside the <code>main()</code> function.</p>
<p>Right now in your project, you have two types of Python file. You have the "main.py" file which is a script. In other words, you can run this file.</p>
<p>Then you have the "library.py" file which is a library. In other words, it houses a number of useful functions and variables that you can import inside other Python files.</p>
<p>Now imagine you have hundreds of files in your project and they more or less look the same. How would someone else find the entry point to the program?</p>
<p>The easiest way would be to perform a search for the line <code>if __name__ == '__main__'</code> on the entire project. This makes your code a lot more readable.</p>
<p>Now that I have you convinced that this is the way to go, let me explain what is actually going on here.</p>
<p>The <code>__name__</code> is a special Python variable. In case of a script, the value of this variable will be <code>__main__</code> and in case of a library, its value will be the name of that file.</p>
<p>So in the aforementioned program, the value of <code>__name__</code> inside the "main.py" file will be <code>__main__</code> and <code>library</code> inside the "library.py" file.</p>
<p>If you change the name of then "main.py" file to something else, the value will still be <code>__main__</code> because it's a script.</p>
<p>Nothing is stopping the "library.py" file from being a script, though. If you run that file instead, it'll become a script.</p>
<p>In languages like C/C++/Go/Java, you'll have a specified <code>main</code> function. That function will be the entry point to the program.</p>
<p>Since Python doesn't have anything like that, the usage of the <code>if __name__ == '__main__'</code> expression enforces a sense of a specified entry point to your program.</p>
<p>It tells the programmer and the IDE that this script is for execution (not for importing inside other Python files).</p>
<h2 id="heading-how-to-initialize-and-publish-a-git-repository-from-pycharm">How to Initialize and Publish a Git Repository From PyCharm</h2>
<p>You may already be familiar with <a target="_blank" href="https://git-scm.com/">Git</a> and know how to initialize a new repository. If you prefer using some other Git client, that's totally fine.</p>
<p>However I think knowing how to make commits right from your IDE can boost your productivity.</p>
<p>Keep in mind you'll need to have Git installed and configured on your system. If you don't have that, <a target="_blank" href="https://www.freecodecamp.org/news/git-first-time-setup/">this article</a> by <a target="_blank" href="https://www.freecodecamp.org/news/author/bolajiayodeji/">Bolaji Ayodeji</a> may come in handy.</p>
<p>Now, continuing on from the last section, if you look at the bottom of your IDE, you should see a "Version Control" tab.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-2-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Click on it and you should switch to the version control tab. Now click on the "Create Git repository..." link.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-3-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>PyCharm will ask you where you want to initialize the new repository. Make sure you're picking the right folder.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-4.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As soon as you press the "OK" button, the "Version Control" tab will change to a "Git" tab.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-5-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>At it's current state, there are no commits. Before you make your first commit, I'd suggest you add a ".gitignore" file so that no unwanted file gets to the repository.</p>
<p>To generate a new gitignore file, head over to <a target="_blank" href="https://www.toptal.com/developers/gitignore/">gitignore.io</a> website. You can generate gitignore files for a large number of technologies from this website.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-6.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You write the name of the technologies that you want to generate the file for. I usually go with "Python", "PyCharm" and hit the "Create" button.</p>
<p>The website will display the content of your desired ".gitignore" file. Select and copy everything from there and go back to PyCharm.</p>
<p>To simulate that, create a new file in your project by right clicking on the "HelloWorld" project name and selecting "File" under the "New" sub menu.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-7.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Name your file ".gitignore" and press enter. PyCharm will ask whether you want to add this file to Git or not. Click on Add and then paste the copied content.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-10.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>At this moment, your repository doesn't have any commits. To create a new commit, click on the "Commit local changes" link or switch to the "Commit" tab.</p>
<p>Since this is your first commit, check all "Changes" and "Unversioned Files" from the commit tab.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-11.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Since this is your first commit, put a descriptive commit message such as "Initial commit" and press the "Commit" button to finalize.</p>
<p>You've successfully made a commit to your local repository. You can now see all the commits under the master branch in detail.</p>
<p>Now it's time to publish this repository on GitHub. To do so, create a new repository under your GitHub account.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-14.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Then copy the SSH link to this repository. If you do not have SSH configured for your project, you may use the HTTPS link but I'd highly recommend SSH.</p>
<p>Now go back to PyCharm and look at the top right corner. Besides where it says Git, you'll find a few signs.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-15.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The downwards blue arrow will pull code from your remote repository, the tick sign will create a new commit, the upwards green arrow will push code.</p>
<p>The clock icon will show your commit history and finally the looped back arrow will revert your changes. Click on the push arrow and a new window will pop up.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-16.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Click on the "Define remote" link and inside the URL input box, paste the link you've copied from GitHub. Press the OK button and wait until the process ends.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-17.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If everything goes fine, PyCharm will give you a "Push" button. It shouldn't take more than a few seconds to push the code to your remote repository.</p>
<p>If you're using HTTPS instead of SSH, you may have to provide your GitHub email and password on every push.</p>
<p>Once done, visit your remote repository and refresh the page to see if the changes have been pushed correctly or not.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-18.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now you can commit and push your code to GitHub right from your IDE every time you make any significant change.</p>
<p>For example, delete the "library.py" file and update the code inside the "main.py" file to print out "Hello, World!" on the console.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(<span class="hljs-string">"Hello, World!"</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, World!</span>
</code></pre>
<p>Once you've made the changes, switch to the commit tab and you'll see all the uncommitted changes.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-19.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Make sure you've checked all the changes you want to commit. Write a descriptive commit message.</p>
<p>Then instead of just committing, try the "Commit and Push..." button this time. A new window will show up.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-21.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If everything looks good to you, click on the Push button and wait for the process to finish.</p>
<p>Remember, if you're using HTTPS you may have to reenter your email and password on every push.</p>
<p>You can check your remote repository on GitHub to make sure that the push has been done correctly.</p>
<p>You can do a lot more in terms of version controlling within PyCharm such as handling pull requests, but I'll leave those out for a later time.</p>
<h2 id="heading-how-to-work-with-variables-and-different-types-of-data-in-python">How to Work With Variables and Different Types of Data in Python</h2>
<p>A variable is an entity that can take on different values of different types. It's a named location in your computer's memory.</p>
<p>To create a new variable in Python, you just need to type out the name of the variable, followed by an equal sign and the value.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book = <span class="hljs-string">'Dracula'</span>
    author = <span class="hljs-string">'Bram Stoker'</span>
    release_year = <span class="hljs-number">1897</span>
    goodreads_rating = <span class="hljs-number">4.01</span>

    print(book)
    print(author)
    print(release_year)
    print(goodreads_rating)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Dracula</span>
<span class="hljs-comment"># Bram Stoker</span>
<span class="hljs-comment"># 1897</span>
<span class="hljs-comment"># 4.01</span>
</code></pre>
<p>When it comes to naming your variable, the <a target="_blank" href="https://peps.python.org/pep-0008/#function-and-variable-names">PEP 8 - Style Guide for Python</a> says:</p>
<blockquote>
<p>Function names should be lowercase, with words separated by underscores as necessary to improve readability.</p>
</blockquote>
<p>And</p>
<blockquote>
<p>Variable names follow the same convention as function names.</p>
</blockquote>
<p>The <a target="_blank" href="https://peps.python.org/pep-0008/#names-to-avoid">guide also</a> says:</p>
<blockquote>
<p>Never use the characters ‘l’ (lowercase letter el), ‘O’ (uppercase letter oh), or ‘I’ (uppercase letter eye) as single character variable names. In some fonts, these characters are indistinguishable from the numerals one and zero. When tempted to use ‘l’, use ‘L’ instead.</p>
</blockquote>
<p>As long as you're keeping these guidelines in mind, declaring variables in Python is very straightforward.</p>
<p>Instead of declaring the variables in separate lines, you can declare them in one go as follows:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book, author, release_year, goodreads_rating = <span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Bram Stoker'</span>, <span class="hljs-number">1897</span>, <span class="hljs-number">4.01</span>

    print(book)
    print(author)
    print(release_year)
    print(goodreads_rating)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Dracula</span>
<span class="hljs-comment"># Bram Stoker</span>
<span class="hljs-comment"># 1897</span>
<span class="hljs-comment"># 4.01</span>
</code></pre>
<p>All you have to do is write the individual variable names in a single line using commas as separators. </p>
<p>Then after the equal sign you have to write the corresponding values in the same order as their names again using commas as separators.</p>
<p>In fact, you can also print them all out in one go. The <code>print()</code> method can take multiple parameters separated by commas.</p>
<pre><code>def main():
    book, author, release_year, goodreads_rating = <span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Bram Stoker'</span>, <span class="hljs-number">1897</span>, <span class="hljs-number">4.01</span>

    print(book, author, release_year, goodreads_rating)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

# Dracula Bram Stoker <span class="hljs-number">1897</span> <span class="hljs-number">4.01</span>
</code></pre><p>These parameters are then printed on the terminal in a single line using spaces for separating each of them.</p>
<p>Speaking of the <code>print()</code> method, you can use the <code>+</code> sign to add variables with strings inside a print method:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book, author, release_year, goodreads_rating = <span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Bram Stoker'</span>, <span class="hljs-number">1897</span>, <span class="hljs-number">4.01</span>

    print(book + <span class="hljs-string">' is a novel by '</span> + author + <span class="hljs-string">', published in '</span> + release_year + <span class="hljs-string">'. It has a rating of '</span> + goodreads_rating + <span class="hljs-string">' on goodreads.'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()


<span class="hljs-comment"># TypeError: can only concatenate str (not "int") to str</span>
</code></pre>
<p>If you try to run this code you'll get a <code>TypeError</code> that says Python can concatenate or add together strings not integers.</p>
<p>In the code snippet above, <code>book</code>, <code>author</code>, <code>release_year</code>, and <code>goodreads_rating</code> are all variables of different types.</p>
<p>The <code>book</code> and <code>author</code> variables are strings. The <code>release_year</code> is an integer and finally the <code>goodreads_rating</code> variable is a floating point number.</p>
<p>Whenever Python encounters a <code>+</code> sign in front of a numeric type, it assumes that the programmer may be performing an arithmetic operation.</p>
<p>The easiest way to solve this problem is to convert the numeric types to strings. You can do that by calling the <code>str()</code> method on the numeric variables.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book, author, release_year, goodreads_rating = <span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Bram Stoker'</span>, <span class="hljs-number">1897</span>, <span class="hljs-number">4.01</span>

    print(book + <span class="hljs-string">' is a novel by '</span> + author + <span class="hljs-string">', published in '</span> + str(release_year) + <span class="hljs-string">'. It has a rating of '</span> + str(goodreads_rating) + <span class="hljs-string">' on goodreads.'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Dracula is a novel by Bram Stoker, published in 1897. It has a rating of 4.01 on goodreads.</span>
</code></pre>
<p>That's better – but you can make that line of code even more readable by using a f string.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book, author, release_year, goodreads_rating = <span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Bram Stoker'</span>, <span class="hljs-number">1897</span>, <span class="hljs-number">4.01</span>

    print(<span class="hljs-string">f'<span class="hljs-subst">{book}</span> is a novel by <span class="hljs-subst">{author}</span>, published in <span class="hljs-subst">{release_year}</span>. It has a rating of <span class="hljs-subst">{goodreads_rating}</span> on goodreads.'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Dracula is a novel by Bram Stoker, published in 1897. It has a rating of 4.01 on goodreads.</span>
</code></pre>
<p>You can turn a regular string to a f string by putting a <code>f</code> in front of it and suddenly you can write variable names inside curly braces right within the string itself.</p>
<p>There is one last thing that's bugging me, and that's the length of the line of code itself. Fortunately you can split long strings into multiple shorter ones as follows:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book, author, release_year, goodreads_rating = <span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Bram Stoker'</span>, <span class="hljs-number">1897</span>, <span class="hljs-number">4.01</span>

    print(<span class="hljs-string">f'<span class="hljs-subst">{book}</span> is a novel by <span class="hljs-subst">{author}</span>, published in <span class="hljs-subst">{release_year}</span>.'</span>
          <span class="hljs-string">f' It has a rating of <span class="hljs-subst">{goodreads_rating}</span> on goodreads.'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Dracula is a novel by Bram Stoker, published in 1897. It has a rating of 4.01 on goodreads.</span>
</code></pre>
<p>Now that's how a good piece of Python code should look. I'd suggest you try to make your code readable from the very beginning – you'll thank me later for that.</p>
<p>Other than <code>int</code> and <code>float</code>, there is another numeric type called <code>complex</code> in Python. It was specifically designed for dealing with numbers like <code>500+2j</code>.</p>
<p>There are also boolean data that can hold the value <code>True</code> or <code>False</code> and nothing else. You can actually ask Python questions and it'll answer in boolean.</p>
<p>Throughout this book you'll not see complex numbers in action and booleans will come into play much later. So for now, lets focus on simple numbers and strings.</p>
<h2 id="heading-how-to-work-with-simple-numbers-in-python">How to Work With Simple Numbers in Python</h2>
<p>Simple numbers in Python are of two types. Whole numbers are integers and numbers with floating points in them are floats.</p>
<p>In Python, you can represent integers using four different bases. These are decimal, hexadecimal, octal, and binary.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Base</td><td>Representation</td></tr>
</thead>
<tbody>
<tr>
<td>Decimal</td><td>404</td></tr>
<tr>
<td>Hexadecimal</td><td>0x194</td></tr>
<tr>
<td>Octal</td><td>0o624</td></tr>
<tr>
<td>Binary</td><td>0b000110010100</td></tr>
</tbody>
</table>
</div><p>So you can represent the value of 404 in hexadecimal, octal, or binary by prefixing the corresponding value with <code>0x</code>, <code>0o</code>, or <code>0b</code> respectively.</p>
<p>On the other hand you can represent floats with the precision of up to 15 significant digits in Python. Any digit after the 15th place may be inaccurate.</p>
<p>There are six different arithmetic operations that you can perform on any of the simple numeric types. The simplest of the bunch are addition and subtraction.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    num_1 = <span class="hljs-number">15</span>
    num_2 = <span class="hljs-number">12</span>

    print(<span class="hljs-string">f'sum of num_1 and num_2 is: <span class="hljs-subst">{num_1 + num_2}</span>'</span>)
    print(<span class="hljs-string">f'difference of num_1 and num_2 is: <span class="hljs-subst">{num_1 - num_2}</span>'</span>)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># sum of num_1 and num_2 is: 27</span>
<span class="hljs-comment"># difference of num_1 and num_2 is: 3</span>
</code></pre>
<p>In case of a subtraction operation, the result will be negative if the second operand is larger than the first one.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    num_1 = <span class="hljs-number">15</span>
    num_2 = <span class="hljs-number">12</span>

    print(<span class="hljs-string">f'difference of num_2 and num_1 is: <span class="hljs-subst">{num_2 - num_1}</span>'</span>)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># difference of num_2 and num_1 is: -3</span>
</code></pre>
<p>Similarly you can perform multiplication and division operations using their corresponding operators.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    num_1 = <span class="hljs-number">15</span>
    num_2 = <span class="hljs-number">12</span>

    print(<span class="hljs-string">f'product of num_1 and num_2 is: <span class="hljs-subst">{num_1 * num_2}</span>'</span>)
    print(<span class="hljs-string">f'quotient of num_1 and num_2 is: <span class="hljs-subst">{num_1 / num_2}</span>'</span>)
    print(<span class="hljs-string">f'floored quotient of num_1 and num_2 is: <span class="hljs-subst">{num_1 // num_2}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># product of num_1 and num_2 is: 180</span>
<span class="hljs-comment"># quotient of num_1 and num_2 is: 1.25</span>
<span class="hljs-comment"># floored quotient of num_1 and num_2 is: 1</span>
</code></pre>
<p>Keep in mind that you can not divide a number by zero in Python. If you attempt that, you'll get a <code>ZeroDivisionError</code> error (more on that later).</p>
<p>Output from a division operation will always be a float value, unless you perform a floored division by using two division operators.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    num_1 = <span class="hljs-number">15</span>
    num_2 = <span class="hljs-number">12</span>

    print(<span class="hljs-string">f'floored quotient of num_1 and num_2 is: <span class="hljs-subst">{num_1 // num_2}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># floored quotient of num_1 and num_2 is: 1</span>
</code></pre>
<p>In this case the result will be rounded off to the nearest integer low – so, for example, 0.25 will be lost. So only perform this operation when such loss of data is permissible.</p>
<p>The last operation to discuss is finding the remainder of a division operation.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    num_1 = <span class="hljs-number">15</span>
    num_2 = <span class="hljs-number">12</span>

    print(<span class="hljs-string">f'remainder of num_1 / num_2 is: <span class="hljs-subst">{num_1 % num_2}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># remainder of num_1 / num_2 is: 3</span>
</code></pre>
<p>This operation is also called a modulo or modulus operation. So if someone mentions the modulo or modulus operator, they're referring to the percent sign.</p>
<p>You can turn an unsigned number into a negative one just by adding a <code>-</code> sign in front of it. You can also freely convert between integer to float and vice versa.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    float_variable = <span class="hljs-number">1.25</span>
    integer_variable = <span class="hljs-number">55</span>

    print(<span class="hljs-string">f'<span class="hljs-subst">{float_variable}</span> converted to an integer is: <span class="hljs-subst">{int(float_variable)}</span>'</span>)
    print(<span class="hljs-string">f'<span class="hljs-subst">{integer_variable}</span> converted to a float is: <span class="hljs-subst">{float(integer_variable)}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 1.25 converted to an integer is: 1</span>
<span class="hljs-comment"># 55 converted to a float is: 55.0</span>
</code></pre>
<p>Loss of data in case of a float to integer conversion is inevitable, so be careful. You can use the <code>int()</code> and <code>float()</code> methods on strings as well (more on that later).</p>
<p>Any arithmetic operation involving a float operand will always produce a float result, unless converted to integer explicitly.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    float_variable = <span class="hljs-number">5.0</span>
    integer_variable = <span class="hljs-number">55</span>

    print(<span class="hljs-string">f'the sum of <span class="hljs-subst">{float_variable}</span> and <span class="hljs-subst">{integer_variable}</span> is: <span class="hljs-subst">{float_variable + integer_variable}</span>'</span>)
    print(<span class="hljs-string">f'the sum of <span class="hljs-subst">{float_variable}</span> and <span class="hljs-subst">{integer_variable}</span> '</span>
          <span class="hljs-string">f'converted to integer is: <span class="hljs-subst">{int(float_variable + integer_variable)}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># the sum of 5.0 and 55 is: 60.0</span>
<span class="hljs-comment"># the sum of 5.0 and 55 converted to integer is: 60</span>
</code></pre>
<p>If you ever want to get the absolute value of a signed value you can do so using the <code>abs()</code> method.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    num_1 = <span class="hljs-number">-5.8</span>

    print(<span class="hljs-string">f'the absolute value of <span class="hljs-subst">{num_1}</span> is: <span class="hljs-subst">{abs(num_1)}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># the absolute value of -5.8 is: 5.8</span>
</code></pre>
<p>There is a similar method <code>pow(x, y)</code> that you can use to apply <code>x</code> as the power of <code>y</code> like this.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    x = <span class="hljs-number">2</span>
    y = <span class="hljs-number">3</span>

    print(<span class="hljs-string">f'<span class="hljs-subst">{<span class="hljs-number">2</span>}</span> to the power of <span class="hljs-subst">{<span class="hljs-number">3</span>}</span> is: <span class="hljs-subst">{pow(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)}</span>'</span>)
    print(<span class="hljs-string">f'<span class="hljs-subst">{<span class="hljs-number">2</span>}</span> to the power of <span class="hljs-subst">{<span class="hljs-number">3</span>}</span> is: <span class="hljs-subst">{<span class="hljs-number">2</span> ** <span class="hljs-number">3</span>}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 2 to the power of 3 is: 8</span>
<span class="hljs-comment"># 2 to the power of 3 is: 8</span>
</code></pre>
<p>You can perform the same operation using two multiplication operators but I always prefer the <code>pow()</code> method.</p>
<p>Finally there is the <code>divmod()</code> method that you can use to combine the division and modulo operation.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    num_1 = <span class="hljs-number">8</span>
    num_2 = <span class="hljs-number">2</span>

    print(<span class="hljs-string">f'division and modulus of <span class="hljs-subst">{num_1}</span> and <span class="hljs-subst">{num_2}</span> is: <span class="hljs-subst">{divmod(num_1, num_2)}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># division and modulus of 8 and 2 is: (4, 0)</span>
</code></pre>
<p>The method returns a tuple of numbers (more on that later). The first one is the result of the division and the second one is the result of the modulo operation.</p>
<p>These are the basic operations you can perform on simple numbers right from the get go. But you can do much more once you start to pull in the built-in modules.</p>
<h2 id="heading-how-to-take-inputs-from-users-in-python">How to Take Inputs From Users in Python</h2>
<p>Learning how to take input from a user is an important milestone because it lets you create programs that a human being can interact with.</p>
<p>Unlike many other programming languages, taking user inputs in Python is very straightforward.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    name = input(<span class="hljs-string">'What is your name? '</span>)

    print(<span class="hljs-string">f'Nice to meet you <span class="hljs-subst">{name}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># What is your name? Farhan</span>
<span class="hljs-comment"># Nice to meet you Farhan</span>
</code></pre>
<p>The built-in <code>input()</code> method does exactly what it sounds like. The method accepts a single parameter <code>prompt</code> which is of string type.</p>
<p>Whatever you write as the value of this parameter will be shown in the console – like in this case, "What is your name?" is the prompt.</p>
<p>Once the user writes something on the console and presses enter, the input method will return that as a string.</p>
<p>You can save that string to any variable like I've saved the name inside the <code>name</code> variable. Even if the user inputs a number, <code>input()</code> will return that as a string.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    name = input(<span class="hljs-string">'What is your name? '</span>)
    age = input(<span class="hljs-string">f'How old are you <span class="hljs-subst">{name}</span>? '</span>)
    current_year = input(<span class="hljs-string">f'What year is this again? '</span>)

    print(<span class="hljs-string">f'If my calculations are right, you were born in <span class="hljs-subst">{current_year - age}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># What is your name? Farhan</span>
<span class="hljs-comment"># How old are you Farhan? 27</span>
<span class="hljs-comment"># What year is this again? 2023</span>
<span class="hljs-comment"># TypeError: unsupported operand type(s) for -: 'str' and 'str'</span>
</code></pre>
<p>Even though Python is taking all the user inputs correctly, it fails to calculate the user's birth year because arithmetic operations are not a good fit for strings.</p>
<p>To solve this problem, you just have to convert the user inputs to numeric types using the <code>int()</code> or <code>float()</code> functions as needed.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    name = input(<span class="hljs-string">'What is your name? '</span>)
    age = int(input(<span class="hljs-string">f'How old are you <span class="hljs-subst">{name}</span>? '</span>))
    current_year = int(input(<span class="hljs-string">f'What year is this again? '</span>))

    print(<span class="hljs-string">f'If my calculations are right, you were born in <span class="hljs-subst">{current_year - age}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># What is your name? Farhan</span>
<span class="hljs-comment"># How old are you Farhan? 27</span>
<span class="hljs-comment"># What year is this again? 2023</span>
<span class="hljs-comment"># If my calculations are right, you were born in 1996</span>
</code></pre>
<p>There you go, works like a charm. You can perform this conversion at any point in the code. It's not mandatory to convert them right at the beginning.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    temperature_in_celsius = input(<span class="hljs-string">'What is the temperature in celsius? '</span>)

    temperature_in_fahrenheit = (float(temperature_in_celsius) * <span class="hljs-number">1.8</span>) + <span class="hljs-number">32</span>

    print(<span class="hljs-string">f'<span class="hljs-subst">{temperature_in_celsius}</span> degree celsius is equivalent to <span class="hljs-subst">{temperature_in_fahrenheit}</span> degree fahrenheit.'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># What is the temperature in celsius? 32</span>
<span class="hljs-comment"># 32 degree celsius is equivalent to 89.6 degree fahrenheit.</span>
</code></pre>
<p>This program can convert temperature from Celsius to Fahrenheit. In this program, I didn't convert the input from string to a numeric type right away.</p>
<p>I performed the conversion during the calculation leaving the original input variable intact. Also notice the use of <code>float()</code> instead of the <code>int()</code> function.</p>
<h2 id="heading-how-to-work-with-strings-in-python">How to Work With Strings in Python</h2>
<p>You've already seen examples of strings in the previous sections – but there is a lot more that you need to learn about strings.</p>
<p>In Python, anything enclosed within a set of single, double, or triple quotes is a string. These are sequences of bytes representing Unicode characters.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book = <span class="hljs-string">'Dracula'</span>
    author = <span class="hljs-string">"Bram Stoker"</span>

    print(<span class="hljs-string">'Title:'</span>, book)
    print(<span class="hljs-string">'Author:'</span>, author)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Title: Dracula</span>
<span class="hljs-comment"># Author: Bram Stoker</span>
</code></pre>
<p>Declaring a string with single or double quotes makes no difference whatsoever. But based on the scenario, you may have to choose on over the other.</p>
<p>For example, if you have an apostrophe within your sentence, you may want to use double quotes.</p>
<pre><code>def main():
    question = <span class="hljs-string">"What's your name?"</span>

    print(question)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

# What<span class="hljs-string">'s your name?</span>
</code></pre><p>The opposite can also occur. For example, when you have a direct quote within your string:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    sentence = <span class="hljs-string">'Harriet Jacobs writes, "She sat down, quivering in every limb"'</span>

    print(sentence)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Harriet Jacobs writes, "She sat down, quivering in every limb"</span>
</code></pre>
<p>You can also go for <a target="_blank" href="https://www.freecodecamp.org/news/escape-sequences-python/">escape sequences</a> if you want to, but the <a target="_blank" href="https://peps.python.org/pep-0008/#string-quotes">PEP 8 - Style Guide for Python Code</a> recommends avoiding the usage of back slashes within strings.</p>
<p>Triple quotes are a different case altogether. You can put multi-line strings within triple quotes and Python will preserve the white spaces as well.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    synopsis = <span class="hljs-string">"""Dracula comprises journal entries, letters, and telegrams written by the main characters.
It begins with Jonathan Harker, a young English lawyer, as he travels to Transylvania.
Harker plans to meet with Count Dracula, a client of his firm, in order to finalize a property transaction.
When he arrives in Transylvania, the locals react with terror after he discloses his destination: Castle Dracula.
Though this unsettles him slightly, he continues onward.
The ominous howling of wolves rings through the air as he arrives at the castle.
When Harker meets Dracula, he acknowledges that the man is pale, gaunt, and strange.
Harker becomes further concerned when, after Harker cuts himself while shaving, Dracula lunges at his throat.
Soon after, Harker is seduced by three female vampires, from whom he barely escapes.
He then learns Dracula’s secret—that he is a vampire and survives by drinking human blood.
Harker correctly assumes that he is to be the count’s next victim.
He attacks the count, but his efforts are unsuccessful.
Dracula leaves Harker trapped in the castle and then, along with 50 boxes of dirt, departs for England."""</span>

    print(<span class="hljs-string">'Synopsis:'</span>, synopsis)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Synopsis: Dracula comprises journal entries, letters, and telegrams written by the main characters.</span>
<span class="hljs-comment"># It begins with Jonathan Harker, a young English lawyer, as he travels to Transylvania.</span>
<span class="hljs-comment"># Harker plans to meet with Count Dracula, a client of his firm, in order to finalize a property transaction.</span>
<span class="hljs-comment"># When he arrives in Transylvania, the locals react with terror after he discloses his destination: Castle Dracula.</span>
<span class="hljs-comment"># Though this unsettles him slightly, he continues onward.</span>
<span class="hljs-comment"># The ominous howling of wolves rings through the air as he arrives at the castle.</span>
<span class="hljs-comment"># When Harker meets Dracula, he acknowledges that the man is pale, gaunt, and strange.</span>
<span class="hljs-comment"># Harker becomes further concerned when, after Harker cuts himself while shaving, Dracula lunges at his throat.</span>
<span class="hljs-comment"># Soon after, Harker is seduced by three female vampires, from whom he barely escapes.</span>
<span class="hljs-comment"># He then learns Dracula’s secret—that he is a vampire and survives by drinking human blood.</span>
<span class="hljs-comment"># Harker correctly assumes that he is to be the count’s next victim.</span>
<span class="hljs-comment"># He attacks the count, but his efforts are unsuccessful.</span>
<span class="hljs-comment"># Dracula leaves Harker trapped in the castle and then, along with 50 boxes of dirt, departs for England.</span>
</code></pre>
<p>So if you ever want to print out a multi line string while preserving the white spaces, go for triple quotes.</p>
<p>You can declare a triple quoted string using three single quotes but the <a target="_blank" href="https://peps.python.org/pep-0008/#string-quotes">PEP 8 - Style Guide for Python Code</a> recommends the usage of three double quotes.</p>
<p>There is a lot more to learn about strings, but I'd like to introduce you to some other sequence types in Python.</p>
<h2 id="heading-what-are-the-sequence-types-in-python">What Are the Sequence Types in Python?</h2>
<p>In Python, there are three sequence types. They are lists, tuples, and ranges. I'll start with the lists because it's probably the most utilized sequence type in Python.</p>
<h3 id="heading-lists-in-python">Lists in Python</h3>
<p>A list in Python is exactly what it sounds like: a collection of data stored sequentially on the computer's memory.</p>
<p>You can create a new list in Python by writing out its name followed by an equal sign, followed by the values to store enclosed in square brackets:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    horror_books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Carmilla'</span>, <span class="hljs-string">'The Imago Sequence'</span>]

    print(horror_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ['Dracula', 'Carmilla', 'The Imago Sequence']</span>
</code></pre>
<p>In this example, <code>horror_books</code> is a list of strings. But you can create lists of integers, floats, or even of mixed types.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    a_random_list = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-number">1</span>, <span class="hljs-number">5.7</span>, <span class="hljs-string">'Carmilla'</span>]

    print(a_random_list)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ['Dracula', 1, 5.7, 'Carmilla']</span>
</code></pre>
<p>Though this is perfectly valid, you may find yourself creating lists of the same types more often.</p>
<p>Lists in Python are mutable. This means you can modify a list after its creation. For example, you can use the <code>pop()</code> method to get rid of the last value in a list.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    horror_books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Carmilla'</span>, <span class="hljs-string">'The Imago Sequence'</span>]

    print(horror_books.pop())
    print(horror_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># The Imago Sequence</span>
<span class="hljs-comment"># ['Dracula', 'Carmilla']</span>
</code></pre>
<p>As you can see, the <code>pop()</code> method returns the last value from the list and gets rid of it. Like <code>pop()</code> there is the <code>append()</code> method for inserting new item to the list.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    horror_books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Carmilla'</span>, <span class="hljs-string">'The Imago Sequence'</span>]

    print(horror_books)

    horror_books.append(<span class="hljs-string">'The Exorcist'</span>)

    print(horror_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ['Dracula', 'Carmilla', 'The Imago Sequence']</span>
<span class="hljs-comment"># ['Dracula', 'Carmilla', 'The Imago Sequence', 'The Exorcist']</span>
</code></pre>
<p>As you can see from the method name, it adds the new item at the end of the list. Given their mutable nature, lists can also be sorted.</p>
<p>Feel free to check out the following article written by my colleague <a target="_blank" href="https://www.freecodecamp.org/news/author/dionysia/">Dionysia Lemonaki</a> here on freeCodeCamp about how to sort lists in Python:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.freecodecamp.org/news/python-sort-how-to-sort-a-list-in-python/">https://www.freecodecamp.org/news/python-sort-how-to-sort-a-list-in-python/</a></div>
<h3 id="heading-tuples-in-python">Tuples in Python</h3>
<p>Lists are not the only sequence type in Python. The closest sibling of lists in Python are tuples.</p>
<p>You can create a new tuple in Python by writing out its name followed by an equal sign, then enclosing inside a pair of parenthesis the values you want to store.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    horror_books = (<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Carmilla'</span>, <span class="hljs-string">'The Imago Sequence'</span>)

    print(horror_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ('Dracula', 'Carmilla', 'The Imago Sequence')</span>
</code></pre>
<p>Just like lists, you can also mix and match different types of data within a single tuple as you see fit.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    a_random_list = (<span class="hljs-string">'Dracula'</span>, <span class="hljs-number">1</span>, <span class="hljs-number">5.7</span>, <span class="hljs-string">'Carmilla'</span>)

    print(a_random_list)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ('Dracula', 1, 5.7, 'Carmilla')</span>
</code></pre>
<p>The most glaring dissimilarity between a list and a tuple is the fact that a tuple is immutable. So there's no popping and appending for us this time.</p>
<h3 id="heading-ranges-in-python">Ranges in Python</h3>
<p>The final sequence type that you're going to learn about in this section is a range. A range in Python is just a range of numbers.</p>
<p>You can create a range by calling the <code>range()</code> method and it'll return a range of numbers. You can call the method in a few different ways.</p>
<p>The most common is by passing a single number as a parameter. In this case, the method will treat that number as the end of the range and 0 as the start.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    a_range = range(<span class="hljs-number">10</span>)

    print(a_range)

    list_a_range = list(a_range)

    print(list_a_range)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># range(0, 10)</span>
<span class="hljs-comment"># [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</span>
<span class="hljs-comment"># (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)</span>
</code></pre>
<p>Printing out a range as is won't give you much information. You'll have to convert the range to a list or a tuple by either calling the <code>list()</code> or <code>tuple()</code> method.</p>
<p>Once converted, you can then print out the entire range to the console. Notice how 10 or the number passed to the <code>range()</code> method is not included in the range.</p>
<p>The second way of calling the method is by supplying both the starting and ending numbers for the range.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    a_range = range(<span class="hljs-number">5</span>, <span class="hljs-number">15</span>)

    print(a_range)

    list_a_range = list(a_range)

    print(list_a_range)

    tuple_a_range = tuple(a_range)

    print(tuple_a_range)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># range(5, 15)</span>
<span class="hljs-comment"># [5, 6, 7, 8, 9, 10, 11, 12, 13, 14]</span>
<span class="hljs-comment"># (5, 6, 7, 8, 9, 10, 11, 12, 13, 14)</span>
</code></pre>
<p>Once again, the number you pass as the ending for the range will not be included in the resultant range.</p>
<p>The third and final way to call the method is by also defining a step. For example, imagine you want a range comprising of all the odd numbers within 1 to 10.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    a_range = range(<span class="hljs-number">1</span>, <span class="hljs-number">10</span>, <span class="hljs-number">2</span>)

    print(a_range)

    list_a_range = list(a_range)

    print(list_a_range)

    tuple_a_range = tuple(a_range)

    print(tuple_a_range)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># range(1, 10, 2)</span>
<span class="hljs-comment"># [1, 3, 5, 7, 9]</span>
<span class="hljs-comment"># (1, 3, 5, 7, 9)</span>
</code></pre>
<p>Since the value of step is 2 in this case, the range will begin with 1 but then skip every second number.</p>
<p>It may take some time to wrap your head around this concept but practicing with different step values will help.</p>
<p>Or you can read the following article written by <a target="_blank" href="https://www.freecodecamp.org/news/author/bala-priya/">Bala Priya C</a>:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.freecodecamp.org/news/python-range-function-explained-with-code-examples/">https://www.freecodecamp.org/news/python-range-function-explained-with-code-examples/</a></div>
<h3 id="heading-how-indexing-works-in-python">How Indexing Works in Python</h3>
<p>One of the most important concepts regarding sequence types that you need to understand is indexing.</p>
<p>You see, each element in a sequence has a number attached to it that expresses its position in the list called an index. These indices are 0 based.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/horror-books-list.svg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This diagram represents our list of horror books. The index of the first book is 0 – this means that the first element is at the 0th place.</p>
<p>The second one is at the 1st place and the third one is at the 2nd place. This zero-based indexing is may seem confusing at first but you'll get the hang of it.</p>
<p>The most basic usage of a index is to access its corresponding value from the sequence.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    horror_books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Carmilla'</span>, <span class="hljs-string">'The Imago Sequence'</span>]

    print(horror_books[<span class="hljs-number">0</span>])
    print(horror_books[<span class="hljs-number">1</span>])
    print(horror_books[<span class="hljs-number">2</span>])


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Dracula</span>
<span class="hljs-comment"># Carmilla</span>
<span class="hljs-comment"># The Imago Sequence</span>
</code></pre>
<p>You can also use negative numbers as indices but in that case the counting will start from the end.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Frankenstein'</span>, <span class="hljs-string">'The Omen'</span>, <span class="hljs-string">'The Exorcist'</span>, <span class="hljs-string">'The Legend of Sleepy Hollow'</span>,
             <span class="hljs-string">'And Then There Were None'</span>, <span class="hljs-string">'The ABC Murders'</span>, <span class="hljs-string">'The Valley of Fear'</span>]

    print(books[<span class="hljs-number">0</span>])

    print(books[<span class="hljs-number">1</span>])
    print(books[<span class="hljs-number">-1</span>])

    print(books[<span class="hljs-number">2</span>])
    print(books[<span class="hljs-number">-2</span>])


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

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

<span class="hljs-comment"># Frankenstein</span>
<span class="hljs-comment"># The Valley of Fear</span>

<span class="hljs-comment"># The Omen</span>
<span class="hljs-comment"># The ABC Murders</span>
</code></pre>
<p>The 0th element in a list will always be the first one. Now if you access the element on the 1st position you get "Frankenstein".</p>
<p>But if you try to access the element on the -1st position, you get "The Valley of Fear" because that's the second item in reverse.</p>
<p>The element on the 2nd position is "The Omen" but the element at the -2nd position is "The ABC Murders" because that's the third item in reverse.</p>
<p>If you're finding it hard to wrap your head around, imagine the list like a clock.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/list-clock.svg" alt="Image" width="600" height="400" loading="lazy">
<em>Zero-based indexing represented as a circular diagram like a clock</em></p>
<p>Here the outer number is the negative index and the inner number is the positive index. If you try to match the outputs against this imaginary clock, it should be easier to understand.</p>
<h2 id="heading-what-are-the-iterable-types-and-how-to-use-them-for-loops-in-python">What Are the Iterable Types and How to Use them for Loops in Python</h2>
<p>So far you've learned about creating collections of data and accessing them one by one. That's cool but there is something cooler.</p>
<p>Imagine you have a list or some other type of that contains a bunch of numbers.</p>
<p>Now you want to multiply each number in that list by two, insert the multiplied numbers in a new list, and print out the list on the terminal.</p>
<p>This is an excellent use case for the <code>for</code> statement in Python. Let's begin by first iterating through each number in a given list.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    random_numbers = [<span class="hljs-number">6</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">8</span>, <span class="hljs-number">0</span>, <span class="hljs-number">9</span>, <span class="hljs-number">12</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">0</span>, <span class="hljs-number">54</span>, <span class="hljs-number">8</span>, <span class="hljs-number">100</span>, <span class="hljs-number">55</span>, <span class="hljs-number">60</span>, <span class="hljs-number">70</span>, <span class="hljs-number">85</span>]

    <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> random_numbers:
        print(number)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 6</span>
<span class="hljs-comment"># 1</span>
<span class="hljs-comment"># 3</span>
<span class="hljs-comment"># 8</span>
<span class="hljs-comment"># 0</span>
<span class="hljs-comment"># 9</span>
<span class="hljs-comment"># 12</span>
<span class="hljs-comment"># 3</span>
<span class="hljs-comment"># 4</span>
<span class="hljs-comment"># 0</span>
<span class="hljs-comment"># 54</span>
<span class="hljs-comment"># 8</span>
<span class="hljs-comment"># 100</span>
<span class="hljs-comment"># 55</span>
<span class="hljs-comment"># 60</span>
<span class="hljs-comment"># 70</span>
<span class="hljs-comment"># 85</span>
</code></pre>
<p>You start by writing out the word <code>for</code> followed by a variable name. I've used <code>number</code> but you can use anything that makes sense to you.</p>
<p>Although you write it as <code>for number</code>, Python reads it as <code>for each number</code> and wonders where are these numbers staying?</p>
<p>That's when you say <code>in</code> followed by the name of the sequence, <code>random_numbers</code> in this case.</p>
<p>Now Python understands that you want to do something with each number in the <code>random_numbers</code> sequence, but what?</p>
<p>That's what you have to write out after the colon and be very careful about the indentation. Anything indented one level after the for loop declaration is considered the loop body.</p>
<p>Inside the for loop you can write whatever you want to do with the current value of the <code>number</code> variable.</p>
<p>Since there are 17 numbers in the sequence, the loop will run 17 times and each time it'll have a new value.</p>
<p>It'll start at index 0 which has the value of 6 and go through index 1, 2, 3, 4, 5, and so on. </p>
<p>On each iteration, it'll save the value of the index it's currently working on inside the <code>number</code> variable and print it out. Hence you get the long list of numbers.</p>
<p>Instead of printing out the original value, you can multiply it by 2 and print out the resultant value instead.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    random_numbers = [<span class="hljs-number">6</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">8</span>, <span class="hljs-number">0</span>, <span class="hljs-number">9</span>, <span class="hljs-number">12</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">0</span>, <span class="hljs-number">54</span>, <span class="hljs-number">8</span>, <span class="hljs-number">100</span>, <span class="hljs-number">55</span>, <span class="hljs-number">60</span>, <span class="hljs-number">70</span>, <span class="hljs-number">85</span>]

    <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> random_numbers:
        print(number * <span class="hljs-number">2</span>)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 12</span>
<span class="hljs-comment"># 2</span>
<span class="hljs-comment"># 6</span>
<span class="hljs-comment"># 16</span>
<span class="hljs-comment"># 0</span>
<span class="hljs-comment"># 18</span>
<span class="hljs-comment"># 24</span>
<span class="hljs-comment"># 6</span>
<span class="hljs-comment"># 8</span>
<span class="hljs-comment"># 0</span>
<span class="hljs-comment"># 108</span>
<span class="hljs-comment"># 16</span>
<span class="hljs-comment"># 200</span>
<span class="hljs-comment"># 110</span>
<span class="hljs-comment"># 120</span>
<span class="hljs-comment"># 140</span>
<span class="hljs-comment"># 170</span>
</code></pre>
<p>Now you're getting the multiplied values. The final task is to insert these multiplied values in a new list and print out the new list itself.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    random_numbers = [<span class="hljs-number">6</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">8</span>, <span class="hljs-number">0</span>, <span class="hljs-number">9</span>, <span class="hljs-number">12</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">0</span>, <span class="hljs-number">54</span>, <span class="hljs-number">8</span>, <span class="hljs-number">100</span>, <span class="hljs-number">55</span>, <span class="hljs-number">60</span>, <span class="hljs-number">70</span>, <span class="hljs-number">85</span>]
    multiplied_random_numbers = []

    <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> random_numbers:
        multiplied_random_numbers.append(number * <span class="hljs-number">2</span>)

    print(multiplied_random_numbers)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># [12, 2, 6, 16, 0, 18, 24, 6, 8, 0, 108, 16, 200, 110, 120, 140, 170]</span>
</code></pre>
<p>For that you'll need an empty list. Then, after multiplying the number, you can simply call the <code>append()</code> method on the new list and pass the multiplied value.</p>
<p>Finally, make sure that you're putting the print statement outside of the loop body otherwise you'll end up printing out the list 17 times.</p>
<p>The <code>for</code> loop works with all the sequence types and any iterable type in the Python language. What is an iterable type, I hear you ask.</p>
<p>Well, any object that has the <code>__iter__()</code> method is considered an iterable in Python.</p>
<p>You can call the <code>dir()</code> function on any object to list out all its methods and properties. Take the <code>random_numbers</code> list as an example.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    random_numbers = [<span class="hljs-number">6</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">8</span>, <span class="hljs-number">0</span>, <span class="hljs-number">9</span>, <span class="hljs-number">12</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">0</span>, <span class="hljs-number">54</span>, <span class="hljs-number">8</span>, <span class="hljs-number">100</span>, <span class="hljs-number">55</span>, <span class="hljs-number">60</span>, <span class="hljs-number">70</span>, <span class="hljs-number">85</span>]

    print(dir(random_numbers))

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']</span>
</code></pre>
<p>You can see some familiar methods such as <code>append</code>, <code>count</code>, and <code>index</code> but most importantly it has the <code>__iter__</code> method.</p>
<p>As you keep working in Python you'll eventually remember the types supported by the <code>for</code> loop but you can always use the <code>dir()</code> method on a object to find out.</p>
<h2 id="heading-how-to-use-while-loops-in-python">How to Use While Loops in Python</h2>
<p>There is another type of loop in Python known as the <code>while</code> loop. Unlike <code>for</code>, a <code>while</code> loop can execute a statement as long as a given condition evaluates to <code>true</code>.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    number = <span class="hljs-number">1</span>
    <span class="hljs-keyword">while</span> number &lt; <span class="hljs-number">11</span>:
        print(number)
        number += <span class="hljs-number">1</span>

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 1</span>
<span class="hljs-comment"># 2</span>
<span class="hljs-comment"># 3</span>
<span class="hljs-comment"># 4</span>
<span class="hljs-comment"># 5</span>
<span class="hljs-comment"># 6</span>
<span class="hljs-comment"># 7</span>
<span class="hljs-comment"># 8</span>
<span class="hljs-comment"># 9</span>
<span class="hljs-comment"># 10</span>
</code></pre>
<p>Here you have a variable <code>number</code> with the value <code>11</code> and a <code>while</code> loop that prints out the value of number, then increases it by 1.</p>
<p>A <code>while</code> loop starts by writing out <code>while</code> followed by the condition. Then you write the loop body starting from the next line after the colon.</p>
<p><code>for</code> loops are useful when you're trying to access every element inside an iterable. <code>while</code> loops are useful when you want to repeat the same set of instructions an arbitrary number of times.</p>
<p>The line <code>number += 1</code> is another way to write <code>number = number + 1</code> and it's very commonly used by programmers across different programming languages.</p>
<h2 id="heading-how-to-write-nested-loops-in-python">How to Write Nested Loops in Python</h2>
<p>You can also nest one loop inside another. For example, look at the following code that prints out multiplication tables:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, <span class="hljs-number">6</span>):
        print()
        <span class="hljs-keyword">for</span> y <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, <span class="hljs-number">11</span>):
            print(<span class="hljs-string">f"<span class="hljs-subst">{x}</span> x <span class="hljs-subst">{y}</span> = <span class="hljs-subst">{x * y}</span>"</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment">#</span>
<span class="hljs-comment"># 1 x 1 = 1</span>
<span class="hljs-comment"># 1 x 2 = 2</span>
<span class="hljs-comment"># 1 x 3 = 3</span>
<span class="hljs-comment"># 1 x 4 = 4</span>
<span class="hljs-comment"># 1 x 5 = 5</span>
<span class="hljs-comment"># 1 x 6 = 6</span>
<span class="hljs-comment"># 1 x 7 = 7</span>
<span class="hljs-comment"># 1 x 8 = 8</span>
<span class="hljs-comment"># 1 x 9 = 9</span>
<span class="hljs-comment"># 1 x 10 = 10</span>
<span class="hljs-comment">#</span>
<span class="hljs-comment"># 2 x 1 = 2</span>
<span class="hljs-comment"># 2 x 2 = 4</span>
<span class="hljs-comment"># 2 x 3 = 6</span>
<span class="hljs-comment"># 2 x 4 = 8</span>
<span class="hljs-comment"># 2 x 5 = 10</span>
<span class="hljs-comment"># 2 x 6 = 12</span>
<span class="hljs-comment"># 2 x 7 = 14</span>
<span class="hljs-comment"># 2 x 8 = 16</span>
<span class="hljs-comment"># 2 x 9 = 18</span>
<span class="hljs-comment"># 2 x 10 = 20</span>
<span class="hljs-comment">#</span>
<span class="hljs-comment"># 3 x 1 = 3</span>
<span class="hljs-comment"># 3 x 2 = 6</span>
<span class="hljs-comment"># 3 x 3 = 9</span>
<span class="hljs-comment"># 3 x 4 = 12</span>
<span class="hljs-comment"># 3 x 5 = 15</span>
<span class="hljs-comment"># 3 x 6 = 18</span>
<span class="hljs-comment"># 3 x 7 = 21</span>
<span class="hljs-comment"># 3 x 8 = 24</span>
<span class="hljs-comment"># 3 x 9 = 27</span>
<span class="hljs-comment"># 3 x 10 = 30</span>
<span class="hljs-comment">#</span>
<span class="hljs-comment"># 4 x 1 = 4</span>
<span class="hljs-comment"># 4 x 2 = 8</span>
<span class="hljs-comment"># 4 x 3 = 12</span>
<span class="hljs-comment"># 4 x 4 = 16</span>
<span class="hljs-comment"># 4 x 5 = 20</span>
<span class="hljs-comment"># 4 x 6 = 24</span>
<span class="hljs-comment"># 4 x 7 = 28</span>
<span class="hljs-comment"># 4 x 8 = 32</span>
<span class="hljs-comment"># 4 x 9 = 36</span>
<span class="hljs-comment"># 4 x 10 = 40</span>
<span class="hljs-comment">#</span>
<span class="hljs-comment"># 5 x 1 = 5</span>
<span class="hljs-comment"># 5 x 2 = 10</span>
<span class="hljs-comment"># 5 x 3 = 15</span>
<span class="hljs-comment"># 5 x 4 = 20</span>
<span class="hljs-comment"># 5 x 5 = 25</span>
<span class="hljs-comment"># 5 x 6 = 30</span>
<span class="hljs-comment"># 5 x 7 = 35</span>
<span class="hljs-comment"># 5 x 8 = 40</span>
<span class="hljs-comment"># 5 x 9 = 45</span>
<span class="hljs-comment"># 5 x 10 = 50</span>
</code></pre>
<p>To be honest, this is a very simple bit of code that makes use of a lot of the things you've already learned in this handbook.</p>
<p>To create a multiplication table we need two operands: one remains constant for the entire table and the other increases by 1 until it reaches 10. </p>
<p>Here, <code>x</code> represents the left operand or the constant one and <code>y</code> represents the right operand or the variable one.</p>
<p>The first loop iterates through a range of 1 to 5 and the second loop iterates through a range of 1 to 10.</p>
<p>Since the ending number of a range is exclusive, you need to put a number that is 1 higher than the desired ending number.</p>
<p>First the Python interpreter encounters the outer loop and starts executing it. While inside that loop, the value of <code>x</code> is 1.</p>
<p>The interpreter then encounters the inner loop and starts executing that. While inside the inner loop, the value of <code>x</code> remains 1 but the value of <code>y</code> increases in each iteration.</p>
<p>The inner loop is the body of the outer loop in this case, so the first iteration of the outer loop lasts until the inner loop finishes.</p>
<p>After finishing 10 iterations of the inner loop, the interpreter comes back to the outer loop and starts executing it once again.</p>
<p>This time the value of <code>x</code> becomes 2 since that's what comes next in the range.</p>
<p>Just like that, the outer loop executes 5 times and the inner loop executes 10 times for each of those iterations.</p>
<p>Like a lot of other concepts, wrapping your head around nested loops can be difficult, but practice will make things easier.</p>
<p>I'd suggest you go ahead and implement this program using <code>while</code> loops to test your understanding.</p>
<p>You can also take the two numbers from the user and print the multiplication table within that range.</p>
<p>For example, if the user puts 5 and 10 as inputs, then you'll print out the multiplication tables of all the numbers from 5 to 10.</p>
<p>You can nest loops to even deeper levels, but going deeper than two loops may cause performance issues so be careful with that.</p>
<h2 id="heading-what-are-some-common-sequence-type-operations-in-python">What Are Some Common Sequence Type Operations in Python?</h2>
<p>Assuming you remember the text sequence type (strings), you're now familiar with the four most popular Python sequence types.</p>
<p>So I think it's time for you to learn some common operations that you can perform on them. Let's begin, shall we?</p>
<h3 id="heading-how-to-use-the-in-operator-in-python">How to Use the <code>in</code> Operator in Python</h3>
<p>The <code>in</code> operator is the most common way of checking for any object's existence. For example, assume that you have a string and you want to check if it contains the word "red" or not.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    a_string = <span class="hljs-string">'Little Red Riding-Hood comes to me one Christmas Eve to give me information of the cruelty and '</span> \
               <span class="hljs-string">'treachery of that dissembling Wolf who ate her grandmother. '</span>

    print(<span class="hljs-string">'Red'</span> <span class="hljs-keyword">in</span> a_string)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># True</span>
</code></pre>
<p>It's literally like asking Python, if the word <code>Red</code> is <code>in</code> the <code>a_string</code> variable. And Python will give you either <code>True</code> or <code>False</code> as an answer.</p>
<p>The <code>in</code> operator is not exclusive to strings. You can actually use it on any other collection type such as lists, tuples, and ranges.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Frankenstein'</span>, <span class="hljs-string">'The Omen'</span>, <span class="hljs-string">'The Exorcist'</span>, <span class="hljs-string">'The Legend of Sleepy Hollow'</span>]
    movies = (<span class="hljs-string">'A Christmas Carol'</span>, <span class="hljs-string">'The Sea Beast'</span>, <span class="hljs-string">'Enchanted'</span>, <span class="hljs-string">'Pinocchio'</span>, <span class="hljs-string">'The Addams Family'</span>)
    numbers = range(<span class="hljs-number">10</span>)

    print(<span class="hljs-string">'A Christmas Carol'</span> <span class="hljs-keyword">in</span> books)
    print(<span class="hljs-string">'Enchanted'</span> <span class="hljs-keyword">in</span> movies)
    print(<span class="hljs-number">5</span> <span class="hljs-keyword">in</span> numbers)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># False</span>
<span class="hljs-comment"># True</span>
<span class="hljs-comment"># True</span>
</code></pre>
<p>A Christmas Carol doesn't exist in the <code>books</code> list so it's a <code>False</code> statement. The other two statements are right, so they're <code>True</code>.</p>
<p>You may also want to find out about the absence of an object. For that, you can use the <code>not</code> operator in conjunction with the <code>in</code> operator.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Frankenstein'</span>, <span class="hljs-string">'The Omen'</span>, <span class="hljs-string">'The Exorcist'</span>, <span class="hljs-string">'The Legend of Sleepy Hollow'</span>]
    movies = (<span class="hljs-string">'A Christmas Carol'</span>, <span class="hljs-string">'The Sea Beast'</span>, <span class="hljs-string">'Enchanted'</span>, <span class="hljs-string">'Pinocchio'</span>, <span class="hljs-string">'The Addams Family'</span>)
    numbers = range(<span class="hljs-number">10</span>)

    print(<span class="hljs-string">'A Christmas Carol'</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> books)
    print(<span class="hljs-string">'Enchanted'</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> movies)
    print(<span class="hljs-number">15</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> numbers)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># True</span>
<span class="hljs-comment"># False</span>
<span class="hljs-comment"># True</span>
</code></pre>
<p>A Christmas Carol doesn't exist in the <code>books</code> list, so the first statement evaluates to <code>true</code>. The second one evaluates to false because Enchanted is present in the <code>movies</code> list.</p>
<p>The last one is self explanatory at this point. The <code>in</code> and <code>not in</code> operators come in very handy when working with conditional statements.</p>
<h3 id="heading-how-to-use-the-and-operators-with-sequence-types-in-python">How to Use the <code>+</code> and <code>*</code> Operators with Sequence Types in Python</h3>
<p>You've already learned about <code>+</code> and <code>*</code> as arithmetic operators – but in the case of sequence types, they play a very different role.</p>
<p>The <code>+</code> operator lets you merge two sequences together.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Frankenstein'</span>, <span class="hljs-string">'The Omen'</span>, <span class="hljs-string">'The Exorcist'</span>, <span class="hljs-string">'The Legend of Sleepy Hollow'</span>]
    more_books = [<span class="hljs-string">'And Then There Were None'</span>, <span class="hljs-string">'The ABC Murders'</span>, <span class="hljs-string">'The Valley of Fear'</span>, <span class="hljs-string">'The Hound of the Baskervilles'</span>, <span class="hljs-string">'The Chestnut Man'</span>]


    print(books + more_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ['Dracula', 'Frankenstein', 'The Omen', 'The Exorcist', 'The Legend of Sleepy Hollow', 'And Then There Were None', 'The ABC Murders', 'The Valley of Fear', 'The Hound of the Baskervilles', 'The Chestnut Man']</span>
</code></pre>
<p>As you can see, the operator has appended the content of the <code>books</code> list to the content of the <code>more_books</code> list.</p>
<p>The <code>*</code> operator, on the other hand, makes multiple copies of a given sequence.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Frankenstein'</span>, <span class="hljs-string">'The Omen'</span>, <span class="hljs-string">'The Exorcist'</span>, <span class="hljs-string">'The Legend of Sleepy Hollow'</span>]


    print(books * <span class="hljs-number">2</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ['Dracula', 'Frankenstein', 'The Omen', 'The Exorcist', 'The Legend of Sleepy Hollow', 'Dracula', 'Frankenstein', 'The Omen', 'The Exorcist', 'The Legend of Sleepy Hollow']</span>
</code></pre>
<p>So multiplying the <code>books</code> list by 2 gives us all the 5 books in the list twice. These operators work the same for tuples, strings, ranges or any other sequence types.</p>
<h3 id="heading-how-to-use-the-len-min-and-max-functions-in-python">How to Use the <code>len()</code>, <code>min()</code>, and <code>max()</code> Functions in Python</h3>
<p>The <code>len()</code> function can return the length of a given sequence. And the <code>min()</code> and <code>max()</code> functions can return the minimum and maximum value in a given sequence, respectively.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    random_numbers = [<span class="hljs-number">6</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">8</span>, <span class="hljs-number">0</span>]


    print(len(random_numbers))
    print(min(random_numbers))
    print(max(random_numbers))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 5</span>
<span class="hljs-comment"># 0</span>
<span class="hljs-comment"># 8</span>
</code></pre>
<p>Since there are 5 elements in the list, 5 is the output from the <code>len()</code> function call. </p>
<p>The smallest value in the list is 0 and the largest value is 8 which are the outputs from the <code>min()</code> and <code>max()</code> function calls, respectively.</p>
<p>Depending on the type of programs you end up writing in the future, these three functions can prove to be some of the most useful ones.</p>
<h2 id="heading-what-are-some-string-type-operations-in-python">What Are Some String Type Operations in Python?</h2>
<p>In the previous section, you've learned about some common operations that you can perform on any sequence type including strings.</p>
<p>However, the text sequence type aka strings have some special operations available to them.</p>
<p>In this chapter I'll introduce you to some of the most common string methods. Keep in mind that this is not a definitive list.</p>
<p>Although each of the methods I'm going to teach you performs a different task, they have one thing in common. None of them modifies a given string variable in place, but rather returns a new, modified copy.</p>
<p>If you want to learn about all the available string methods, feel free to consult the official Python documentation.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://docs.python.org/3/library/stdtypes.html#string-methods">https://docs.python.org/3/library/stdtypes.html#string-methods</a></div>
<p>Also remember it's not a matter of just going through each method and memorizing their usage.</p>
<p>It's about knowing what works best in a given scenario and coming up with clever solutions. And that requires practice.</p>
<h3 id="heading-how-to-capitalize-strings-in-python">How to Capitalize Strings in Python</h3>
<p>The first method you're going to learn is called <code>capitalize()</code> and it does what it sounds like.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    country_name = <span class="hljs-string">'bangladesh'</span>

    print(country_name.capitalize())


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Bangladesh</span>
</code></pre>
<p>As you can see from the code snippet above, the <code>capitalize()</code> method turns the first letter of the word to a capital letter.</p>
<p>This is simple, but let's try this on a string with multiple words in it – a sentence perhaps.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">'the house of silk'</span>

    print(book_name.capitalize())


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># The house of silk</span>
</code></pre>
<p>Although the method did its job, there is slight problem. Depending on what you're trying to achieve, you may expect the first letter of each word to be capitalized.</p>
<p>That's where the <code>title()</code> method comes in. This method returns a title cased version of a given string.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">'the house of silk'</span>

    print(book_name.title())


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># The House Of Silk</span>
</code></pre>
<p>But there is still an issue. Take the following string with apostrophes for example.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">"alice's adventures in wonderland"</span>

    print(book_name.title())


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Alice'S Adventures In Wonderland</span>
</code></pre>
<p>As you can see, the <code>title()</code> method treats the <code>s</code> following the apostrophe as a separate word and capitalizes it.</p>
<p>Regarding this issue, the <a target="_blank" href="https://docs.python.org/3/library/stdtypes.html#str.title">official documentation</a> states:</p>
<blockquote>
<p>The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries.</p>
</blockquote>
<p>The <code>capwords()</code> helper function can solve this issue. This function breaks the string into multiple words based on the spaces between them, capitalizes the words, joins them back into a string and returns that to the user.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> string <span class="hljs-keyword">import</span> capwords


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">"alice's adventures in wonderland"</span>

    print(capwords(book_name))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Alice's Adventures In Wonderland</span>
</code></pre>
<p>Pay attention to the <code>import</code> statement at the top. The <code>capwords()</code> function is not a method within the string type but a function that resides inside the <code>string</code> module.</p>
<p>You'll learn about modules and imports in more details later on. For now, just roll with it. Although the function uses spaces to split words, you can overwrite it.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> string <span class="hljs-keyword">import</span> capwords


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    address = <span class="hljs-string">'house 42, road 02, wonderland'</span>

    print(capwords(address, <span class="hljs-string">', '</span>))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># House 42, Road 02, Wonderland</span>
</code></pre>
<p>As you can see, in this case the string has multiple parts divided by a comma followed by a space.</p>
<p>The <code>capwords()</code> function can take a custom delimiter as its second parameter. You can pass any string as the delimiter.</p>
<p>Finally, there is the <code>istitle()</code> method that can check whether a given string is in title case or not.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">'hearts in atlantis'</span>

    print(<span class="hljs-string">f'Is "<span class="hljs-subst">{book_name}</span>" in title case? <span class="hljs-subst">{book_name.istitle()}</span>'</span>)
    print(<span class="hljs-string">f'Is "<span class="hljs-subst">{book_name.title()}</span>" in title case? <span class="hljs-subst">{book_name.title().istitle()}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Is "hearts in atlantis" in title case? False</span>
<span class="hljs-comment"># Is "Hearts In Atlantis" in title case? True</span>
</code></pre>
<p>However, keep in mind that the <code>istitle()</code> method doesn't work with the <code>capwords()</code> helper function.</p>
<h3 id="heading-how-to-convert-strings-to-lower-case-or-upper-case-in-python">How to Convert Strings to Lower Case or Upper Case in Python</h3>
<p>Apart from capitalization, you may want to convert an entire string to upper case or lower case. You can do that by using the <code>upper()</code> and <code>lower()</code> methods in Python.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">'moriarty'</span>

    print(book_name.upper())

    another_book_name = <span class="hljs-string">'DRACULA'</span>

    print(another_book_name.lower())


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># MORIARTY</span>
<span class="hljs-comment"># dracula</span>
</code></pre>
<p>There are also the <code>isupper()</code> and <code>islower()</code> methods to check whether a given string is already in either of the letter cases or not.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">'moriarty'</span>

    print(book_name)
    print(<span class="hljs-string">f'Is <span class="hljs-subst">{book_name}</span> in upper case? <span class="hljs-subst">{book_name.isupper()}</span>'</span>)
    print(<span class="hljs-string">f'Is <span class="hljs-subst">{book_name}</span> in lower case? <span class="hljs-subst">{book_name.islower()}</span>'</span>)

    another_book_name = <span class="hljs-string">'DRACULA'</span>

    print(another_book_name)
    print(<span class="hljs-string">f'Is <span class="hljs-subst">{another_book_name}</span> in upper case? <span class="hljs-subst">{another_book_name.islower()}</span>'</span>)
    print(<span class="hljs-string">f'Is <span class="hljs-subst">{another_book_name}</span> in lower case? <span class="hljs-subst">{another_book_name.isupper()}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># moriarty</span>
<span class="hljs-comment"># Is moriarty in upper case? False</span>
<span class="hljs-comment"># Is moriarty in lower case? True</span>
<span class="hljs-comment"># DRACULA</span>
<span class="hljs-comment"># Is DRACULA in upper case? True</span>
<span class="hljs-comment"># Is DRACULA in lower case? False</span>
</code></pre>
<p>There is one last method called <code>casefold()</code> which is kind of a more aggressive version of the <code>lower()</code> method.</p>
<p>According to the <a target="_blank" href="https://docs.python.org/3/library/stdtypes.html#str.casefold">official documentation</a>:</p>
<blockquote>
<p>Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to 'ß'; casefold() converts it to "ss".</p>
</blockquote>
<p>The usage of this method is identical to the <code>lower()</code> method.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">'DRACULA'</span>

    print(book_name.casefold())


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># dracula</span>
</code></pre>
<p>These three methods are fine and dandy, but what if you don't want to use any of these particular methods and just want to switch the case of a given string?</p>
<p>The <code>swapcase()</code> method can do just that.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">'HEARTS IN ATLANTIS'</span>

    print(book_name.swapcase())


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># hearts in atlantis</span>
</code></pre>
<p>As you can see, the method has converted the book name into lower case from upper case.</p>
<h3 id="heading-how-to-count-the-number-of-occurrences-of-a-substring-in-a-string-in-python">How to Count the Number of Occurrences of a Substring in a String in Python</h3>
<p>If you want to find out the number of occurrences of a substring within a string, you can use the <code>count()</code> method in Python.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    paragraph = <span class="hljs-string">'''At three in the morning the chief Sussex detective, obeying the urgent call from Sergeant Wilson of 
    Birlstone, arrived from headquarters in a light dog-cart behind a breathless trotter. By the five-forty train in 
    the morning he had sent his message to Scotland Yard, and he was at the Birlstone station at twelve o'clock to 
    welcome us. White Mason was a quiet, comfortable-looking person in a loose tweed suit, with a clean-shaved, 
    ruddy face, a stoutish body, and powerful bandy legs adorned with gaiters, looking like a small farmer, 
    a retired gamekeeper, or anything upon earth except a very favourable specimen of the provincial criminal 
    officer.'''</span>

    substring = <span class="hljs-string">'morning'</span>

    print(<span class="hljs-string">f'The substring "<span class="hljs-subst">{substring}</span>" shows up <span class="hljs-subst">{paragraph.count(substring)}</span> times in the paragraph.'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># The substring "morning" shows up 2 times in the paragraph.</span>
</code></pre>
<p>If you call the <code>count()</code> method without passing anything to it, the method will return the number of empty spaces in the given string.</p>
<h3 id="heading-how-to-split-and-join-strings-in-python">How to Split and Join Strings in Python</h3>
<p>You can actually break a string into a list of words or join a list of words in a string in Python.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    string = <span class="hljs-string">'Holmes was certainly not a difficult man to live with'</span>

    word_list = string.split()

    print(word_list)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ['Holmes', 'was', 'certainly', 'not', 'a', 'difficult', 'man', 'to', 'live', 'with']</span>
</code></pre>
<p>If you call the <code>split()</code> method without any parameters, it'll split the given string into words using the spaces as separators.</p>
<p>You can override that by passing a custom separator and also fix the number of splits you want.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    string = <span class="hljs-string">'Holmes,was,certainly,not,a,difficult,man,to,live,with'</span>

    word_list = string.split(<span class="hljs-string">','</span>, <span class="hljs-number">5</span>)

    print(word_list)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ['Holmes', 'was', 'certainly', 'not', 'a', 'difficult,man,to,live,with']</span>
</code></pre>
<p>This time I've replaced the spaces in the source string with commas. I've also overridden the default separator with a comma and fixed the number of splits to five.</p>
<p>As you can see in the output, there are five splits and the rest of the string is kept unchanged as the sixth element in the list.</p>
<p>The <code>split()</code> method is good for using with data that has been intentionally delimited. Using it with natural text with punctuation may produce unexpected results.</p>
<p>The opposite of the <code>split()</code> method is <code>join()</code> and it works on any iterator type in Python.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    word_list = [<span class="hljs-string">'Holmes'</span>, <span class="hljs-string">'was'</span>, <span class="hljs-string">'certainly'</span>, <span class="hljs-string">'not'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'difficult'</span>, <span class="hljs-string">'man'</span>, <span class="hljs-string">'to'</span>, <span class="hljs-string">'live'</span>, <span class="hljs-string">'with'</span>]
    string = <span class="hljs-string">''</span>

    string = string.join(word_list)

    print(string)

    word_list = [<span class="hljs-string">'Holmes '</span>, <span class="hljs-string">'was '</span>, <span class="hljs-string">'certainly '</span>, <span class="hljs-string">'not '</span>, <span class="hljs-string">'a '</span>, <span class="hljs-string">'difficult '</span>, <span class="hljs-string">'man '</span>, <span class="hljs-string">'to '</span>, <span class="hljs-string">'live '</span>, <span class="hljs-string">'with'</span>]
    string = <span class="hljs-string">''</span>

    string = string.join(word_list)

    print(string)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Holmeswascertainlynotadifficultmantolivewith</span>
<span class="hljs-comment"># Holmes was certainly not a difficult man to live with</span>
</code></pre>
<p>There you have it. Notice how the <code>join()</code> method didn't care about adding spaces as separator after each word in the first call.</p>
<p>So I appended a space with each word in the list and in the second call the line has become much more readable.</p>
<h2 id="heading-how-to-write-conditional-statements-in-python">How to Write Conditional Statements in Python</h2>
<p>This is where it gets interesting. In Python or in any other programming language you can make decisions based on conditions.</p>
<p>I hope you remember the <code>boolean</code> data type from a previous section – the one that can only hold <code>True</code> or <code>False</code> values.</p>
<p>Well, you can use a boolean with an <code>if</code> statement (a conditional statement) in Python to perform an action conditionally.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    number = int(input(<span class="hljs-string">'what number would you like to check?\n- '</span>))

    <span class="hljs-keyword">if</span> number % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>:
        print(<span class="hljs-string">f"<span class="hljs-subst">{number}</span> is even."</span>)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">f"<span class="hljs-subst">{number}</span> is odd."</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># what number would you like to check?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># 10 is even.</span>
</code></pre>
<p>You start by writing out <code>if</code> followed by a condition and a colon. By condition, what I mean is a statement that evaluates to a boolean value (true or false).</p>
<p>You've been using the <code>==</code> operator since the beginning and already know that it checks whether the value on the left side of it is equal to the one in the right or not.</p>
<p>So, if you divide a given number by 2 and the remainder is 0, that's an even number – otherwise, it'll be odd.</p>
<p>You can use the <code>if...else</code> statement to choose between two different options. But, if you have multiple options to choose from, you can use the <code>if...elif...else</code> statement.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    year = int(input(<span class="hljs-string">'which year would you like to check?\n- '</span>))

    <span class="hljs-keyword">if</span> year % <span class="hljs-number">400</span> == <span class="hljs-number">0</span> <span class="hljs-keyword">and</span> year % <span class="hljs-number">100</span> == <span class="hljs-number">0</span>:
        print(<span class="hljs-string">f"<span class="hljs-subst">{year}</span> is leap year."</span>)
    <span class="hljs-keyword">elif</span> year % <span class="hljs-number">4</span> == <span class="hljs-number">0</span> <span class="hljs-keyword">and</span> year % <span class="hljs-number">100</span> != <span class="hljs-number">0</span>:
        print(<span class="hljs-string">f"<span class="hljs-subst">{year}</span> is leap year."</span>)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">f"<span class="hljs-subst">{year}</span> is not leap year."</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># which year would you like to check?</span>
<span class="hljs-comment"># - 2004</span>
<span class="hljs-comment"># 2004 is leap year.</span>
</code></pre>
<p>The <code>elif</code> statement usually goes after an <code>if</code> statement and before an <code>else</code> statement.</p>
<p>Think of it like "else if", so if the <code>if</code> statement fails, then the <code>elif</code> will take over. You write it exactly like a regular <code>if</code> statement.</p>
<p>Another new thing in this example is the <code>and</code> operator. It's one of the logical operators in Python. It does what it does in real life.</p>
<p>If the expressions on both sides of the <code>and</code> statement evaluates to <code>true</code>, then the whole expression evaluates to <code>true</code>. Simple.</p>
<p>Don't worry if you do not understand the <code>and</code> operator in detail at the moment. You'll learn about it and its siblings in the very next section.</p>
<p>Another thing you need to understand is that these <code>if</code> statements are just regular statements so you can do pretty much anything inside them.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    number = int(input(<span class="hljs-string">'what number would you like to check?\n- '</span>))

    is_not_prime = <span class="hljs-literal">False</span>

    <span class="hljs-keyword">if</span> number == <span class="hljs-number">1</span>:
        print(<span class="hljs-string">f"<span class="hljs-subst">{number}</span> is not a prime number."</span>)
    <span class="hljs-keyword">elif</span> number &gt; <span class="hljs-number">1</span>:
        <span class="hljs-keyword">for</span> n <span class="hljs-keyword">in</span> range(<span class="hljs-number">2</span>, number):
            <span class="hljs-keyword">if</span> (number % n) == <span class="hljs-number">0</span>:
                is_not_prime = <span class="hljs-literal">True</span>
                <span class="hljs-keyword">break</span>

        <span class="hljs-keyword">if</span> is_not_prime:
            print(<span class="hljs-string">f"<span class="hljs-subst">{number}</span> is not a prime number."</span>)
        <span class="hljs-keyword">else</span>:
            print(<span class="hljs-string">f"<span class="hljs-subst">{number}</span> is a prime number."</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># what number would you like to check?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># 10 is not a prime number.</span>
</code></pre>
<p>This example is a bit more complex than what you've seen so far. So let me break it down for you. The program checks whether a given number is a prime number or not.</p>
<p>First, you take a number from the user. For a number to be prime, it has to be divisible only by 1 and itself. Since 1 is only divisible by 1, it's not a prime number.</p>
<p>Now, if the given number is larger than 1, then you'd have to divide the number with all the numbers from 2 to that particular number.</p>
<p>If the number is divisible by any of these numbers, then you'll turn the <code>is_not_prime</code> variable to <code>True</code>, and <code>break</code> the loop.</p>
<p>The <code>break</code> statement simply breaks out of a loop immediately. There is also the <code>continue</code> statement that can skip the current iteration instead of breaking out.</p>
<p>Finally, if the <code>is_not_prime</code> variable is <code>True</code> then the number is not prime, otherwise it's a prime number.</p>
<p>So as you can see, not only you can put loops inside a conditional statement but also put conditional statements inside a loop.</p>
<p>The final example that I'd like to show you is the <code>for...else</code> statement. As you can see in the example above, you have a <code>for</code> statement followed by a <code>if...else</code> statement.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    number = int(input(<span class="hljs-string">'what number would you like to check?\n- '</span>))

    <span class="hljs-keyword">if</span> number == <span class="hljs-number">1</span>:
        print(<span class="hljs-string">f"<span class="hljs-subst">{number}</span> is not a prime number."</span>)
    <span class="hljs-keyword">elif</span> number &gt; <span class="hljs-number">1</span>:
        <span class="hljs-keyword">for</span> n <span class="hljs-keyword">in</span> range(<span class="hljs-number">2</span>, number):
            <span class="hljs-keyword">if</span> (number % n) == <span class="hljs-number">0</span>:
                print(<span class="hljs-string">f"<span class="hljs-subst">{number}</span> is not a prime number."</span>)
                <span class="hljs-keyword">break</span>
        <span class="hljs-keyword">else</span>:
            print(<span class="hljs-string">f"<span class="hljs-subst">{number}</span> is a prime number."</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># what number would you like to check?</span>
<span class="hljs-comment"># - 5</span>
<span class="hljs-comment"># 5 is a prime number.</span>
</code></pre>
<p>If you put an <code>else</code> statement on the same level as a <code>for</code> statement, then Python will execute whatever you put inside that <code>else</code> block as soon as the loop has finished.</p>
<h2 id="heading-what-are-relational-and-logical-operators-in-python">What are Relational and Logical Operators in Python?</h2>
<p>In the examples above, you've seen the usage of <code>==</code> as well as the <code>and</code> operators. In this section, you'll learn about them in detail.</p>
<p>The relational operators come in handy when you want to check the relationship between two operands. There are six of these operators:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>OPERATOR</td><td>EXPLANATION</td><td>USAGE</td></tr>
</thead>
<tbody>
<tr>
<td><code>==</code></td><td>Equal To</td><td><code>5 == 5</code> gives you <code>True</code>, but <code>5 == 10</code> gives you <code>False</code></td></tr>
<tr>
<td><code>!=</code></td><td>Not Equal To</td><td><code>5 != 10</code> gives you <code>True</code>, but <code>5 != 5</code> gives you <code>False</code></td></tr>
<tr>
<td><code>&gt;</code></td><td>Greater Than</td><td><code>10 &gt; 5</code> gives you <code>True</code>, but <code>5 &gt; 10</code>gives you <code>False</code></td></tr>
<tr>
<td><code>&lt;</code></td><td>Less Than</td><td><code>5 &lt; 10</code> gives you <code>True</code>, but <code>10 &lt; 5</code> gives you <code>False</code></td></tr>
<tr>
<td><code>&gt;=</code></td><td>Greater Than or Equal</td><td><code>10 &gt;= 5</code> and <code>10 &gt;= 10</code> gives you <code>True</code>, but <code>5 &gt;= 10</code> gives you <code>False</code></td></tr>
<tr>
<td><code>&lt;=</code></td><td>Less Than or Equal</td><td><code>5 &lt;= 10</code> and <code>5 &lt;= 5</code> gives you <code>True</code>, but <code>10 &lt;= 5</code> gives you <code>False</code></td></tr>
</tbody>
</table>
</div><p>You've been using the <code>equal to</code> operator since the very beginning. The other ones you'll learn about as you keep going.</p>
<p>Apart from these, there are three logical operators in Python. They are the <code>and</code>, <code>or</code>, and <code>not</code> operators.</p>
<p>Take an RPG game, for example, where the hero has to have a level 45 or up shield and a level 48 or up sword in order to go to the next level.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    shield = int(input(<span class="hljs-string">'what is your shield level? '</span>))
    sword = int(input(<span class="hljs-string">'what is your sword level? '</span>))

    <span class="hljs-keyword">if</span> shield &gt;= <span class="hljs-number">45</span> <span class="hljs-keyword">and</span> sword &gt;= <span class="hljs-number">48</span>:
        print(<span class="hljs-string">'you shall pass!'</span>)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">'you shall not pass!'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># what is your shield level? 42</span>
<span class="hljs-comment"># what is your sword level? 52</span>
<span class="hljs-comment"># you shall not pass!</span>
</code></pre>
<p>Unless you meet both conditions, the statement will evaluate to <code>False</code>. You can have more conditions in a statement like this:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    shield = int(input(<span class="hljs-string">'what is your shield level? '</span>))
    sword = int(input(<span class="hljs-string">'what is your sword level? '</span>))
    armor = int(input(<span class="hljs-string">'what is your armor level? '</span>))

    <span class="hljs-keyword">if</span> shield &gt;= <span class="hljs-number">45</span> <span class="hljs-keyword">and</span> sword &gt;= <span class="hljs-number">48</span> <span class="hljs-keyword">and</span> armor &gt;= <span class="hljs-number">25</span>:
        print(<span class="hljs-string">'you shall pass!'</span>)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">'you shall not pass!'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># what is your shield level? 45</span>
<span class="hljs-comment"># what is your sword level? 50</span>
<span class="hljs-comment"># what is your armor level? 10</span>
<span class="hljs-comment"># you shall not pass!</span>
</code></pre>
<p>The <code>or</code> operator, on the other hand, is a bit more forgiving. If any of the given conditions evaluates true, than the entire statement will evaluate to true.</p>
<p>For example in another horror game, you can only get into The Castle Dracula if you are more than 500,000 years old or legally dead.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    age = <span class="hljs-number">10</span>_000
    is_legally_dead = <span class="hljs-literal">True</span>

    <span class="hljs-keyword">if</span> is_legally_dead <span class="hljs-keyword">or</span> age &gt; <span class="hljs-number">500</span>_000:
        print(<span class="hljs-string">'you shall pass!'</span>)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">'you shall not pass!'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># you shall pass!</span>
</code></pre>
<p>You can mix the <code>and</code> and <code>or</code> operators together. I won't list out all the possible combinations of these operators, but as you keep working with Python, you'll get to use a lot of them.</p>
<p>The last logical operator that I'd like to discuss is the <code>not</code> operator. This operator takes only one operand and returns the opposite value.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(<span class="hljs-string">'not True ='</span>, <span class="hljs-keyword">not</span> <span class="hljs-literal">True</span>)
    print(<span class="hljs-string">'not False ='</span>, <span class="hljs-keyword">not</span> <span class="hljs-literal">False</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># not True = False</span>
<span class="hljs-comment"># not False = True</span>
</code></pre>
<p>For example, if you change the rules of the horror game we talked about in the previous example and make is so that only people who are over 500,000 years old and not Van Helsing can enter the castle.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    age = <span class="hljs-number">800</span>_000
    is_van_helsing = <span class="hljs-literal">True</span>

    <span class="hljs-keyword">if</span> age &gt; <span class="hljs-number">500</span>_000 <span class="hljs-keyword">and</span> <span class="hljs-keyword">not</span> is_van_helsing:
        print(<span class="hljs-string">'you shall pass!'</span>)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">'you shall not pass!'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># you shall not pass!</span>
</code></pre>
<p>Since we've been talking about conditional statements and some of the operators associated with them, I'd like to introduce you to another statement first introduced in Python 3.10, the <code>match...case</code> statement.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.freecodecamp.org/news/python-switch-statement-switch-case-example/">https://www.freecodecamp.org/news/python-switch-statement-switch-case-example/</a></div>
<p>Since my colleague <a target="_blank" href="https://www.freecodecamp.org/news/author/kolade/">Kolade Chris</a> has written such a nice article on the topic, I'll not repeat that here. Feel free to check it out at your leisure.</p>
<h2 id="heading-what-are-assignment-operators-in-python">What Are Assignment Operators in Python?</h2>
<p>You've already encountered the simple assignment operator which is the <code>=</code> sign you used to assign a value to a variable.</p>
<p>Now there are a few variations to this operator that you can use to perform arithmetic and bitwise operations while also assigning a value.</p>
<p>Bitwise operations are a little out of the scope of this book, so I'll stick to the arithmetic operations.</p>
<p>There are seven different assignment operators in Python. Since you've already learned about the simple one, I'll discuss the other six in the following table.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>OPERATOR</td><td>USAGE</td><td>EQUIVALENT TO</td></tr>
</thead>
<tbody>
<tr>
<td><code>+=</code></td><td><code>a += b</code></td><td><code>a = a + b</code></td></tr>
<tr>
<td><code>-=</code></td><td><code>a -= b</code></td><td><code>a = a - b</code></td></tr>
<tr>
<td><code>*=</code></td><td><code>a *= b</code></td><td><code>a = a * b</code></td></tr>
<tr>
<td><code>/=</code></td><td><code>a /= b</code></td><td><code>a = a / b</code></td></tr>
<tr>
<td><code>%=</code></td><td><code>a %= b</code></td><td><code>a = a % b</code></td></tr>
<tr>
<td><code>**=</code></td><td><code>a **= b</code></td><td><code>a = a ** b</code></td></tr>
</tbody>
</table>
</div><p>These operators are not exclusive to Python, and in most programming resources, you'll find these in a much earlier chapter.</p>
<p>But I wanted to wait until you've learned about taking input from the user, working with ranges, and looping through them before introducting them here.</p>
<p>Assume that you want to write a program that calculates the sum of all the numbers within a given range.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    start = int(input(<span class="hljs-string">'which number do you want to start from?\n- '</span>))
    end = int(input(<span class="hljs-string">'which number do you want to stop at?\n- '</span>))

    total = <span class="hljs-number">0</span>

    <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> range(start, end + <span class="hljs-number">1</span>):
        total += number

    print(<span class="hljs-string">f"the sum of the numbers between <span class="hljs-subst">{start}</span> and <span class="hljs-subst">{end}</span> is: <span class="hljs-subst">{total}</span>"</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># which number do you want to start from?</span>
<span class="hljs-comment"># - 1</span>
<span class="hljs-comment"># which number do you want to stop at?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># the sum of the numbers between 1 and 10 is: 55</span>
</code></pre>
<p>I hope you remember that the ending number of a <code>range()</code> function call is exclusive. So I had to add a <code>+1</code> with the ending number.</p>
<p>Otherwise it's a very simple range based for loop that adds each number to the <code>total</code> variable and prints it out once the loop has finished.</p>
<h2 id="heading-what-is-the-set-type-in-python">What Is the Set Type in Python?</h2>
<p>So far you've learned about a number of iterable types such as lists, tuples, and also strings. There is another one known as a set. Let's look at an example:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    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>}

    <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> numbers:
        print(number)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 1</span>
<span class="hljs-comment"># 2</span>
<span class="hljs-comment"># 3</span>
<span class="hljs-comment"># 4</span>
<span class="hljs-comment"># 5</span>
</code></pre>
<p>You can create a new set by putting the values between a set of curly braces. Keep in mind however, you can not create an empty set using the curly braces.</p>
<p>You'll have to use the <code>set()</code> function for that.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    numbers = {}

    print(type(numbers))

    numbers = set()

    print(type(numbers))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># &lt;class 'dict'&gt;</span>
<span class="hljs-comment"># &lt;class 'set'&gt;</span>
</code></pre>
<p>As you can see, usage of empty curly braces creates a dictionary whereas the <code>set()</code> function creates an empty set.</p>
<p>Sets may seem similar to lists, but they are actually quite different. For starters, you can not put duplicate values in a set.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    numbers_list = [<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">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>]

    print(numbers_list)

    numbers_set = set(numbers_list)

    print(numbers_set)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># [1, 2, 3, 4, 5, 3, 2, 4]</span>
<span class="hljs-comment"># {1, 2, 3, 4, 5}</span>
</code></pre>
<p>The list of numbers can hold duplicate values without any problem. But as soon as you create a set from that list, all the duplicate values will be gone.</p>
<p>Sets are mutable, so you can add new values to a set using the <code>add()</code> method.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    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>}

    numbers.add(<span class="hljs-number">500</span>)

    print(numbers)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># {1, 2, 3, 4, 5, 500}</span>
</code></pre>
<p>Likewise you can use the <code>discard()</code> method to remove an item from a set or use the <code>clear()</code> method to remove all values altogether.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    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>}

    numbers.discard(<span class="hljs-number">3</span>)

    print(numbers)

    numbers.clear()

    print(numbers)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># {1, 2, 4, 5}</span>
<span class="hljs-comment"># set()</span>
</code></pre>
<p>Notice how an empty set shows up as <code>set()</code> instead of <code>{}</code> because the latter indicates an empty dictionary.</p>
<p>Apart from the fact that a set never contains duplicate values, there is another speciality of this type.</p>
<p>You can perform set operations such as union, intersection, complement, and  difference using sets in Python.</p>
<p>My colleague <a target="_blank" href="https://www.freecodecamp.org/news/author/estefaniacn/">Estefania Cassingena Navone</a> has written an excellent guide on sets, frozen set and all the operations that you can perform on them.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.freecodecamp.org/news/python-sets-detailed-visual-introduction/">https://www.freecodecamp.org/news/python-sets-detailed-visual-introduction/</a></div>
<p>Finally, if you'd like to get a definitive look at the set type, the <a target="_blank" href="https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset">official documentation</a> will more than suffice.</p>
<h2 id="heading-what-is-the-mapping-type-in-python">What Is the Mapping Type in Python?</h2>
<p>You've already learned about the sequence types and set types in Python. Those are really useful for containing a bunch of data.</p>
<p>But situations where you want to store data in key value pairs are not uncommon. Take, for example, an online bookshop where you have to store the prices of the books.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    programming_books = {
        <span class="hljs-string">'C Programming Language'</span>: <span class="hljs-number">35</span>,
        <span class="hljs-string">'Introduction to Algorithms'</span>: <span class="hljs-number">100</span>,
        <span class="hljs-string">'Clean Code: A Handbook of Agile Software Craftsmanship'</span>: <span class="hljs-number">50</span>
    }

    print(programming_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># {'C Programming Language': 35, 'Introduction to Algorithms': 100, 'Clean Code: A Handbook of Agile Software Craftsmanship': 50}</span>
</code></pre>
<p>The variable <code>programming_books</code> here is a mapping type usually known as a dictionary. Declaring a dictionary is similar to declaring a list or tuple but you use a set of curly braces instead of square braces or parenthesis.</p>
<p>Enclosed within the braces are a bunch of key value pairs. The strings on the left side are the keys and the numbers are the values. You can access any of the keys using the <code>get()</code> method.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    programming_books = {
        <span class="hljs-string">'C Programming Language'</span>: <span class="hljs-number">35</span>,
        <span class="hljs-string">'Introduction to Algorithms'</span>: <span class="hljs-number">100</span>,
        <span class="hljs-string">'Clean Code: A Handbook of Agile Software Craftsmanship'</span>: <span class="hljs-number">50</span>
    }

    cpl = <span class="hljs-string">'C Programming Language'</span>
    algo = <span class="hljs-string">'Introduction to Algorithms'</span>

    print(<span class="hljs-string">f"The price of <span class="hljs-subst">{cpl}</span> is $<span class="hljs-subst">{programming_books.get(cpl)}</span>"</span>)
    print(<span class="hljs-string">f"The price of <span class="hljs-subst">{algo}</span> is $<span class="hljs-subst">{programming_books[algo]}</span>"</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># The price of C Programming Language is $35</span>
<span class="hljs-comment"># The price of Introduction to Algorithms is $100</span>
</code></pre>
<p>Alternatively, you can also use square braces like you did with lists to access a dictionary item.</p>
<p>Dictionaries are mutable which means you can add new items to them, remove or change existing items.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    programming_books = {
        <span class="hljs-string">'C Programming Language'</span>: <span class="hljs-number">35</span>,
        <span class="hljs-string">'Introduction to Algorithms'</span>: <span class="hljs-number">100</span>,
        <span class="hljs-string">'Clean Code: A Handbook of Agile Software Craftsmanship'</span>: <span class="hljs-number">50</span>
    }

    key = <span class="hljs-string">'C Programming Language'</span>

    programming_books[key] = <span class="hljs-number">45</span>

    programming_books[<span class="hljs-string">'The Pragmatic Programmer'</span>] = <span class="hljs-number">32</span>

    print(programming_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># {'C Programming Language': 45, 'Introduction to Algorithms': 100, 'Clean Code: A Handbook of Agile Software Craftsmanship': 50, 'The Pragmatic Programmer': 32}</span>
</code></pre>
<p>You can change an existing item by accessing the item using the square braces and assign a new value to it. The price of C Programming Language has gone up by $10.</p>
<p>If you put a nonexistent key in between the square braces, then that'll show up as a new item. The price of The Pragmatic Programmer was not in the dictionary before but now it has been added.</p>
<p>For removing an item from a dictionary, you can use the <code>popitem()</code> or the <code>pop()</code> method.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    programming_books = {
        <span class="hljs-string">'C Programming Language'</span>: <span class="hljs-number">35</span>,
        <span class="hljs-string">'Introduction to Algorithms'</span>: <span class="hljs-number">100</span>,
        <span class="hljs-string">'Clean Code: A Handbook of Agile Software Craftsmanship'</span>: <span class="hljs-number">50</span>
    }

    print(programming_books.popitem())

    key = <span class="hljs-string">'C Programming Language'</span>

    print(programming_books.pop(key))

    print(programming_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ('Clean Code: A Handbook of Agile Software Craftsmanship', 50)</span>
<span class="hljs-comment"># 35</span>
<span class="hljs-comment"># {'Introduction to Algorithms': 100}</span>
</code></pre>
<p>The <code>popitem()</code> method removes the last item in the dictionary and returns that as a tuple.</p>
<p>The <code>pop()</code> method, on the other hand, returns the value for a given key and removes the pair.</p>
<p>The final <code>print()</code> function call shows that indeed two items were removed from the dictionary due to the pop calls.</p>
<p>Finally, there is the <code>clear()</code> method that wipes out all the pairs in a given dictionary in one go.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    programming_books = {
        <span class="hljs-string">'C Programming Language'</span>: <span class="hljs-number">35</span>,
        <span class="hljs-string">'Introduction to Algorithms'</span>: <span class="hljs-number">100</span>,
        <span class="hljs-string">'Clean Code: A Handbook of Agile Software Craftsmanship'</span>: <span class="hljs-number">50</span>
    }

    programming_books.clear()

    print(programming_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># {}</span>
</code></pre>
<h3 id="heading-what-are-dictionary-view-objects-in-python">What Are Dictionary View Objects in Python?</h3>
<p>So far in this section, you've seen dictionaries printed out as long comma separated lines between pairs of curly braces – but that's not very readable.</p>
<p>This is where the view objects come in handy. You can call some specific methods on dictionaries and get view objects in return.</p>
<p>The first method that I'm going to discuss is the <code>keys()</code> methods. It returns the keys of a given dictionary and you can loop over them.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    programming_books = {
        <span class="hljs-string">'C Programming Language'</span>: <span class="hljs-number">35</span>,
        <span class="hljs-string">'Introduction to Algorithms'</span>: <span class="hljs-number">100</span>,
        <span class="hljs-string">'Clean Code: A Handbook of Agile Software Craftsmanship'</span>: <span class="hljs-number">50</span>
    }

    <span class="hljs-keyword">for</span> key <span class="hljs-keyword">in</span> programming_books.keys():
        print(key)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># C Programming Language</span>
<span class="hljs-comment"># Introduction to Algorithms</span>
<span class="hljs-comment"># Clean Code: A Handbook of Agile Software Craftsmanship</span>
</code></pre>
<p>Just like the <code>keys()</code> method, there is the <code>values()</code> method that returns the values in a dictionary instead.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    programming_books = {
        <span class="hljs-string">'C Programming Language'</span>: <span class="hljs-number">35</span>,
        <span class="hljs-string">'Introduction to Algorithms'</span>: <span class="hljs-number">100</span>,
        <span class="hljs-string">'Clean Code: A Handbook of Agile Software Craftsmanship'</span>: <span class="hljs-number">50</span>
    }

    <span class="hljs-keyword">for</span> value <span class="hljs-keyword">in</span> programming_books.values():
        print(value)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 35</span>
<span class="hljs-comment"># 100</span>
<span class="hljs-comment"># 50</span>
</code></pre>
<p>Finally, if you want both the keys and the values as tuples, you can use the <code>items</code> method.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    programming_books = {
        <span class="hljs-string">'C Programming Language'</span>: <span class="hljs-number">35</span>,
        <span class="hljs-string">'Introduction to Algorithms'</span>: <span class="hljs-number">100</span>,
        <span class="hljs-string">'Clean Code: A Handbook of Agile Software Craftsmanship'</span>: <span class="hljs-number">50</span>
    }

    <span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> programming_books.items():
        print(item)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ('C Programming Language', 35)</span>
<span class="hljs-comment"># ('Introduction to Algorithms', 100)</span>
<span class="hljs-comment"># ('Clean Code: A Handbook of Agile Software Craftsmanship', 50)</span>
</code></pre>
<h2 id="heading-how-to-write-functions-in-python">How to Write Functions in Python</h2>
<p>A function in Python (and programming in general) is a self-contained collection of instructions that perform a single task.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">print_hello</span>():</span>
    print(<span class="hljs-string">'Hello, World!'</span>)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print_hello()


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, World!</span>
</code></pre>
<p>You define a function by writing out <code>def</code> followed by the name of the funtion and a colon. You can then write the function body from the next indented line.</p>
<p>In this example, the <code>print_hello()</code> prints out <code>Hello, World!</code> on the terminal. It doesn't accept any argument.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">print_hello</span>(<span class="hljs-params">message</span>):</span>
    print(message)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print_hello(<span class="hljs-string">'Hello, Universe!'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, Universe!</span>
</code></pre>
<p>Now instead of printing out <code>Hello, World!</code> all the time, you can pass a custom message for the function to print out.</p>
<p>You can make a function accept multiple arguments and even set a default value for it.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">print_hello</span>(<span class="hljs-params">message, is_lower=False</span>):</span>
    <span class="hljs-keyword">if</span> is_lower:
        print(message.lower())
    <span class="hljs-keyword">else</span>:
        print(message.upper())


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print_hello(<span class="hljs-string">'Hello, Universe!'</span>)
    print_hello(<span class="hljs-string">'Hello, Universe!'</span>, <span class="hljs-literal">True</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># HELLO, UNIVERSE!</span>
<span class="hljs-comment"># hello, universe!</span>
</code></pre>
<p>Setting a default value to a function parameter makes it optional. So if you do not pass a value during the function call, your program will use the default value.</p>
<p>Instead of printing out the message outright, you can make the function return the message.</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">message, is_lower=False</span>):</span>
    <span class="hljs-keyword">if</span> is_lower:
        <span class="hljs-keyword">return</span> message.lower()
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> message.upper()


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(hello(<span class="hljs-string">'Hello, Universe!'</span>))
    print(hello(<span class="hljs-string">'Hello, Universe!'</span>, <span class="hljs-literal">True</span>))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># HELLO, UNIVERSE!</span>
<span class="hljs-comment"># hello, universe!</span>
</code></pre>
<p>Since the function doesn't print out the message anymore, changing its name from <code>print_hello()</code> to just <code>hello()</code> makes more sense.</p>
<p>When you call the function with or without a custom message, the function returns a string that you can then print out within the <code>main()</code> function.</p>
<p>You can also save the message in variables instead of passing them to the <code>print()</code> function directly.</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">message, is_lower=False</span>):</span>
    <span class="hljs-keyword">if</span> is_lower:
        <span class="hljs-keyword">return</span> message.lower()
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> message.upper()


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    uppercase_message = hello(<span class="hljs-string">'Hello, Universe!'</span>)
    print(uppercase_message)

    lowercase_message = hello(<span class="hljs-string">'Hello, Universe!'</span>, <span class="hljs-literal">True</span>)
    print(lowercase_message)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># HELLO, UNIVERSE!</span>
<span class="hljs-comment"># hello, universe!</span>
</code></pre>
<p>It's not that you can only pass singular values to a function. You can pass lists, tuples, dictionaries or any other object to a function.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">total</span>(<span class="hljs-params">numbers</span>):</span>
    s = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> numbers:
        s += number
    <span class="hljs-keyword">return</span> s


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(total([<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>, <span class="hljs-number">10</span>]))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 55</span>
</code></pre>
<p>In this function, you can pass a list of numbers to and get their sum. I had to name the function <code>total()</code> instead of <code>sum()</code> because there is a built-in function with that name.</p>
<p>There is one last concept regarding functions that I'd like to discuss in this section, and that is recursion.</p>
<p>Recursion in Python or programming in general is the technique of making a function call itself to perform a task iteratively.</p>
<p>For example, imagine a function that accepts an integer and calculates the sum of all natural numbers up to that given integer. You can write this program using loops.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">natural_sum</span>(<span class="hljs-params">last_number</span>):</span>
    <span class="hljs-keyword">if</span> last_number &lt; <span class="hljs-number">1</span>:
        <span class="hljs-keyword">return</span> last_number

    total = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, last_number + <span class="hljs-number">1</span>):
        total += number

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


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    last_number = int(input(<span class="hljs-string">'up to which number would you like to calculate the sum?\n- '</span>))

    print(natural_sum(last_number))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># up to which number would you like to calculate the sum?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># 55</span>
</code></pre>
<p>There is nothing new there, just regular usage of a range-based for loop. Now, you can also write the same program without any loop.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">recursive_natural_sum</span>(<span class="hljs-params">last_number</span>):</span>
    <span class="hljs-keyword">if</span> last_number &lt; <span class="hljs-number">1</span>:
        <span class="hljs-keyword">return</span> last_number

    <span class="hljs-keyword">return</span> last_number + recursive_natural_sum(last_number - <span class="hljs-number">1</span>)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    last_number = int(input(<span class="hljs-string">'up to which number would you like to calculate the sum?\n- '</span>))

    print(recursive_natural_sum(last_number))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># up to which number would you like to calculate the sum?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># 55</span>
</code></pre>
<p>At a glance, this piece of code may look very complicated to you. But in reality it's very simple. Let's break it down step by step.</p>
<p>When you call the <code>recursive_natural_sum()</code> function with the value of 10 for the first time, you start a chain reaction of sorts.</p>
<p>Since the value is not less than 1, the <code>if</code> statement evaluates to <code>False</code> and the second <code>return</code> statement gets called.</p>
<p>Inside that <code>return</code> statement, you're calling the <code>recursive_natural_sum()</code> function by passing the value of <code>last_number - 1</code> which is 9 at this point.</p>
<p>You're also adding the returned value from this call to the current value of the <code>last_number</code> variable.</p>
<p>But you'll not get a return value because your inner function call will call itself again with <code>last_number - 1</code> which will be 8 at that point.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/recursion-1.drawio.svg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This calling goes on and on until the value of <code>last_digit</code> becomes zero. Once it becomes zero, the <code>if</code> statement evaluates to <code>True</code> and the function calls start to return a value.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/recursion-2.drawio-1.svg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The value returned from each function call is <code>last_digit + (last_digit - 1)</code> by the end of the recursion chain it adds up to 55.</p>
<p>My colleague <a target="_blank" href="https://www.freecodecamp.org/news/author/beau/">Beau Carnes</a> has written a more in-depth article discussing how recursion works. You may take a look at it if you want to learn more.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.freecodecamp.org/news/how-recursion-works-explained-with-flowcharts-and-a-video-de61f40cb7f9/">https://www.freecodecamp.org/news/how-recursion-works-explained-with-flowcharts-and-a-video-de61f40cb7f9/</a></div>
<p>I'm not sating that recursive functions are easier than loops – but at times, using a recursive function instead of nested loops can be more efficient.</p>
<h3 id="heading-how-to-write-anonymous-or-lambda-functions-in-python">How to Write Anonymous or Lambda Functions in Python</h3>
<p>Anonymous or lambda functions are functions without any name. This is not something exclusive to Python and most of the modern programming languages have some sort of lambda implementation.</p>
<p>Instead of beginning the function declaration with <code>def</code>, you instead start with writing out <code>lambda</code> followed by a colon and the function body.</p>
<pre><code class="lang-python">print_hello = <span class="hljs-keyword">lambda</span>: print(<span class="hljs-string">'Hello, World!'</span>)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print_hello()


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, World!</span>
</code></pre>
<p>Since lambdas do not have a name, you have to put it in a variable in order to access it but that's not recommended. If you need a named function, use <code>def</code> instead.</p>
<p>Lambda functions are useful when you want to pass a function as an argument to another function call. Take the <code>filter()</code> function for example.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_even</span>(<span class="hljs-params">number</span>):</span>
    <span class="hljs-keyword">if</span> number % <span class="hljs-number">2</span> == <span class="hljs-number">0</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>


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">5</span>, <span class="hljs-number">4</span>, <span class="hljs-number">7</span>, <span class="hljs-number">88</span>, <span class="hljs-number">12</span>, <span class="hljs-number">15</span>, <span class="hljs-number">55</span>, <span class="hljs-number">77</span>, <span class="hljs-number">95</span>]

    even_numbers = filter(check_even, numbers)

    print(list(even_numbers))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># [2, 4, 88, 12]</span>
</code></pre>
<p>The <code>filter()</code> function takes a function and an iterable type as its two arguments. The function should describe the logic for filtering and the iterable type will contain the values you want to filter from.</p>
<p>In this code, you have a list of numbers and you want to filter out the odd numbers from that list.</p>
<p>The <code>check_even()</code> function takes a number as argument. It then returns <code>True</code> if the number is divisible by two and <code>False</code> if not.</p>
<p>The <code>filter()</code> function iterates through the list of numbers and passes each number to the <code>check_even()</code> function.</p>
<p>It keeps the number if the <code>check_even()</code> function returns <code>True</code> or discards the number if the <code>check_even()</code> function returns <code>False</code>.</p>
<p>Now this <code>check_even()</code> function doesn't have any purpose other than checking if a given number is divisible by two or not. So you can write it as a lambda.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">5</span>, <span class="hljs-number">4</span>, <span class="hljs-number">7</span>, <span class="hljs-number">88</span>, <span class="hljs-number">12</span>, <span class="hljs-number">15</span>, <span class="hljs-number">55</span>, <span class="hljs-number">77</span>, <span class="hljs-number">95</span>]

    even_numbers = filter(<span class="hljs-keyword">lambda</span> number: <span class="hljs-literal">True</span> <span class="hljs-keyword">if</span> number % <span class="hljs-number">2</span> == <span class="hljs-number">0</span> <span class="hljs-keyword">else</span> <span class="hljs-literal">False</span>, numbers)

    print(list(even_numbers))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># [2, 4, 88, 12]</span>
</code></pre>
<p>This lambda takes an argument named <code>number</code> then returns <code>True</code> if that's divisible by two and <code>False</code> otherwise.</p>
<p>You can add multiple arguments separating each by a comma. Finally a lambda doesn'e need a return statement but you can assume a return.</p>
<p>So <code>True if number % 2 == 0 else False</code> is equivalent to <code>return True if number % 2 == 0 else False</code>. The <code>if...else</code> statement inside the lambda is in short hand form.</p>
<h3 id="heading-how-to-work-with-local-nonlocal-and-global-variables-in-python">How to Work with local, nonlocal and global Variables in Python</h3>
<p>Scope of a variable in Python or programming in general refers to region where that variable is accessible.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">outside</span>():</span>
    message = <span class="hljs-string">'Hello, World!'</span>


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


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># NameError: name 'msg' is not defined</span>
</code></pre>
<p>In this example, the <code>message</code> variable is defined inside the <code>outside()</code> function and there is no existence of it anywhere else.</p>
<p>As a result, when you try to access that variable from the <code>main()</code> function, you get a <code>NameError</code> since the variable is scoped to the <code>outside()</code> function.</p>
<p>Variables like this are called local variables and they only exist within the block they've been declared.</p>
<p>Global variables, on the other hand, are usually declared outside of any particular block of code.</p>
<pre><code class="lang-python">message = <span class="hljs-string">'Hello, World!'</span>


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


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, World!</span>
</code></pre>
<p>As you can see, now the <code>message</code> variable has no indentation and is declared at the top of the function. You could've declared the variable after the <code>main()</code> function.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(message)


message = <span class="hljs-string">'Hello, World!'</span>

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, World!</span>
</code></pre>
<p>This works because you don't try to access the variable until you call the <code>main()</code> function inside the <code>if</code> statement.</p>
<p>Although global variables are accessible pretty much everywhere, it can be a bit tricky to work with if you have a local variable with a similar name.</p>
<pre><code class="lang-python">message = <span class="hljs-string">'Hello, {name}!'</span>


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    message = message.format(name=<span class="hljs-string">'Farhan'</span>)
    print(message)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># UnboundLocalError: local variable 'message' referenced before assignment</span>
</code></pre>
<p>In this code, you have a placeholder for a name inside the <code>message</code> variable. You can use the <code>format()</code> method to put a name there.</p>
<p>But if you try to run this code, you'll get a <code>local variable 'message' referenced before assignment</code> message. In simpler words, you're trying to access a local variable named <code>message</code> before even assigning anything to it.</p>
<p>So clearly, Python is looking for a local variable with the given name instead of accessing the global one. Since it's asking, try giving it a local variable.</p>
<pre><code class="lang-python">message = <span class="hljs-string">'Hello, {name}!'</span>


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    message = str()

    message = message.format(name=<span class="hljs-string">'Farhan'</span>)
    print(message)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()
</code></pre>
<p>This time the error will be gone but you will not get any output in your console. This is because the local <code>message</code> variable is empty and there is no placeholder to put a name in.</p>
<p>This is where the <code>global</code> keyword comes in. Instead of creating a local variable, you can let Python know that you're trying to access the global <code>message</code> variable.</p>
<pre><code class="lang-python">message = <span class="hljs-string">'Hello, {name}!'</span>


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    <span class="hljs-keyword">global</span> message

    message = message.format(name=<span class="hljs-string">'Farhan'</span>)
    print(message)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, Farhan!</span>
</code></pre>
<p>Now, instead of trying to look for a variable named <code>message</code> within the local scope, Python will directly reach out to the global scope.</p>
<p>Finally, there is the <code>nonlocal</code> keyword usually used in nested functions. It solves a similar problem as the <code>global</code> keyword but in a local scope.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name</span>):</span>
    message = <span class="hljs-string">'Hello, {name}!'</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">include_name</span>():</span>
        message = message.format(name=name)

    include_name()
    <span class="hljs-keyword">return</span> message


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(greet(<span class="hljs-string">'Farhan'</span>))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># UnboundLocalError: local variable 'message' referenced before assignment</span>
</code></pre>
<p>In this example, you're dealing with three functions. There is the <code>main()</code> function, there is the <code>greet()</code> function, and inside that is the <code>include_name()</code> function.</p>
<p>The <code>greet()</code> function takes a name as an argument but doesn't include that in the message right away.</p>
<p>Instead it calls the <code>include_name()</code> function defined within its local scope. That's where the problem begins.</p>
<p>You see, the <code>message</code> variable is outside the scope of the <code>include_message()</code> function and that's why you're getting the <code>referenced before assignment</code> error message.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name</span>):</span>
    message = <span class="hljs-string">'Hello, {name}!'</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">include_name</span>():</span>
        <span class="hljs-keyword">global</span> message

        message = message.format(name=name)

    include_name()
    <span class="hljs-keyword">return</span> message


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(greet(<span class="hljs-string">'Farhan'</span>))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># NameError: name 'message' is not defined</span>
</code></pre>
<p>You can't use the <code>global</code> keyword either since the <code>message</code> variable is not defined in the global scope and that's what the error message dictates.</p>
<p>You can use the <code>nonlocal</code> keyword to use variables that are not in the global scope but in the scope of the outer function.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name</span>):</span>
    message = <span class="hljs-string">'Hello, {name}!'</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">include_name</span>():</span>
        <span class="hljs-keyword">nonlocal</span> message
        message = message.format(name=name)

    include_name()
    <span class="hljs-keyword">return</span> message


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(greet(<span class="hljs-string">'Farhan'</span>))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, Farhan!</span>
</code></pre>
<p>Now the <code>include_name()</code> function will look for the <code>message</code> variable within the scope of the <code>greet()</code> function instead of its local scope.</p>
<h3 id="heading-how-to-pass-a-variable-number-of-arguments-to-a-function-using-args-and-kwargs-in-python">How to Pass a Variable Number of Arguments to a Function Using <em>args and *</em>kwargs in Python</h3>
<p>Imagine a function that takes a bunch of numbers as arguments and returns their sum. In a function like this, it'd be nice to have the provision of passing a variable number of arguments.</p>
<p>Surely you can pass the numbers as a tuple or as a list but you may want to pass them as regular arguments separated by commas. You can do that by using <code>*args</code> or non key arguments in Python.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">total</span>(<span class="hljs-params">*args</span>):</span>
    print(type(args))

    t = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> arg <span class="hljs-keyword">in</span> args:
        t += arg

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


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(total(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># &lt;class 'tuple'&gt;</span>
<span class="hljs-comment"># 15</span>
</code></pre>
<p>Here, you can pass an arbitrary number of variables to the <code>total()</code> function as argument and you'll have access to them as a tuple inside that function.</p>
<p>It's not mandatory to name the argument as <code>*args</code><em>,</em> you can call it something more descriptive like <code>_*_numbers</code> or anything else. As long as you put the asterisk in front, you're good to go.</p>
<p>Like <code>*args</code> there is also <code>**kwargs</code> or keyword arguments that will allow you to access the function arguments as a dictionary.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">items</span>(<span class="hljs-params">**kwargs</span>):</span>
    print(type(kwargs))

    <span class="hljs-keyword">for</span> key, value <span class="hljs-keyword">in</span> kwargs.items():
        print(<span class="hljs-string">f"<span class="hljs-subst">{key}</span> : <span class="hljs-subst">{value}</span>"</span>)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    items(
        Apple=<span class="hljs-number">10</span>,
        Orange=<span class="hljs-number">8</span>,
        Grape=<span class="hljs-number">35</span>
    )


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># &lt;class 'dict'&gt;</span>
<span class="hljs-comment"># Apple : 10</span>
<span class="hljs-comment"># Orange : 8</span>
<span class="hljs-comment"># Grape : 35</span>
</code></pre>
<p>In this case, you can pass arbitrary number of key-value pairs and access them as a dictionary inside the <code>items()</code> function.</p>
<p>Just like the the <code>*args</code> keyword, you don't have to absolutely name it <code>**kwargs</code>. Instead you can name it anything you want.</p>
<p>As long as you put the double asterisks at the front, you'll be fine. The <code>items()</code> method within dictionaries lets you iterate through them.</p>
<p>You can also change the names of the <code>key</code> and <code>value</code> variables. A more readable version of the function can be as follows:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">items</span>(<span class="hljs-params">**fruits</span>):</span>
    print(type(fruits))

    <span class="hljs-keyword">for</span> fruit, price <span class="hljs-keyword">in</span> fruits.items():
        print(<span class="hljs-string">f"<span class="hljs-subst">{fruit}</span> : <span class="hljs-subst">{price}</span>"</span>)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    items(
        Apple=<span class="hljs-number">10</span>,
        Orange=<span class="hljs-number">8</span>,
        Grape=<span class="hljs-number">35</span>
    )


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># &lt;class 'dict'&gt;</span>
<span class="hljs-comment"># Apple : 10</span>
<span class="hljs-comment"># Orange : 8</span>
<span class="hljs-comment"># Grape : 35</span>
</code></pre>
<p>Keep in mind that the type of the keys in this case has to be a string and the values can be anything you want.</p>
<h2 id="heading-what-are-modules-in-python">What Are Modules in Python?</h2>
<p>As you project grows, breaking off your code into multiple files becomes a necessity. A module in Python is just a file containing Python code that you can import inside other Python files.</p>
<p>For example, assume that you have a Python project with two files. The first one may be "mathstuff.py" and the other one may be "main.py".</p>
<p>The "mathstuff.py" file can contain stuff related to mathematics, for example a function that sums up all the natural numbers in a range.</p>
<pre><code class="lang-python"><span class="hljs-comment"># mathstuff.py</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">natural_sum</span>(<span class="hljs-params">last_number</span>):</span>
    <span class="hljs-keyword">if</span> last_number &lt; <span class="hljs-number">1</span>:
        <span class="hljs-keyword">return</span> last_number

    total = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, last_number + <span class="hljs-number">1</span>):
        total += number

    <span class="hljs-keyword">return</span> total
</code></pre>
<p>Now you can import this function any other file such as the "main.py" file.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> mathstuff


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    last_number = int(input(<span class="hljs-string">'up to which number would you like to calculate the sum?\n- '</span>))

    print(mathstuff.natural_sum(last_number))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># up to which number would you like to calculate the sum?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># 55</span>
</code></pre>
<p>The <code>import</code> statement, as the name suggests, imports bits of code from another file or module.</p>
<p>It's not uncommon to house more than one function, variable, or other object in a Python module and often times you may want to use only few of them.</p>
<p>You can use the <code>from...import</code> statement in these situations.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> mathstuff <span class="hljs-keyword">import</span> natural_sum


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    last_number = int(input(<span class="hljs-string">'up to which number would you like to calculate the sum?\n- '</span>))

    print(natural_sum(last_number))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># up to which number would you like to calculate the sum?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># 55</span>
</code></pre>
<p>It also saves you from having to write the module name everytime you want to access a function or object living inside that module.</p>
<p>Finally, you can use the <code>as</code> keyword to change the name of an imported module to make that more easily accessible.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> mathstuff <span class="hljs-keyword">as</span> math


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    last_number = int(input(<span class="hljs-string">'up to which number would you like to calculate the sum?\n- '</span>))

    print(math.natural_sum(last_number))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># up to which number would you like to calculate the sum?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># 55</span>
</code></pre>
<p>Also works with the <code>from...import</code> statement.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> mathstuff <span class="hljs-keyword">import</span> natural_sum <span class="hljs-keyword">as</span> nsum


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    last_number = int(input(<span class="hljs-string">'up to which number would you like to calculate the sum?\n- '</span>))

    print(nsum(last_number))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># up to which number would you like to calculate the sum?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># 55</span>
</code></pre>
<p>Importing modules is something that you'll have to do all the time. Apart from modules, there is also the idea of packages.</p>
<p>In these examples, both files are in the same folder. Packages are a nifty little way of keeping related Python modules together in different folders.</p>
<p>For example, in a web framework, you may have a package called <code>framework</code> that houses all the code that comes with this web framework.</p>
<p>Now this <code>framework</code> package can in turn have multiple subpackages – for example there may be a package named <code>http</code> for handling HTTP requests and responses.</p>
<pre><code>├───framework
│   └───http
</code></pre><p>At the moment, these are just regular folders. To turn them into Python, all you need is to create "<strong>init</strong>.py" files inside them.</p>
<pre><code>├───framework
│   │   __init__.py
│   │
│   └───http
│           __init__.py
</code></pre><p>Now these files have turned into packages. These "<strong>init</strong>.py" files will tell the Python import system that these folders are indeed packages.</p>
<p>Finally, to put some code inside the <code>http</code> package, create a file named <code>response.py</code> with the following content:</p>
<pre><code class="lang-python"><span class="hljs-comment"># framework/http/response.py</span>

<span class="hljs-keyword">from</span> json <span class="hljs-keyword">import</span> dumps


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">as_json</span>(<span class="hljs-params">message</span>):</span>
    <span class="hljs-keyword">return</span> dumps({
        <span class="hljs-string">'message'</span>: message
    })
</code></pre>
<p>First, you're importing the <code>dumps</code> function from the <code>json</code> package. These are part of the Python standard library.</p>
<p>The <code>dumps</code> function can turn a Python object like a dictionary into a JSON string, which means the <code>as_json()</code> function returns a given value in JSON format.</p>
<pre><code class="lang-json">{<span class="hljs-attr">"message"</span>: <span class="hljs-string">"Hello, World"</span>}
</code></pre>
<p>Now you can import this function in the "main.py" file.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> framework.http.response <span class="hljs-keyword">import</span> as_json


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(as_json(<span class="hljs-string">'Hello, World!'</span>))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># {"message": "Hello, World"}</span>
</code></pre>
<p>Instead of putting the <code>as_json()</code> function inside another Python file, you can simply put it inside the "framework/http/<strong>init</strong>.py" file.</p>
<p>Then you can update the "main.py" file to use the updated package path.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> framework.http <span class="hljs-keyword">import</span> as_json


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(as_json(<span class="hljs-string">'Hello, World!'</span>))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># {"message": "Hello, World"}</span>
</code></pre>
<p>If you ever try out a framework like Django, you'll see that the framework contains a huge amount of packages, so understanding how the import system works will help you out immensely.</p>
<h2 id="heading-how-to-use-the-python-documentation-efficiently">How to Use the Python Documentation Efficiently</h2>
<p>Since you're now out of infancy as a Python programmer, I'd like to show you how you can browse through the official Python documentation.</p>
<p>You may think, well browsing documentation is not hard and you'd be absolutely right. But it can be daunting at first.</p>
<p>So what I'm going to do is give you a little primer on how I have used the documentation throughout my career.</p>
<p>The first step is to visit <a target="_blank" href="https://docs.python.org/">https://docs.python.org/</a> and you'll automatically land on the documentation for the latest version of Python.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/image-154.png" alt="Image" width="600" height="400" loading="lazy">
<em>Python Documentation (<a target="_blank" href="https://docs.python.org/">https://docs.python.org/</a>)</em></p>
<p>At the time of writing, the latest version of Python is 3.11.4 however I still have version 3.10.11 installed on my computers.</p>
<p>Right from the get go, you can see lots of different links other pages and to be honest, you're not going to need all of them right away.</p>
<p>The best way to find out which link to what page is to to have a look at whichever looks interesting to you.</p>
<p>I'll talk about three links from this page that have helped me immensely. The first one is the "Tutorial" page.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/image-155.png" alt="Image" width="600" height="400" loading="lazy">
<em>The Python Tutorial (https://docs.python.org/3/tutorial/index.html)</em></p>
<p>Back when I was making my shift from C to Python, this is the tutorial I went through. The tutorial starts with an introduction to the Python interpreter.</p>
<p>Then it teaches you topics including but not limited to data types, control flow statements, data structures, modules, error handling, the standard library, and even object oriented programming.</p>
<p>The other page that's extremely useful is the "Glossary" page. It contains a list of all the important terminology that you may come across while working with Python.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/image-156.png" alt="Image" width="600" height="400" loading="lazy">
<em>Glossary (https://docs.python.org/3/glossary.html)</em></p>
<p>So at any point if you feel like that you do not know the meaning of a word, take a look at the glossary.</p>
<p>Finally the "Library Reference" page is a detailed description of everything included in the standard Python library.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/image-158.png" alt="Image" width="600" height="400" loading="lazy">
<em>Library Reference (https://docs.python.org/3/library/index.html)</em></p>
<p>Say, for example, I'd like to learn about the context manager type (which is beyond the scope of this book). I can just look under the "Built-in Types" section.</p>
<p>Or if you want to know about something else such as the JSON package, you can search the library reference for JSON – and sure enough you'll find something on it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/image-159.png" alt="Image" width="600" height="400" loading="lazy">
<em>JSON is under the Internet Data Handling section ()</em></p>
<p>Following the link will land you on the page describing how the JSON package works.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/image-160.png" alt="Image" width="600" height="400" loading="lazy">
<em>JSON encoder and decoder (https://docs.python.org/3/library/json.html)</em></p>
<p>The page not only contains text but also contains practical and very useful code examples.</p>
<p>The official documentation is going to be your most reliable and in-depth source of learning, so the sooner you get used to it the better.</p>
<h2 id="heading-whats-next">What's Next?</h2>
<p>As I've said, this text is not a definitive guide to Python – which means there is still a lot to learn. In this section I'll list out a number of different resources.</p>
<h3 id="heading-object-oriented-programming">Object Oriented Programming</h3>
<p>The first thing that you may want to learn right after finishing this handbook is object oriented programming with Python.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/Ej_02ICOIgs" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>This comprehensive video course is hosted on the freeCodeCamp YouTube channel. It's a little over 2 hours long and covers the essential concepts nicely.</p>
<p>Object Oriented Programming is not just about learning about concepts like classes, objects, and inheritance.</p>
<p>Writing good object oriented code takes a lot of practice and it all begins with the basics. Take your time with this one and make sure to understand everything.</p>
<h3 id="heading-algorithms-and-data-structures">Algorithms and Data Structures</h3>
<p>The second item on the list that you should absolutely learn if you're serious about being an efficient programmer is data structures and algorithms.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/8hly31xKli0" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>Fortunately, the freeCodeCamp YouTube channel hosts a very comprehensive video produced by some of the finest teachers out there on the topic.</p>
<p>The video is a little over 5 hours long and will teach everything you need to know about data structures and algorithms as beginner.</p>
<p>This course is not going to turn you into a better programmer instantly, but it'll teach you a better and more efficient way of thinking about problems.</p>
<h3 id="heading-django">Django</h3>
<p>If you'd like to get into web development using Python, Django is among the most popular choices out there.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/o0XbHvKxw7Y" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>The freeCodeCamp YouTube channel hosts this massive 18 hour long course taught by Dr. Chuck, one of the best teachers in the world.</p>
<p>The course not only teaches Django from the ground up but also a long list of concepts around the web itself.</p>
<p>Having a good understanding of object oriented programming is important before you jump into the world of Django, so make sure you have that.</p>
<h3 id="heading-qt">Qt</h3>
<p>Python may not be the most popular languages for building graphical user interfaces, but it's surprisingly capable on that end, too.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/Z1N9JzNax2k" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>Qt is a very popular cross-platform UI framework and PySide6 is the official Python bindings for Qt 6.</p>
<p>In this 5 hour long course, you'l learn all the fundamentals of creating user interfaces using Qt and create cross-platform, robust software in no time.</p>
<h3 id="heading-pygame">PyGame</h3>
<p>Just like cross-platform graphical user interfaces, Python is not the most popular choice when it comes to game programing.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/R9apl6B_ZgI" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>However, the PyGame library is a very powerful and easy to use library for writing 2D games in Python.</p>
<p>In this almost 7 hour long course on game programming with Python, you'll learn about writing a game that mimicks the very popular Stardew Valley.</p>
<p>Undoubtedly, this is a very challenging video to go through but so is making games. So if you're into gamedev and Python, this may be the course you need.</p>
<h3 id="heading-data-science">Data Science</h3>
<p>Data science is arguably the most popular field where Python plays a huge role. Becoming a data scientist can take years but you gotta start somewhere.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/LHBE6Q9XlzI" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>This 12 hour long course on the freeCodeCamp YouTube channel teaches you a lot about how to use your Python knowledge in data science.</p>
<p>Although the course doesn't go very deep into the realm of data science, it teaches you about a number of very important libraries used regularly in data science.</p>
<p>Near the end of the course, you'll also create a project by applying everything you learn throughout the course.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I would like to thank you from the bottom of my heart for the time you've spent reading this article.</p>
<p>Although I've listed only a small number of courses here, the <a target="_blank" href="https://www.youtube.com/c/Freecodecamp/search?query=python">freeCodeCamp YouTube channel</a> is just filled with excellent Python learning resources.</p>
<p>Keep in mind that this handbook is a living document and I'll update it with from time to time. So bookmarking it maybe a great idea.</p>
<p>I also have a personal blog where I write about random tech stuff, so if you're interested in something like that, checkout <a target="_blank" href="https://farhan.dev">https://farhan.dev</a>.</p>
<p>If you have any questions or are confused about anything – or just want to get in touch – I'm available on <a target="_blank" href="https://twitter.com/frhnhsin">Twitter</a> and <a target="_blank" href="https://www.linkedin.com/in/farhanhasin/">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ TCP and UDP Protocols – Explained in Plain English ]]>
                </title>
                <description>
                    <![CDATA[ Did you know that it's thanks to the TCP and UDP protocols that the internet works? But what do these acronyms mean? Well, TCP stands for Transmission Control Protocol and UDP stands for User Datagram Protocol Ok, but what are they? Why are they usef... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/tcp-and-udp-protocols/</link>
                <guid isPermaLink="false">66ba5347154fcfa01a69956c</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ computer networking ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tiago Capelo Monteiro ]]>
                </dc:creator>
                <pubDate>Thu, 10 Aug 2023 22:19:30 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/pexels-pixabay-159304.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Did you know that it's thanks to the TCP and UDP protocols that the internet works?</p>
<p>But what do these acronyms mean?</p>
<p>Well, TCP stands for Transmission Control Protocol and UDP stands for User Datagram Protocol</p>
<p>Ok, but what are they? Why are they useful? Why is it thanks to these protocols that the internet works?</p>
<p>In this article, we'll start with a simple analogy to help you understand the ideas behind TCP and UDP. Then I'll explain how they work in plain English. Next we'll discuss why these protocols are important, and we'll understand their key differences.</p>
<h2 id="heading-what-are-tcp-and-udp-explained-with-an-analogy">What are TCP and UDP? Explained with an Analogy</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/letter.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Photo by Suzy Hazelwood from Pexels: https://www.pexels.com/photo/shallow-focus-of-letter-paper-1157151/</em></p>
<p>You can think about TCP and UDP in a similar way as you think about a mail service.</p>
<p>Just like a <strong>mail service</strong> sends <strong>letters</strong> to <strong>individuals, TCP and UDP</strong> send <strong>packets</strong> to <strong>computers</strong>.</p>
<p>Packets are just formatted units of data in bytes.</p>
<p>TCP works more like a registered mail service. With registered mail, the sender sends a parcel to a recipient, and they're notified when the parcel is delivered. The sender can also track the parcel if it is lost or delayed.</p>
<p>On the other hand, UDP is like a regular mail service. The sender sends a parcel without any confirmation of delivery. There is also no tracking or guarantee that the parcel is going to be delivered.</p>
<h2 id="heading-how-do-tcp-and-udp-work">How Do TCP and UDP Work?</h2>
<p>Both the UDP and TCP are protocols used to ensure that data is reliably and securely transmitted between devices over a network.</p>
<p>TCP creates a connection between the sender and receiver and then data is transmitted between packets.</p>
<p>TCP also ensures that all packets are delivered in order. Additionally, it has mechanisms for resending lost packets and managing flow control. </p>
<p>Meanwhile, UDP sends packets without establishing a connection. Because of this, packets can be lost or arrive out of order as there is no mechanism to request retransmission.</p>
<h2 id="heading-tcp-vs-udp-whats-the-difference">TCP vs UDP – What's the Difference?</h2>
<p>Both UDP and TCP were developed starting in the 1980s.</p>
<p>TCP is important in programming because it provides a reliable and secure way for devices to communicate with each other over a network.</p>
<p>Without TCP, it would be difficult for devices to communicate securely, and many of the applications that we use today would not exist.</p>
<p>For example email communication, file transfers, and online transactions would all be very difficult without TCP.</p>
<p>TCP is preferred for secure, ordered, and reliable data transmission, as well as for delivering large amounts of data with minimal delay and mitigating network congestion.</p>
<p>UDP is also important for connections that require a lot broadband where security is not an issue.</p>
<p>For example video streaming services, online gaming platforms, and IoT devices can all use UDP to transmit data.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>With these protocols, the internet can operate safely and devices can communicate with each other effectively.</p>
<p>These concepts are key to understand if you're interested in Computer Networking. If you want to learn more about networking, you can <a target="_blank" href="https://www.freecodecamp.org/news/computer-networking-how-applications-talk-over-the-internet/">read this tutorial</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is Node.js? Server-Side JavaScript Development Basics ]]>
                </title>
                <description>
                    <![CDATA[ Node.js is a powerful runtime environment for executing JavaScript code outside of a web browser. It brings the JavaScript language to the server-side, enabling developers to build scalable, high-performance, and event-driven applications. Let's disc... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/node-js-basics/</link>
                <guid isPermaLink="false">66b9961894b336889c60043c</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node js ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ David Clinton ]]>
                </dc:creator>
                <pubDate>Tue, 25 Jul 2023 18:24:42 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/07/pexels-tomasz-filipek-1630035.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Node.js is a powerful runtime environment for executing JavaScript code <em>outside</em> of a web browser. It brings the JavaScript language to the server-side, enabling developers to build scalable, high-performance, and event-driven applications.</p>
<p>Let's discover how Node.js code works, and how that code can be integrated within your JavaScript and then executed.</p>
<p>This article comes from <a target="_blank" href="https://www.udemy.com/course/complete-lpi-web-development-essentials-exam-study-guide/?referralCode=C92570BCBB38302A9257">my Complete LPI Web Development Essentials Study Guide course</a>. If you'd like, you can follow the video version here:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/pSvvqaXCL30" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>Node.js allows developers to use JavaScript both on the client-side and the server-side, providing a unified language and ecosystem. This eliminates the need for context switching and enables code reuse between the front-end and back-end. This results in improved productivity and reduced development time.</p>
<p>Node.js has a vast and active ecosystem of modules and libraries available through the Node Package Manager (npm). This rich ecosystem offers ready-to-use tools and packages for various functionalities, such as web frameworks, database connectors, authentication, and testing frameworks. </p>
<p>Developers can leverage these modules to accelerate development and enhance application functionality.</p>
<p>Given all that, Node.js is particularly well-suited for building:</p>
<ul>
<li>Web applications</li>
<li>Scalable APIs</li>
<li>Real-time applications requiring instant data updates and bidirectional communication like chat applications and multiplayer games</li>
<li>Streaming applications like audio or video processing or real-time analytics</li>
<li>Single-page applications</li>
<li>Internet of Things deployments</li>
</ul>
<p>All that sound like a good match for some useful web applications? I thought it would. So let's see how it all works. </p>
<h2 id="heading-how-to-build-a-nodejs-server-environment">How to Build a Node.js Server Environment</h2>
<p>First off, you won't need to set up and run a third-party web server like Apache HTTPD or NGINX or place your content within the <code>/var/www/html</code> directory hierarchy. That's because Node.js is, among other things, a web server framework. </p>
<p>Let me show you what that means. You'll need to make sure you've got Node.js installed along with the necessary dependencies. By and large, you'll use the NPM package manager to get that done. There's excellent documentation for installing Node on your OS <a target="_blank" href="https://nodejs.org/en/download">from the official website</a>. </p>
<p>You can confirm that both Node and NPM are live and waiting for action by running these commands:</p>
<pre><code>$ node -v
v18<span class="hljs-number">.16</span><span class="hljs-number">.0</span>
$ npm -v
<span class="hljs-number">9.5</span><span class="hljs-number">.1</span>
</code></pre><p>Just to have some HTML to work with, you should find or create a simple <code>index.html</code> file and save it to a local directory on your machine. This command will download the <code>html</code> of an LPI page from my own website if you need something quick and small:</p>
<pre><code>wget https:<span class="hljs-comment">//bootstrap-it.com/lpi/</span>
</code></pre><p>Let's take a look at the <code>server.js</code> code we used for our Node server. </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);

<span class="hljs-keyword">const</span> server = http.createServer(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-comment">// Read the HTML file</span>
  fs.readFile(<span class="hljs-string">'index.html'</span>, <span class="hljs-string">'utf8'</span>, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (err) {
      res.writeHead(<span class="hljs-number">500</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span> });
      res.end(<span class="hljs-string">'Error loading HTML file'</span>);
      <span class="hljs-keyword">return</span>;
    }

    res.writeHead(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/html'</span> });
    res.end(data);
  });
});

<span class="hljs-keyword">const</span> port = <span class="hljs-number">3000</span>;
server.listen(port, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server is running on http://localhost:<span class="hljs-subst">${port}</span>`</span>);
});
</code></pre>
<p>Now let's work through that code, one section at a time. We begin by loading two necessary modules: <code>http</code> to manage the website hosting, and <code>fs</code> to read the HTML files. </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);
</code></pre>
<p>We then create a server function – called <code>server</code>. When called, it will either read and serve our <code>index.html</code> file (generating a 200 success code) or, if there's a problem reading the file, it'll generate a 500 error message.</p>
<pre><code class="lang-javascript">  fs.readFile(<span class="hljs-string">'index.html'</span>, <span class="hljs-string">'utf8'</span>, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (err) {
      res.writeHead(<span class="hljs-number">500</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span> });
      res.end(<span class="hljs-string">'Error loading HTML file'</span>);
      <span class="hljs-keyword">return</span>;
    }
</code></pre>
<p>The code continues by setting 3000 as the listening port for our application – although, technically, you could change that to any value you like between 1 and 65535. </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> port = <span class="hljs-number">3000</span>;
</code></pre>
<p>Finally, we call the <code>server</code> function using the <code>listen</code> method and specifying the port number, and then writing an entry to <code>console.log</code>.</p>
<pre><code class="lang-javascript">server.listen(port, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server is running on http://localhost:<span class="hljs-subst">${port}</span>`</span>);
</code></pre>
<h2 id="heading-how-to-execute-your-nodejs-server">How to Execute Your Node.js Server</h2>
<p>Running the <code>npm init</code> command in the same directory were your program files will live is used to initialize a new Node.js project and create a <code>package.json</code> file. </p>
<p>The <code>package.json</code> file serves as the manifest for the project, containing metadata and configuration information about the project, its dependencies, scripts, and other details.</p>
<p>You can manually add dependencies to the file or use:</p>
<pre><code class="lang-js">npm install &lt;package-name&gt;
</code></pre>
<p>...to add packages and their versions to the dependencies section of the <code>package.json</code>.</p>
<p>When you actually run <code>npm init</code> to initialize a directory for a new project, a script will ask you some questions. The default values npm suggests for you will include <code>1.0.0</code> as a version number and an entry point of <code>index.js</code>. </p>
<p>You'll also have the option of setting a git repo, keywords, and a choice of user license models. All the defaults should work just fine.</p>
<p>When that's done, the script will show you the proposed JSON-formatted version of your settings and ask for your approval. The <code>package.json</code> file that was created will reflect those settings.</p>
<p>For our project, install the MySQL database connector module along with express.js:</p>
<pre><code class="lang-javascript">$ npm install mysql
$ npm install express.js
</code></pre>
<p>Neither takes more than a few seconds. When that's all done, I'll see that there's now a new file in town: <code>package-lock.json</code>. </p>
<p>Peeking inside that file will show you an awful lot of JSON goodness. What's that all about? The package-lock.json file is automatically generated by npm when you install dependencies for your project. It serves as a lockfile that ensures deterministic and reproducible builds of your project across different environments. </p>
<p>It's important to include the package-lock.json file in version control systems like Git so that other developers or deployment environments can reproduce the exact dependency tree and versions used in the project. This ensures consistency and avoids potential conflicts or surprises when working with dependencies.</p>
<p>There will also be a new <code>node_modules</code> directory that was automatically created and populated by that init operation. This directory is a storage location for all the packages and modules our project relies on. When you install packages using <code>npm install</code>, the downloaded packages are placed here. </p>
<p>npm automatically resolves and installs the required dependencies of each package. It creates a hierarchical structure in the node_modules directory that reflects the dependency tree of your project.</p>
<p>Launching your server is straightforward:</p>
<pre><code class="lang-javascript">$ node server.js
</code></pre>
<p>To view the service, open your browser and direct it to the application URL, using port <code>3000</code>. When your browser is on the same machine as the Node server, this is how that'll look:</p>
<pre><code class="lang-javascript">localhost:<span class="hljs-number">3000</span>
</code></pre>
<p>Of course, you don't really need Node.js just for that. The value of Node.js comes from building user interactivity by integrating it with a backend database. That can happen using Express.js, but it'll have to wait for another time.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>What we <em>have</em> seen here is how the magic behind building a Node.js environment can provide all the infrastructure and backend functionality you need to launch and maintain an interactive and dynamic server.</p>
<p><em>This article comes from <a target="_blank" href="https://www.udemy.com/course/complete-lpi-web-development-essentials-exam-study-guide/?referralCode=C92570BCBB38302A9257">my Complete LPI Web Development Essentials Study Guide course</a>.</em> <em>And there's much more technology goodness available at <a target="_blank" href="https://bootstrap-it.com/">bootstrap-it.com</a></em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Google Sheets – A Beginner's Guide ]]>
                </title>
                <description>
                    <![CDATA[ Google Sheets is an online spreadsheet app with real-time collaboration features. It's like Microsoft Excel for regular people. 🙌 gif of guy saying aren't ordinary people adorable And, these days, it's actually giving Excel a run for its money. It'... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/google-sheets-for-beginners/</link>
                <guid isPermaLink="false">66b8ddef0a89d796f29a16e1</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ google sheets ]]>
                    </category>
                
                    <category>
                        <![CDATA[ spreadsheets ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Eamonn Cottrell ]]>
                </dc:creator>
                <pubDate>Tue, 25 Jul 2023 17:53:57 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/07/maxresdefault.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Google Sheets is an online spreadsheet app with real-time collaboration features. It's like Microsoft Excel for regular people. 🙌</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/ordinary.gif" alt="Image" width="600" height="400" loading="lazy">
<em>gif of guy saying aren't ordinary people adorable</em></p>
<p>And, these days, it's actually giving Excel a run for its money. It's picked up a lot of features and processing power over the years that used to be exclusive to Excel.</p>
<p>But we're here to talk about the basics today.</p>
<p>🧾I'm going to cover:</p>
<ol>
<li>How to create new Google Sheets</li>
<li>Intro to Templates</li>
<li>Menu and toolbar overview</li>
<li>Basic data entry and calculations</li>
<li>Basic formatting</li>
<li>How to create a table</li>
<li>How to sort and filter data</li>
<li>Intro to formulas and functions</li>
</ol>
<h2 id="heading-video-walkthrough">Video Walkthrough</h2>
<p>I've made a video walkthrough of the things we'll be covering in this article. You can check it out below:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/_bvRa7T-59U" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-how-to-create-a-new-sheet">How to Create a New Sheet</h2>
<p>Spreadsheets can be intimidating even in their most basic form. </p>
<p>Don't be scared, though.👇 </p>
<p>To use Google Sheets, you need a free Google account. (If you're using Gmail, you already have this.) Go <a target="_blank" href="https://www.google.com/sheets/about/">here</a> to sign up if you don't have one yet.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-141.png" alt="Image" width="600" height="400" loading="lazy">
<em>pic of the Google Sheets homepage</em></p>
<p>Go ahead and go to <a target="_blank" href="https://sheets.new">sheets.new</a> to create a brand new Google Sheet. It will also prompt you to sign up if you don't have an account yet. </p>
<p> 💥This is what you'll see:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-138.png" alt="Image" width="600" height="400" loading="lazy">
<em>pic of a blank spreadsheet</em></p>
<p>😓Some of you may already have begun perspiring because a spreadsheet looks like an unapproachable blank slate reserved for data analysts, financial gurus, and overly ambitious content creators. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/sweat.gif" alt="Image" width="600" height="400" loading="lazy">
<em>gif of man stressing out</em></p>
<p>💪Fear not. </p>
<p>A spreadsheet, and particularly a Google Sheet, is ripe with possibilities for the average person.</p>
<p>You can use them to enhance productivity after learning only a few basic things. </p>
<p>📊A spreadsheet is a <strong>big grid</strong> made up of <strong>columns labeled with letters</strong> and <strong>rows labeled with numbers</strong>. Each of the rectangles of the grid are called a <strong>cell</strong>, and the active cell is the one with the blue outline. </p>
<p>If you start typing, whatever you type will appear in the active cell.</p>
<p>The cells can contain numbers, words, formulas, dates, pretty much anything...</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-140.png" alt="Image" width="600" height="400" loading="lazy">
<em>pic of spreadsheet cell</em></p>
<h2 id="heading-google-sheets-templates">Google Sheets Templates</h2>
<p>Google has supplied us with a respectable amount of templates to get started with. </p>
<p>I will not be covering these in any detail because it's important to get the basics down first. I just want you to be aware of them if you need a starting point <strong>after</strong> you've gotten comfortable with Sheets. </p>
<p>You can look through the template gallery <a target="_blank" href="https://docs.google.com/spreadsheets/u/0/?ftv=1">here</a>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-142.png" alt="Image" width="600" height="400" loading="lazy">
<em>pic of Google Sheets templates</em></p>
<h2 id="heading-menu-and-toolbar-overview">Menu and Toolbar Overview</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/menus.png" alt="Image" width="600" height="400" loading="lazy">
<em>pic of Google Sheets menu and toolbar</em></p>
<p>You will likely be familiar with the menu and toolbar setup. As with most modern applications, they are at the top of the page. The menu has many familiar options like File, Edit, View, Insert, and so on. And the toolbar below it consists of mostly icons related to formatting and text options.</p>
<p>The <strong>File</strong> menu has options to share, download, copy, import, rename and other such things related to the whole spreadsheet.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-144.png" alt="Image" width="600" height="400" loading="lazy">
<em>pic of file menu</em></p>
<p><strong>Edit</strong> and <strong>View</strong> have familiar options regarding copy/paste and choosing different levels of visibility for your spreadsheet.</p>
<p><strong>Insert</strong> gives us a host of options of things to import into our sheet like charts, pivot tables, checkboxes, emojis, dropdown lists, and many more.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-145.png" alt="Image" width="600" height="400" loading="lazy">
<em>pic of insert menu</em></p>
<p><strong>🎨Format</strong> contains many options for formatting our sheet. We can add color, borders, tables styles, and more from here.</p>
<p>The <strong>Data</strong> menu has a lot of spreadsheet specific functions. It contains shortcuts to sort and filter data, to protect different ranges of cells, to group ranges together by naming them, data validation, and advanced items like connecting data sources.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-146.png" alt="Image" width="600" height="400" loading="lazy">
<em>pic of the Data menu in Google Sheets</em></p>
<p>Tools and Extensions will be lesser used menus, at least in the beginning. But some really exciting stuff is possible by leveraging the power of <strong>Google Apps Script</strong> through the Extensions menu. This lets us write programs in a language similar to JavaScript all while in a spreadsheet.</p>
<p>But, that's for later – or check out some of my other <a target="_blank" href="https://www.youtube.com/@eamonncottrell">videos</a> and <a target="_blank" href="https://www.freecodecamp.org/news/author/eamonn">articles</a> to get a taste of Apps Script.</p>
<h2 id="heading-basic-data-entry-and-calculations">Basic Data Entry and Calculations</h2>
<p>What is data? According to my Google search, data are "facts and statistics collected together for reference or analysis."</p>
<p>Spreadsheets thrive on data. Yes, think numbers, dates, percentages...things that are easily calculable.</p>
<p>In Google Sheets, we can enter in some data. Say, a list of names, dollar amounts, and dates. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-150.png" alt="Image" width="600" height="400" loading="lazy">
<em>pic of some data</em></p>
<p>Now, we have a simple list of data. Because it's small, we can scan it and analyze it ourselves pretty easily. </p>
<ol>
<li>We can see that it's ordered by date</li>
<li>We can see that Paul either has or owes the most</li>
<li>We can see that Sara either has or owes the least</li>
</ol>
<p>But imagine this is a list of thousands of records (each row of an amount, a name, and a date can be referred to as one record).</p>
<p>Suddenly it gets a lot harder to analyze or make sense of the data. </p>
<p>Then add a dozen or a hundred more columns of data for each record. It becomes virtually impossible for a human to draw anything meaningful from the data without the help of a spreadsheet or computer program.</p>
<p>Next, we'll see how some organization and simple spreadsheet operations can help us draw insights from our data.👇</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/easy.gif" alt="Image" width="600" height="400" loading="lazy">
<em>gif of woman saying this is so easy</em></p>
<h2 id="heading-basic-formatting">Basic Formatting</h2>
<p>Highlight the table. You can do this by clicking and dragging across the whole range of cells. Now, you should have an active <strong>range</strong> instead of an active <strong>cell</strong>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-151.png" alt="Image" width="600" height="400" loading="lazy">
<em>pic of Google Sheets table</em></p>
<p>Take a moment and click through some of the formatting options on the toolbar. I've changed the text, the font size, and then made bold the first header row. </p>
<p>I've also highlighted only the dollar amounts, and changed their format to <strong>currency</strong> instead of just a number.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/menus-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>pic of Google Sheets formatting</em></p>
<p>Already, the information is a little more readable. In the next steps we will go further.👇</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/rabbit-hole.gif" alt="Image" width="600" height="400" loading="lazy">
<em>gif of Alice falling down rabbit hole</em></p>
<h2 id="heading-how-to-create-a-table-in-sheets">How to Create a Table in Sheets</h2>
<p>Alas, we don't (yet) have a swift shortcut like Excel does to make a table. But if we highlight our data again, and select <strong>Format -&gt; Alternating Colors</strong> from the toolbar, we can create table formatting for enhanced readability.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-153.png" alt="Image" width="600" height="400" loading="lazy">
<em>pic of Alternating Colors table style in Google Sheets</em></p>
<p>Now, we have banded rows of alternating colors. This becomes very useful in large data sets, but is equally pleasing in our small example. Once satisfied with your color selections, click done.</p>
<p>Now, if we add rows of data to the bottom of our table, Google Sheets is smart enough to know that we probably want to extend the table downward. It will extend the alternating color formatting as we add two more lines:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-154.png" alt="Image" width="600" height="400" loading="lazy">
<em>pic of extended Google Sheets table</em></p>
<h2 id="heading-how-to-sort-data-with-a-filter-in-sheets">How to Sort Data with a Filter in Sheets</h2>
<p>Tables are useful because, with some small steps, we can sort and filter data in ways that make it easier to draw conclusions or extract meaning from our data.</p>
<p>Click anywhere in the range of data, and select <strong>Data -&gt; Create a filter</strong> from the Menu bar.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-155.png" alt="Image" width="600" height="400" loading="lazy">
<em>pic of creating a filter in Google Sheets</em></p>
<p>Again, Google Sheets knows to create a filter for the entire data set, and you can see two things visually represented: </p>
<ol>
<li>The rows and columns of the data set are now given a highlight color to show that a filter has been applied.</li>
<li>To the right of each header label, there are three horizontal lines that look like an upside-down pyramid. These are the filters.</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-156.png" alt="Image" width="600" height="400" loading="lazy">
<em>pic of filter on a Google Sheets table</em></p>
<p>From here, we can both sort and/or filter our data. If we sort, for instance, Z -&gt; A, we can display each row from highest to lowest dollar amount.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-157.png" alt="Image" width="600" height="400" loading="lazy">
<em>sorted table</em></p>
<p>If we click the data column's pyramid, we can see that for filtering options, we can either filter by condition or by value.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-158.png" alt="Image" width="600" height="400" loading="lazy">
<em>pic of filtering options in Google Sheets</em></p>
<p>Filtering by <strong>values</strong> lets us toggle on or off certain dates. Filtering by <strong>condition</strong> allows for all sorts of options. We can choose dates that are before or after certain dates. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-159.png" alt="Image" width="600" height="400" loading="lazy">
<em>pic of filter options in Google Sheets</em></p>
<p>Or we can select "Is between" and then write in a period of dates we want to filter for.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-161.png" alt="Image" width="600" height="400" loading="lazy">
<em>pic of filter options in Google Sheets</em></p>
<p>This becomes immensely helpful to narrow down a field of results for analysis. Now we can focus on only the subset of filtered results.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-162.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-intro-to-formulas-and-functions">Intro to Formulas and Functions</h2>
<p>The final piece we'll touch on is the ability to <strong>write formulas</strong> and <strong>use functions</strong>.</p>
<h3 id="heading-formulas-in-google-sheets">Formulas in Google Sheets</h3>
<p>Formulas are instructions we manually type into a cell to manipulate data. If we wanted to add the values in cells A16 and A17, we could write a formula that did this like so: <code>=A16+A17</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-163.png" alt="Image" width="600" height="400" loading="lazy">
<em>pic of a formula in Google Sheets</em></p>
<p>We can do basic math very easily like this, but there's an even better way to do this by using functions.</p>
<h3 id="heading-functions-in-google-sheets">Functions in Google Sheets</h3>
<p>Functions are built-in formulas that we use by typing their name. Again, we start out by typing the equals sign, but then we type the name of the function, in this case SUM: <code>=SUM(A16:A17)</code>.</p>
<p>When we begin typing a function, a tooltip will pop up giving us options for the different functions available. You can hit the TAB key to select a function, click one from the list, or complete the spelling of the function and type an open parentheses to select a function.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-165.png" alt="Image" width="600" height="400" loading="lazy">
<em>pic of available functions in Google Sheets</em></p>
<p>Once selected, the tooltip will display helper text about that function in case we need an explanation of what it does and/or the variables it needs:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-164.png" alt="Image" width="600" height="400" loading="lazy">
<em>pic of the SUM function in Google Sheets</em></p>
<p>These are straightforward examples of adding numbers, but there are over 400 built-in functions that range greatly in complexity. </p>
<h2 id="heading-whats-next">What's Next?</h2>
<p>As you've probably figured out, this barely scratches the surface of Google Sheets. Once you're comfortable with the basics, it's time to dive deeper and use Sheets to solve some problems of your own.</p>
<p>Check out the templates I've linked above for inspiration, spin up a personal finance tracker, make a workout calendar, track stock prices, build a cost of goods sheet for a small business, build an amortization sheet to see if you can afford a house, track your time with a project management sheet...the possibilities are vast.</p>
<p>🔗Check out my <a target="_blank" href="https://www.youtube.com/@eamonncottrell">YouTube channel</a> and <a target="_blank" href="https://got-sheet.beehiiv.com/subscribe">newsletter</a> for more Sheets content and projects.</p>
<p>🔗Connect with me on <a target="_blank" href="https://www.linkedin.com/in/eamonncottrell/">LinkedIn</a>.</p>
<p>Hope you have a great one!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/bye-gosling.gif" alt="Image" width="600" height="400" loading="lazy">
<em>gif of Gosling waving bye</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn JavaScript for Beginners – JS Basics Handbook ]]>
                </title>
                <description>
                    <![CDATA[ The goal of this handbook is to quickly introduce you to the basics of JavaScript so you can start programming applications. Instead of covering all the theories and concepts of JavaScript, I'll be teaching you only the most important building blocks... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-javascript-for-beginners/</link>
                <guid isPermaLink="false">66bd9197ffb0fc5947cc9139</guid>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nathan Sebhastian ]]>
                </dc:creator>
                <pubDate>Thu, 06 Jul 2023 19:01:25 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/06/book-cover.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The goal of this handbook is to quickly introduce you to the basics of JavaScript so you can start programming applications.</p>
<p>Instead of covering all the theories and concepts of JavaScript, I'll be teaching you only the most important building blocks of the language. We'll cover things like variables, data types, functions, objects, arrays, and classes. You'll also learn how to mix them all to build a small but solid program.</p>
<p>We're also going to leave out HTML, CSS, and using JavaScript in the browser. This tutorial focuses only on JavaScript as a programming language and uses the terminal to run the code.</p>
<p>This tutorial also has exercises for each section which gives you time to practice what you learned and "drill" the knowledge into your brain.</p>
<p>This handbook is completely free right here in this webpage. If you want the <a target="_blank" href="https://codewithnathan.com/beginning-modern-javascript">Kindle or paperback version of this tutorial</a>, you can pay a small fee for it. It'll help support me in creating an in-depth JavaScript Tutorial that will help you build a complete web application.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-1-javascript-introduction">1 - JavaScript Introduction</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-why-learn-javascript">Why learn JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-javascript-vs-java">JavaScript vs Java</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-2-how-to-set-up-your-computer">2 - How to Set Up Your Computer</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-to-install-vscode">How to Install VSCode</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-install-nodejs">How to Install Node.js</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-3-quick-console-introduction">3 - Quick Console Introduction</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-4-time-to-say-hello-world">4 - Time to Say Hello World!</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-5-javascript-code-structure">5 - JavaScript Code Structure</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-statements">Statements</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-comments">Comments</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-execution-flow">Execution Flow</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-exercise-1">Exercise #1</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-6-javascript-variables">6 - JavaScript Variables</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-variable-naming">Variable naming</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-constant-variable">Constant variable</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-var-keyword">The var keyword</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-exercise-2">Exercise #2</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-summary">Summary</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-7-javascript-basic-data-types">7 - JavaScript Basic Data Types</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-strings-in-javascript">Strings in JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-numbers-integers-and-floats-in-javascript">Numbers (integers and floats) in JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-booleans-in-javascript">Booleans in JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-undefined-in-javascript">Undefined in JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-null-in-javascript">Null in JavaScript</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-8-type-conversion-and-coercion">8 - Type conversion and coercion</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-type-coercion">Type coercion</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-type-coercion-rules">Type coercion rules</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-you-should-avoid-type-coercion">Why you should avoid type coercion</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-9-operators-in-javascript">9 - Operators in JavaScript</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-arithmetic-operators">Arithmetic operators</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-assignment-operator">The assignment operator</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-comparison-operators">The comparison operators</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-logical-operators">Logical operators</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-typeof-operator">The typeof operator</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-exercise-3">Exercise #3</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-10-javascript-arrays">10 - JavaScript Arrays</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-array-index-position">Array index position</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-special-methods-for-array-manipulation">Special methods for array manipulation</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-exercise-4">Exercise #4</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-11-control-flows-conditionals-in-javascript">11 - Control Flows (Conditionals) in JavaScript</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-the-ifelse-statement">The if...else statement</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-switchcase-statement">The switch...case statement</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-switch-statement-body">The switch statement body</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-switch-statement-use-cases">Switch statement use cases</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-exercise-5">Exercise #5</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-12-control-flows-loops-in-javascript">12 - Control Flows (Loops) in JavaScript</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-the-for-statement">The for statement</a></p>
</li>
<li><p><a class="post-section-overview" href="#whentousetheforloop">When to use the for loop?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-while-statement">The while statement</a></p>
</li>
<li><p><a class="post-section-overview" href="#whentousethewhileloop">When to use the while loop?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-exercise-6">Exercise #6</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-13-functions-in-javascript">13 - Functions in JavaScript</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-to-create-your-own-function">How to create your own function</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-function-parameters-and-arguments">Function parameters and arguments</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-default-parameters">Default parameters</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-default-parameters-and-null">Default parameters and null</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-return-statement">The return statement</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-the-rest-parameter">The rest parameter</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-arrow-function">Arrow function</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-single-and-multiline-arrow-functions">Single and multiline arrow functions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-arrow-function-without-round-brackets">Arrow function without round brackets</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-arrow-function-doesnt-have-arguments-binding">Arrow function doesn't have arguments binding</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-convert-a-normal-function-to-an-arrow-function-easily">How to convert a normal function to an arrow function easily</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-exercise-7">Exercise #7</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-14-objects-in-javascript">14 - Objects in JavaScript</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-to-access-object-values">How to access object values</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-add-a-new-property-to-the-object">How to add a new property to the object</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-modify-object-properties">How to modify object properties</a></p>
</li>
<li><p><a class="post-section-overview" href="#howtodeletegobjectproperties">How to delete object properties</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-check-if-a-property-exists-in-an-object">How to check if a property exists in an object</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-exercise-8">Exercise #8</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#finalexercisebuildeacashregistermachine">Final Exercise: Build a Cash Register Machine</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-solutions">Solutions</a></p>
</li>
</ul>
<h2 id="heading-1-javascript-introduction">1 - JavaScript Introduction</h2>
<p>JavaScript was created around April 1995 by Brendan Eich. At the time, he was working to develop a browser for a company called Netscape. He was told that he only had 10 days to design and code a working prototype of a programming language that could run on the browser.</p>
<p>He needed to create a language that appealed to non-professional programmers like Microsoft Visual Basic.</p>
<p>The reason he was given only 10 days was that Netscape needed to release its browser, which at the time was in competition with Microsoft.</p>
<p>In the beginning, JavaScript was not as powerful as it is today, since it was originally designed to add interaction and animation for web pages. It wasn't until 2005 when jQuery and AJAX were released that JavaScript began to be used in every website.</p>
<p>People simply didn't have an easy alternative to jQuery and AJAX for DOM manipulation and sending asynchronous requests. Plus, an active community of JavaScript developers kept adding new features to the library.</p>
<p>Then Google launched its modern Chrome browser, and Facebook started getting more people online. JavaScript began to grow to accomodate the ambitions of these giant internet companies.</p>
<p>Browsers began developing APIs that you could use in JavaScript. JS could retrieve information such as IP addresses and geographic locations from the browser, adding more power to internet companies to localize the features of their websites.</p>
<p>Then another innovation happened to make JavaScript even more powerful.</p>
<p>A server-side environment named Node.js was released in 2009, allowing JavaScript to run on the server side like PHP, Java, Python, Ruby, and many more. It also enabled devs to develop full-stack web applications using only JavaScript.</p>
<p>Today, JavaScript is a language that can power the web, desktop, and mobile applications.</p>
<p>Here's a quote from Tim O'Reilly, the founder of O'Reilly Media:</p>
<blockquote>
<p>Learning JavaScript used to mean you weren't a serious developer. Today, not learning JavaScript means the same thing.</p>
</blockquote>
<p>Learning JavaScript is now critical for people who want to be web developers.</p>
<h3 id="heading-why-learn-javascript">Why learn JavaScript?</h3>
<p>There are 4 good reasons why you need to learn and deeply understand JavaScript:</p>
<ol>
<li><p>JavaScript is the only language that works in the browser</p>
</li>
<li><p>It's fairly easy to learn (but hard to master)</p>
</li>
<li><p>It's an essential language for making web applications</p>
</li>
<li><p>There are many career opportunities for JavaScript devs</p>
</li>
</ol>
<p>Learning JavaScript opens tremendous opportunities where you can be a frontend, backend, or mobile developer.</p>
<p>Basically, learning JavaScript is a gateway to career improvements in tech.</p>
<h3 id="heading-javascript-vs-java">JavaScript vs Java</h3>
<p>In the beginning, JavaScript was actually named LiveScript. It was renamed to JavaScript because Java was a very popular programming language.</p>
<p>Since most software developers were already familiar with Java, the name JavaScript was thought to help in marketing JavaScript as a great programming language and draw the interest of developers at the time.</p>
<p>Just to be clear, JavaScript and Java are two completely different programming languages. You don't need to know Java to learn JavaScript (or the other way around). :)</p>
<h2 id="heading-2-how-to-set-up-your-computer">2 - How to Set Up Your Computer</h2>
<p>To write a program using JavaScript, you need to install 2 free tools that are available for all operating systems.</p>
<p>The first tool to install is Visual Studio Code.</p>
<h3 id="heading-how-to-install-vscode">How to Install VSCode</h3>
<p>Visual Studio Code or VSCode for short is a text editor program created for the purpose of writing code. Aside from being free, VSCode is open source and available on all major operating systems.</p>
<p>You can use VSCode on Windows, macOS, and Linux, so if you don't have a text editor on your computer, I recommend that you install VSCode here.</p>
<p>Now that you have a text editor to write JavaScript code, you need a software to run JavaScript code. Let's install Node.js next.</p>
<h3 id="heading-how-to-install-nodejs">How to Install Node.js</h3>
<p>To run JavaScript outside of the browser, you need to install Node.js, which is essentially a JavaScript runner.</p>
<p>Simply go to the Node.js website at nodejs.org and download the latest LTS version for your computer. Once the download is complete, install it on your system.</p>
<p>You need to run Node.js using the console, so open your command line or terminal application and run the following command:</p>
<pre><code class="lang-sh">node -v
</code></pre>
<p>This command will output the version of your freshly installed Node.js into the console.</p>
<h2 id="heading-3-quick-console-introduction">3 - Quick Console Introduction</h2>
<p>The console is a text-based interface that you can use to type and run commands on your computer. On Windows, it's called the Command Line. On macOS and Linux it's known as the Terminal.</p>
<p>You're not going to use all the commands available within the console. In fact, you only need to know 7 basic commands to help you run JavaScript code.</p>
<p>First, open the console program on your computer and type the <code>pwd</code> command:</p>
<pre><code class="lang-sh"><span class="hljs-built_in">pwd</span>
</code></pre>
<p>This is the command you use to find out which directory your terminal is currently on. <code>pwd</code> is short for print working directory.</p>
<p>To change the working directory, you need to run the <code>cd</code> command.</p>
<p>Here's an example to move into a child directory:</p>
<pre><code class="lang-sh"><span class="hljs-built_in">cd</span> directory_name/directory_name
</code></pre>
<p>To move up to a parent directory, you specify <code>..</code> next to the command:</p>
<pre><code class="lang-sh"><span class="hljs-built_in">cd</span> ..
</code></pre>
<p>To go up more than one directory, use <code>../..</code></p>
<p>To clear your console from previous commands and output, use the <code>clear</code> command:</p>
<pre><code class="lang-sh">clear
</code></pre>
<p>To print out the list of files and directories in the current directory, run the <code>ls</code> command:</p>
<pre><code class="lang-sh">ls
</code></pre>
<p>To create a new file, use the <code>touch</code> command followed by the file name and extension:</p>
<pre><code class="lang-sh">touch index.js
</code></pre>
<p>The command above will create a new JavaScript file named <code>index.js</code> on the current working directory.</p>
<p>To create a new directory, use the <code>mkdir</code> command followed by the directory name:</p>
<pre><code class="lang-sh">mkdir my_project
</code></pre>
<p>To run JavaScript using Node.js, specify <code>node</code> followed by the file name as follows:</p>
<pre><code class="lang-sh">node index.js
</code></pre>
<p>You'll see any output from the code in the same console.</p>
<p>There are lots of things you can do with the console, but these 7 commands would be enough because we only need it to run JavaScript code.</p>
<p>Next, let's run your first JavaScript program!</p>
<h2 id="heading-4-time-to-say-hello-world">4 - Time to Say Hello World!</h2>
<p>It's time to run your first JavaScript program using Node.</p>
<p>From the console, create a new JavaScript file named <code>index.js</code> using the <code>touch</code> command.</p>
<pre><code class="lang-sh">touch index.js
</code></pre>
<p>Next, open the file using VSCode and write the following line of code into the file:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World!"</span>);
</code></pre>
<p>Back on the console, run this script with Node:</p>
<pre><code class="lang-sh">node index.js
</code></pre>
<p>The console should execute the <code>index.js</code> file and print "Hello World!".</p>
<p>You've just run your very first JavaScript program using Node.js. Excellent!</p>
<p>When you run the <code>node index.js</code> command, the Node.js program starts reading the script line by line from top to bottom.</p>
<p>The <code>node</code> program sees that you wrote the word <code>console.log</code> followed by parentheses <code>()</code>, so it knows that you're instructing it to print something. The program then reads what you put in the parentheses and prints it out on the console.</p>
<p>In your VSCode or other text editor program, you should see different parts of your code highlighted with different colors. This is a feature of the text editor called <em>syntax highlighting</em>, and it's really useful to help you distinguish different parts of the code.</p>
<p>The <code>log</code> keyword is a function, so it gets highlighted in one color, while the words in the parentheses have another color.</p>
<p>A function is simply a piece of code that's used to perform a certain task. The <code>log()</code> function is used to "print" whatever you put inside the parentheses.</p>
<p>On the other hand, the <code>console</code> keyword is an object, which is a standalone property that gives access to certain functionalities.</p>
<p>We'll learn more about functions and objects later. For now, just remember that the <code>console.log()</code> keyword is used to print things to the console.</p>
<p>Next, let's start with learning JavaScript code structure.</p>
<h2 id="heading-5-javascript-code-structure">5 - JavaScript Code Structure</h2>
<p>A computer program is a series of pieces of code written in a text file. These text files are then run through a software that's designed specially for running the code. The Node.js software you downloaded previously is the tool that processes JavaScript code.</p>
<p>Before we go further, let's understand the structure of code.</p>
<h3 id="heading-statements">Statements</h3>
<p>A statement is a single instruction for the computer to run. Think of it like a sentence, but for computers. We can end a statement by using a semicolon <code>;</code> just like we can end a sentence using a dot <code>.</code></p>
<p>You can write multiple statements in a single line, but the convention is to write one statement per line:</p>
<pre><code class="lang-js"><span class="hljs-comment">// This is hard to read</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World!"</span>); <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I'm learning JavaScript"</span>);

<span class="hljs-comment">// Now it's better</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World!"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I'm learning JavaScript"</span>);
</code></pre>
<p>Each statement is an expression of some action that needs to be carried out by the software that executes the code.</p>
<h3 id="heading-comments">Comments</h3>
<p>In programming, comments are text we use to communicate the context of the code written in the file.</p>
<p>To write a comment in JavaScript, you need to add two forward slashes <code>//</code> before the comment as shown below:</p>
<pre><code class="lang-js"><span class="hljs-comment">// This is a comment</span>
<span class="hljs-comment">// This is also a comment</span>

<span class="hljs-comment">// Below print two lines of statements</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World!"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I'm learning JavaScript"</span>);
</code></pre>
<p>Comments are ignored by the language processor, so you can use comments to disable some code without having to delete that code.</p>
<p>The code below shows how to disable the second print statement:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World!"</span>);
<span class="hljs-comment">// console.log("I'm learning JavaScript");</span>
</code></pre>
<h3 id="heading-execution-flow">Execution Flow</h3>
<p>A language processor such as Node.js executes statements in a top-down approach. The statement written in the first line will be executed before the second line, then continue down to the last line:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World!"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I'm learning JavaScript"</span>);

<span class="hljs-comment">// Printing numbers</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">1</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">2</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">3</span>);
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-txt">Hello World!
I'm learning JavaScript
1
2
3
</code></pre>
<p>If you want to print the numbers before the text, then you need to move the corresponding <code>console.log()</code> lines to the top.</p>
<h3 id="heading-exercise-1">Exercise #1</h3>
<p>Try to print your name, age, and occupation on the console.</p>
<p>The output would look as follows:</p>
<pre><code class="lang-txt">John Doe
19
Student
</code></pre>
<p>Now that you understand the basic code structure of JavaScript, let's continue with learning variables next.</p>
<h2 id="heading-6-javascript-variables">6 - JavaScript Variables</h2>
<p>Before explaining what a variable is, I want you to change the code you've written in the <code>index.js</code> file.</p>
<p>Change the code in that file as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> message = <span class="hljs-string">"Hello World!"</span>
<span class="hljs-built_in">console</span>.log(message)
</code></pre>
<p>Next, run the code using the <code>node index.js</code> command. You'll see the same output as when you write the 'Hello World!' message directly inside the <code>console.log()</code> function. How can this be?</p>
<p>This is because the message written in the code above is a <em>variable</em>.</p>
<p>In programming, a variable is simply a name that you give to a value so that you can access that value later. You can think of a variable as a label that can be tagged to a certain value, so you can refer to the value using the label.</p>
<p>To declare a variable, you need to type the keyword <code>let</code> followed by the variable name.</p>
<p>The first line in the code tells JavaScript to associate the <code>message</code> variable with the value <code>Hello World!</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> message = <span class="hljs-string">"Hello World!"</span>
</code></pre>
<p>In the second line, JavaScript is instructed to print the value of <code>message</code>, and that's exactly what it does.</p>
<p>You can change the value of your variable by re-assigning another value as follows:</p>
<pre><code class="lang-js">message = <span class="hljs-string">"Hello World!"</span>
<span class="hljs-built_in">console</span>.log(message)
message = <span class="hljs-string">"Nice weather!"</span>
<span class="hljs-built_in">console</span>.log(message)
</code></pre>
<p>Run the file and you'll see two lines printed as the output:</p>
<pre><code class="lang-txt">Hello World!
Nice weather!
</code></pre>
<p>Variables are used to reference data so that you can use the same data multiple times in your program.</p>
<p>Next, let's see some rules for naming variables in JavaScript.</p>
<h3 id="heading-variable-naming">Variable naming</h3>
<p>JavaScript has a few naming rules that you need to know to avoid naming errors.</p>
<p>Variable names can only contain alphabet letters, numbers, and underscores (<code>_</code>). This means you can name your variable <code>message</code>, <code>message_1</code>, <code>message_2</code>.</p>
<p>The first character of the variable name must not be a number. <code>message_1</code> is okay. <code>1_message</code> is not.</p>
<p>You can't use reserved keywords such as <code>console</code> because they are used by JavaScript to do certain things. There are many other keywords used by JavaScript that you'll learn in the following sections such as <code>if</code>, <code>for</code>, and <code>while</code>.</p>
<p>Variable names are case-sensitive, which means <code>Message</code>, <code>MESSAGE</code>, and <code>message</code> can be used to create three different variables. But of course, I don't recommend using similar names as it causes confusion.</p>
<p>Sometimes, you need more than one word to declare a variable name. JavaScript has two naming conventions that are used worldwide:</p>
<ol>
<li><p><code>camelCase</code></p>
</li>
<li><p><code>snake_case</code></p>
</li>
</ol>
<p>Camel case is a naming convention that uses an uppercase letter for the first character for subsequent words. Here's an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myAwesomeVariable
</code></pre>
<p>The snake case naming convention uses an underscore to separate words. Here's an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> my_awesome_variable
</code></pre>
<p>Both are acceptable naming conventions, but you should stick to one of them in your code to avoid confusion.</p>
<h3 id="heading-constant-variable">Constant variable</h3>
<p>There are times when you need to store a value that never changes in a variable.</p>
<p>A constant variable is a variable that doesn't change its value as long as the program is running. In other programming languages, changing the value of a constant will produce an error.</p>
<p>In JavaScript, a constant variable is declared using the <code>const</code> keyword.</p>
<p>The following shows how to declare 2 constants in JavaScript:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> FILE_SIZE_LIMIT = <span class="hljs-number">2000</span>
<span class="hljs-keyword">const</span> MAX_SPEED = <span class="hljs-number">300</span>
</code></pre>
<p>The naming convention for a constant is to use all uppercase letters, although using lowercase letters also works. The uppercase is just a standard to make constants stand out more.</p>
<h3 id="heading-the-var-keyword">The var keyword</h3>
<p>The <code>var</code> keyword is used to declare variables with a global scope. This keyword was the only keyword you can use to declare variables before JavaScript released the new <code>let</code> and <code>const</code> keyword in 2015.</p>
<p>As of today, you should avoid using <code>var</code> if you can, since <code>var</code> can introduce bugs that you can avoid by using the <code>let</code> keyword.</p>
<p>To show you what I mean, consider the following example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">if</span>(<span class="hljs-literal">true</span>) {
    <span class="hljs-keyword">var</span> name = <span class="hljs-string">"Nathan"</span>;
}

<span class="hljs-built_in">console</span>.log(name)
</code></pre>
<p>The code above will print the <code>name</code> variable just fine, but it really should not because the variable <code>name</code> is declared inside the <code>if</code> block.</p>
<p>This is because any variable declared using the <code>var</code> keyword is accessible from everywhere. The scope of that variable is global.</p>
<p>On the other hand, the <code>let</code> keyword has a block scope, which means the variable is only accessible from the block and all its child blocks.</p>
<p>But why bother with scoping the variable? This is because when you have hundreds or thousands of code lines, it can become frustrating to trace an error that occurs because of global variables.</p>
<p>There's a principle in software development called "principles of least exposure", which means you don't expose any part of your program that's unnecessary.</p>
<p>Block scoping a variable ensures that a variable is exposed and accessible only in parts of your codebase that require the variable.</p>
<p>A variable declared using the <code>let</code> keyword is identical to a variable declared using <code>var</code> except for the scope level.</p>
<pre><code class="lang-js"><span class="hljs-keyword">if</span>(<span class="hljs-literal">true</span>) {
    <span class="hljs-keyword">let</span> name = <span class="hljs-string">"Nathan"</span>;
}

<span class="hljs-built_in">console</span>.log(name)  <span class="hljs-comment">// Error: name is not defined</span>
</code></pre>
<p>This also means that you now have <code>var</code>, <code>let</code>, and <code>const</code> keywords to declare a variable. Which one to use?</p>
<p>In general, you can declare a variable with <code>const</code> first. When you code your application and realize that you need to change the variable assignment, you can change the declaration to <code>let</code>.</p>
<p>If you know from the start that the variable's value will change, then you can use <code>let</code> immediately. Just don't use <code>var</code> today or people might get mad at you.</p>
<h3 id="heading-exercise-2">Exercise #2</h3>
<p>Write a program with three variables, each with the following value:</p>
<ol>
<li><p>The first variable contains your name</p>
</li>
<li><p>The second variable contains your age</p>
</li>
<li><p>The third variable contains your occupation</p>
</li>
</ol>
<p>Then print the variables using the <code>console.log()</code> method. Here's the example output:</p>
<pre><code class="lang-txt">John Doe
Student
19
</code></pre>
<h3 id="heading-summary">Summary</h3>
<p>How you use variables to make a program that does what you want it to do is one of the most important skills you can have as a programmer.</p>
<p>But before you learn more about how to make use of variables, let's learn about data types in JavaScript.</p>
<h2 id="heading-7-javascript-basic-data-types">7 - JavaScript Basic Data Types</h2>
<p>Data Types are simply definitions for different types of data known to a programming language.</p>
<p>A data type contains specifications about what you can and can't do with that data.</p>
<p>To show you a brain-friendly example, I'm sure you agree that <code>2 + 2 = 4</code>?</p>
<p>Well, JavaScript also agrees with that:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-number">2</span> + <span class="hljs-number">2</span>);

<span class="hljs-comment">// Output: 4</span>
</code></pre>
<p>But what if you try to add a number with letters as shown below?</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-number">2</span> + <span class="hljs-string">"ABC"</span>);
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-txt">2ABC
</code></pre>
<p>Adding a number and letters together will cause JavaScript to concatenate or join the values together.</p>
<p>In this section, you're going to learn basic data types that JavaScript knows:</p>
<ul>
<li><p>Strings</p>
</li>
<li><p>Numbers</p>
</li>
<li><p>Booleans</p>
</li>
<li><p>Null</p>
</li>
<li><p>Undefined</p>
</li>
</ul>
<p>You will also see how these different types react to operators such as <code>+</code> shown in the above example.</p>
<p>First, let's start with strings.</p>
<h3 id="heading-strings-in-javascript">Strings in JavaScript</h3>
<p>Strings are simply data defined as a series of characters.</p>
<p>You've seen an example of string data previously when you call the <code>console.log()</code> function to print a message:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> message = <span class="hljs-string">"Hello, Sunshine!"</span>;
<span class="hljs-built_in">console</span>.log(message); <span class="hljs-comment">// Hello, Sunshine!</span>
</code></pre>
<p>A string needs to be enclosed in quotations. You can use double quotes or single quotes, but they have to match.</p>
<p>You'll get an error when you use different quotation marks like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Invalid or unexpected token</span>
<span class="hljs-keyword">let</span> message = <span class="hljs-string">"Hello';</span>
</code></pre>
<p>You can join two or more strings as one with the plus <code>+</code> symbol. Don't forget to add a space before the next string or you'll get a string without spaces!</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> message = <span class="hljs-string">"Hello "</span> + <span class="hljs-string">"and "</span> + <span class="hljs-string">"Goodbye!"</span>;
<span class="hljs-built_in">console</span>.log(message);

<span class="hljs-comment">// Output: Hello and Goodbye!</span>
</code></pre>
<p>When printing a variable's value, you can also add strings in the <code>console.log()</code> function directly as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> message = <span class="hljs-string">"Hello, Dave!"</span>;

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The message is: "</span> + message);

<span class="hljs-comment">// Output: The message is: Hello, Dave!</span>
</code></pre>
<p>This is particularly useful when you have multiple strings to console.log in one sentence as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> name = <span class="hljs-string">"John"</span>;
<span class="hljs-keyword">let</span> topic = <span class="hljs-string">"JavaScript"</span>;

<span class="hljs-built_in">console</span>.log(name + <span class="hljs-string">" is learning "</span> + topic + <span class="hljs-string">" today"</span>);

<span class="hljs-comment">// Output: John is learning JavaScript today</span>
</code></pre>
<p>Or you can also use the template strings format, which allows you to embed a variable directly inside the string as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> name = <span class="hljs-string">"John"</span>;
<span class="hljs-keyword">let</span> topic = <span class="hljs-string">"JavaScript"</span>;

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${name}</span> is learning <span class="hljs-subst">${topic}</span> today`</span>);

<span class="hljs-comment">// Output: John is learning JavaScript today</span>
</code></pre>
<p>To use the template strings format, you need to use the backtick <code>(`)</code> character to wrap the string instead of quotations.</p>
<p>The variable is embedded in the string using the dollar symbol and curly brackets as in <code>${variable}</code>.</p>
<p>This way, JavaScript knows that you're referencing a variable inside the string.</p>
<p>When you have multiple strings to print in a single line, then the template strings format is more convenient because you didn't have to break the string with quotations and concatenations.</p>
<p>Next, strings can also represent numbers. You surround the numbers in quotations as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> score = <span class="hljs-string">"10"</span> + <span class="hljs-string">"30"</span>;
<span class="hljs-built_in">console</span>.log(score);

<span class="hljs-comment">// Output: 1030</span>
</code></pre>
<p>When you join two string numbers with a <code>+</code> symbol, JavaScript will join the two numbers instead of performing arithmetic addition.</p>
<p>This is how strings work in JavaScript. Let's look at numbers next.</p>
<h3 id="heading-numbers-integers-and-floats-in-javascript">Numbers (integers and floats) in JavaScript</h3>
<p>Number data types represent different kinds of numbers. There are two types of numbers in JavaScript:</p>
<ul>
<li><p>Integers</p>
</li>
<li><p>Floats</p>
</li>
</ul>
<p>An integer is a whole number without decimals and fractions. Below, you see examples of two integers <code>x</code> and <code>y</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> x = <span class="hljs-number">1</span>;
<span class="hljs-keyword">let</span> y = <span class="hljs-number">2</span>;

<span class="hljs-built_in">console</span>.log(x + y);

<span class="hljs-comment">// Output: 3</span>
</code></pre>
<p>On the other hand, floats refer to numbers with decimal points like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> f = <span class="hljs-number">1.2</span>;
<span class="hljs-keyword">let</span> z = <span class="hljs-number">2.35</span>;

<span class="hljs-built_in">console</span>.log(f + z);

<span class="hljs-comment">// Output: 3.55</span>
</code></pre>
<p>To create a float, you need to write a number and use <code>.</code> to define the decimal values.</p>
<p>With number types, you can perform arithmetic operations such as addition <code>+</code>, subtraction <code>-</code>, division <code>/</code>, and multiplication <code>*</code> just like how you use a calculator.</p>
<h3 id="heading-booleans-in-javascript">Booleans in JavaScript</h3>
<p>Boolean is a type that represents <code>true</code> and <code>false</code> values.</p>
<p>You can think of Booleans as a light switch that can only be in one of two positions: on or off.</p>
<p>So it is with Boolean values in programming languages. They are used when JavaScript needs to make a decision: Go left or go right? Right or wrong?</p>
<p>Here's how you create Boolean values in JavaScript:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> on = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">let</span> off = <span class="hljs-literal">false</span>;
</code></pre>
<p>This data type is frequently used when you need to make a decision using a control flow. You'll see why Boolean values are very useful in developing a program later in Section 9.</p>
<h3 id="heading-undefined-in-javascript">Undefined in JavaScript</h3>
<p>Undefined is a data type in JavaScript used to represent a variable that hasn't been assigned any value yet.</p>
<p>Anytime you declared a variable without assigning any value, the <code>undefined</code> value will be assigned to that variable. For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> first_name;

<span class="hljs-built_in">console</span>.log(first_name); <span class="hljs-comment">// undefined</span>
</code></pre>
<p>You can also assign <code>undefined</code> to a variable explicitly as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> last_name = <span class="hljs-literal">undefined</span>;
</code></pre>
<p>But this is usually not recommended, because JavaScript has another value called <code>null</code> which is used to mark a variable as empty.</p>
<h3 id="heading-null-in-javascript">Null in JavaScript</h3>
<p>The <code>null</code> value is a special data type that represents an empty or unknown value. Here's how you assign a variable as null:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> first_name = <span class="hljs-literal">null</span>;
</code></pre>
<p>The code above means that the value of <code>first_name</code> is empty or unknown.</p>
<p>At this point, you may be thinking what's the difference between <code>undefined</code> and <code>null</code>? They seem to serve a similar purpose.</p>
<p>And you are correct. Both <code>undefined</code> and <code>null</code> are values that represent nothing, and other programming languages usually only have one, and that is <code>null</code>.</p>
<p>In JavaScript, the <code>undefined</code> value is reserved as the default value when a variable is declared, while <code>null</code> means you intentionally assign an "empty" value for the variable.</p>
<p>This slight difference will come to play later when you learn about functions in Chapter 13.</p>
<p>For now, just keep in mind that JavaScript treats <code>undefined</code> as the "default" empty value and <code>null</code> as the "intentional" empty value.</p>
<h2 id="heading-8-type-conversion-and-coercion">8 - Type Conversion and Coercion</h2>
<p>At times, you might want to convert one data type into another so that the program runs as expected.</p>
<p>For example, suppose you need to convert a string into an integer so you can perform an addition between numbers.</p>
<p>If you have one of the numbers as a string, JavaScript joins them together instead of adding:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> x = <span class="hljs-string">"7"</span>;
<span class="hljs-keyword">let</span> y = <span class="hljs-number">5</span>;

<span class="hljs-built_in">console</span>.log(x + y); <span class="hljs-comment">// 75</span>
</code></pre>
<p>To add the two numbers properly, you need to convert the <code>x</code> variable into an integer.</p>
<p>Changing the data from one type to another is also known as type conversion or type casting. There are 3 functions frequently used to do type conversion:</p>
<ul>
<li><p><code>Number()</code></p>
</li>
<li><p><code>String()</code></p>
</li>
<li><p><code>Boolean()</code></p>
</li>
</ul>
<p>As their name implies, these type conversion functions will attempt to convert any value you specified inside the parentheses to the type of the same name.</p>
<p>To convert a string into an integer, you can use the <code>int()</code> function:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> x = <span class="hljs-string">"7"</span>;
<span class="hljs-keyword">let</span> y = <span class="hljs-number">5</span>;

<span class="hljs-comment">// Convert x to integer</span>
x = <span class="hljs-built_in">Number</span>(x);

<span class="hljs-built_in">console</span>.log(x + y); <span class="hljs-comment">// 12</span>
</code></pre>
<p>On the other hand, the <code>String()</code> function converts a value of another type to a string. If you type <code>String(true)</code>, then you'll get 'true' back.</p>
<p>Passing a value of the same type as the function has no effect. It will just return the same value back.</p>
<h3 id="heading-type-coercion">Type coercion</h3>
<p>In JavaScript, type coercion is a process where a value of one type is implicitly converted into another type.</p>
<p>This is automatically done by JavaScript so that your code won't cause an error. But as you'll see in this section, type coercion can actually cause undesired behavior in the program.</p>
<p>Let's consider what happens when you perform an addition between a <code>number</code> and a <code>string</code> in JavaScript:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-number">1</span> + <span class="hljs-string">"1"</span>);
</code></pre>
<p>As you've seen in the previous section, JavaScript will consider the number as a string and join the two letters as <code>11</code> instead of adding them (<code>1 + 1 = 2</code>)</p>
<p>But you need to know that other programming languages don't respond the same way.</p>
<p>Programming languages like Ruby or Python will respond by stopping your program and giving an error as feedback. It will respond with something along the lines of "Cannot perform addition between a number and a string".</p>
<p>But JavaScript will see this and said: "I cannot do the operation you requested <strong>as it is</strong>, but I can do it if the number <code>1</code> is converted to a <code>string</code>, <strong>so I'll do just that</strong>."</p>
<p>And that's exactly what type coercion is. JavaScript notices that it doesn't know how to execute your code, but it doesn't stop the program and respond with an error.</p>
<p>Instead, it will change the data type of one of the values without telling you.</p>
<p>While type coercion doesn't cause any errors, the output is actually something you don't want either.</p>
<h3 id="heading-type-coercion-rules">Type coercion rules</h3>
<p>Type coercion rules are never stated clearly anywhere, but I did find some rules by trying various silly code myself.</p>
<p>It seems that JavaScript will first convert data types to <code>string</code> when it finds different data types:</p>
<pre><code class="lang-js"><span class="hljs-number">1</span> + <span class="hljs-string">"1"</span> <span class="hljs-comment">// "11"</span>
[<span class="hljs-number">1</span> ,<span class="hljs-number">2</span>] + <span class="hljs-string">"1"</span> <span class="hljs-comment">// "1,21"</span>
<span class="hljs-literal">true</span> + <span class="hljs-string">"1"</span> <span class="hljs-comment">// "true1"</span>
</code></pre>
<p>But the order of the values matters when you have an object. Writing objects first always returns numeric <code>1</code>:</p>
<pre><code class="lang-js">{ <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> } + <span class="hljs-string">"1"</span> <span class="hljs-comment">// 1</span>
<span class="hljs-string">"1"</span> + { <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> } <span class="hljs-comment">// "1[object Object]"</span>
<span class="hljs-literal">true</span> + { <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> } <span class="hljs-comment">// "true[object Object]"</span>
{ <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> } + <span class="hljs-number">1</span> <span class="hljs-comment">// 1</span>
</code></pre>
<p>JavaScript can calculate between boolean and numeric types, because boolean values <code>true</code> and <code>false</code> implicitly has the numeric value of <code>1</code> and <code>0</code>:</p>
<pre><code class="lang-js"><span class="hljs-literal">true</span> + <span class="hljs-number">1</span> <span class="hljs-comment">// 1+1 = 2</span>
<span class="hljs-literal">false</span> + <span class="hljs-number">1</span> <span class="hljs-comment">// 0+1 = 1</span>
[<span class="hljs-number">1</span>,<span class="hljs-number">2</span>] + <span class="hljs-number">1</span> <span class="hljs-comment">// "1,21"</span>
</code></pre>
<p>Type coercion is always performed <strong>implicitly</strong>. When you assign the value as a variable, the variable type will never change outside of the operation:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myNumber = <span class="hljs-number">1</span>;
<span class="hljs-built_in">console</span>.log(myNumber + <span class="hljs-string">"1"</span>); <span class="hljs-comment">// prints 11</span>
<span class="hljs-built_in">console</span>.log(myNumber); <span class="hljs-comment">// still prints number 1 and not string</span>
</code></pre>
<p>You can try to find some more on your own, but you hopefully understand what type coercion is and how it works by now.</p>
<h3 id="heading-why-you-should-avoid-type-coercion">Why you should avoid type coercion</h3>
<p>JavaScript developers are generally divided into two camps when talking about type coercion:</p>
<ul>
<li><p>Those who think it's a feature</p>
</li>
<li><p>Those who think it's a bug</p>
</li>
</ul>
<p>If you ask me, I would recommend that you avoid using type coercion in your code all the time.</p>
<p>The reason is that I've never found a problem where type coercion is required for the solution, and when I need to convert one type into another, it's always better to do so explicitly:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> price = <span class="hljs-string">"50"</span>;
<span class="hljs-keyword">let</span> tax = <span class="hljs-number">5</span>;

<span class="hljs-keyword">let</span> totalPrice = <span class="hljs-built_in">Number</span>(price) + <span class="hljs-built_in">Number</span>(tax);

<span class="hljs-built_in">console</span>.log(totalPrice);
</code></pre>
<p>Using explicit type conversion functions such as <code>Number()</code> and <code>String()</code> will make your code clear and transparent. You don't need to guess the correct data type required in your program.</p>
<p>Type coercion is one of the unique features in JavaScript that may confuse beginners, so it's good to clear it up early.</p>
<p>Next, we'll learn about JavaScript operators.</p>
<h2 id="heading-9-operators-in-javascript">9 - Operators in JavaScript</h2>
<p>As the name implies, operators are symbols you can use to perform operations on your data.</p>
<p>You've seen some examples of using the plus <code>+</code> operator to join multiple strings and add two numbers together. Of course, JavaScript has more than one operator as you'll discover in this section.</p>
<p>Since you've learned about data types and conversion previously, learning operators should be relatively easy.</p>
<h3 id="heading-arithmetic-operators">Arithmetic operators</h3>
<p>The arithmetic operators are used to perform mathematical operations like additions and subtractions.</p>
<p>These operators are frequently used with number data types. Here's an example:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-number">10</span> - <span class="hljs-number">3</span>); <span class="hljs-comment">// 7</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">2</span> + <span class="hljs-number">4</span>); <span class="hljs-comment">// 6</span>
</code></pre>
<p>In total, there are 8 arithmetic operators in JavaScript:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Name</td><td>Operation example</td><td>Meaning</td></tr>
</thead>
<tbody>
<tr>
<td>Addition</td><td><code>x + y</code></td><td>Returns the sum between the two operands</td></tr>
<tr>
<td>Subtraction</td><td><code>x - y</code></td><td>Returns the difference between the two operands</td></tr>
<tr>
<td>Multiplication</td><td><code>x * y</code></td><td>Returns the multiplication between the two operands</td></tr>
<tr>
<td>Exponentiation</td><td><code>x ** y</code></td><td>Returns the value of the left operand raised to the power of the right operand</td></tr>
<tr>
<td>Division</td><td><code>x / y</code></td><td>Returns the value of the left operand divided by the right operand</td></tr>
<tr>
<td>Remainder</td><td><code>x % y</code></td><td>Returns the remainder of the left operand after being divided by the right operand</td></tr>
<tr>
<td>Increment</td><td><code>x++</code></td><td>Returns the operand plus one</td></tr>
<tr>
<td>Decrement</td><td><code>x--</code></td><td>Returns the operand minus one</td></tr>
</tbody>
</table>
</div><p>These operators are pretty straightforward, so you can try them on your own.</p>
<p>As you've seen in the previous section, the <code>+</code> operator can also be used on strings data to merge multiple strings as one:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> message = <span class="hljs-string">"Hello "</span> + <span class="hljs-string">"human!"</span>;
<span class="hljs-built_in">console</span>.log(message); <span class="hljs-comment">// Hello human!</span>
</code></pre>
<p>When you add a number and a string, JavaScript will perform a type coercion and treats the number value as a string value:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> sum = <span class="hljs-string">"Hi "</span> + <span class="hljs-number">89</span>;
<span class="hljs-built_in">console</span>.log(sum); <span class="hljs-comment">// Hi 89</span>
</code></pre>
<p>Using any other arithmetic operator with strings will cause JavaScript to return a <code>NaN</code> value.</p>
<h3 id="heading-the-assignment-operator">The assignment operator</h3>
<p>The next operator to learn is the assignment operator, which is represented by the equals <code>=</code> sign.</p>
<p>In JavaScript, the assignment operator is used to assign data or a value to a variable.</p>
<p>You've seen some examples of using the assignment operator before, so here's a reminder:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Assign the string value 'Hello' to the 'message' variable</span>
<span class="hljs-keyword">let</span> message = <span class="hljs-string">"Hello"</span>;

<span class="hljs-comment">// Assign the Boolean value true to the 'on' variable</span>
<span class="hljs-keyword">let</span> on = <span class="hljs-literal">true</span>;
</code></pre>
<p>You may've noticed that the equals sign has a slightly different meaning in programming than in math, and you're correct!</p>
<p>The assignment operator isn't used to compare if a number equals another number in programming.</p>
<p>If you want to do that kind of comparison, then you need to use the equal to <code>==</code> operator.</p>
<p>Assignment operators can also be combined with arithmetic operators, so that you can add or subtract values from the left operand.</p>
<p>See the table below for the types of assignment operators:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Name</td><td>Operation example</td><td>Meaning</td></tr>
</thead>
<tbody>
<tr>
<td>Assignment</td><td><code>x = y</code></td><td><code>x = y</code></td></tr>
<tr>
<td>Addition assignment</td><td><code>x += y</code></td><td><code>x = x + y</code></td></tr>
<tr>
<td>Subtraction assignment</td><td><code>x -= y</code></td><td><code>x = x - y</code></td></tr>
<tr>
<td>Multiplication assignment</td><td><code>x *= y</code></td><td><code>x = x * y</code></td></tr>
<tr>
<td>Division assignment</td><td><code>x /= y</code></td><td><code>x = x / y</code></td></tr>
<tr>
<td>Remainder assignment</td><td><code>x %= y</code></td><td><code>x = x % y</code></td></tr>
</tbody>
</table>
</div><p>Next, let's look at comparison operators.</p>
<h3 id="heading-the-comparison-operators">The comparison operators</h3>
<p>Comparison operators are used to compare two values. The operators in this category will return Boolean values: either <code>true</code> or <code>false</code>.</p>
<p>The following table shows all comparison operators available in JavaScript:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Name</td><td>Operation example</td><td>Meaning</td></tr>
</thead>
<tbody>
<tr>
<td>Equal</td><td><code>x == y</code></td><td>Returns <code>true</code> if the operands are equal</td></tr>
<tr>
<td>Not equal</td><td><code>x != y</code></td><td>Returns <code>true</code> if the operands are not equal</td></tr>
<tr>
<td>Strict equal</td><td><code>x === y</code></td><td>Returns <code>true</code> if the operands are equal and have the same type</td></tr>
<tr>
<td>Strict not equal</td><td><code>x !== y</code></td><td>Returns <code>true</code> if the operands are not equal, or have different types</td></tr>
<tr>
<td>Greater than</td><td><code>x &gt; y</code></td><td>Returns <code>true</code> if the left operand is greater than the right operand</td></tr>
<tr>
<td>Greater than or equal</td><td><code>x &gt;= y</code></td><td>Returns <code>true</code> if the left operand is greater than or equal to the right operand</td></tr>
<tr>
<td>Less than</td><td><code>x &lt; y</code></td><td>Returns <code>true</code> if the left operand is less than the right operand</td></tr>
<tr>
<td>Less than or equal</td><td><code>x &lt;= y</code></td><td>Returns <code>true</code> if the left operand is less than or equal to the right operand</td></tr>
</tbody>
</table>
</div><p>Here are some examples of using these operators:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-number">9</span> == <span class="hljs-number">9</span>); <span class="hljs-comment">// true</span>

<span class="hljs-built_in">console</span>.log(<span class="hljs-number">9</span> != <span class="hljs-number">20</span>); <span class="hljs-comment">// true</span>

<span class="hljs-built_in">console</span>.log(<span class="hljs-number">2</span> &gt; <span class="hljs-number">10</span>); <span class="hljs-comment">// false</span>

<span class="hljs-built_in">console</span>.log(<span class="hljs-number">2</span> &lt; <span class="hljs-number">10</span>); <span class="hljs-comment">// true</span>

<span class="hljs-built_in">console</span>.log(<span class="hljs-number">5</span> &gt;= <span class="hljs-number">10</span>); <span class="hljs-comment">// false</span>

<span class="hljs-built_in">console</span>.log(<span class="hljs-number">10</span> &lt;= <span class="hljs-number">10</span>); <span class="hljs-comment">// true</span>
</code></pre>
<p>The comparison operators can also be used to compare strings like this:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"ABC"</span> == <span class="hljs-string">"ABC"</span>); <span class="hljs-comment">// true</span>

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"ABC"</span> == <span class="hljs-string">"abc"</span>); <span class="hljs-comment">// false</span>

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Z"</span> == <span class="hljs-string">"A"</span>); <span class="hljs-comment">// false</span>
</code></pre>
<p>String comparisons are case-sensitive, as shown in the example above.</p>
<p>JavaScript also has two versions of each comparison operator: loose and strict.</p>
<p>In strict mode, JavaScript will compare the types without performing a type coercion.</p>
<p>You need to add one more equal <code>=</code> symbol to the operator as follows</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"9"</span> == <span class="hljs-number">9</span>); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"9"</span> === <span class="hljs-number">9</span>); <span class="hljs-comment">// false</span>

<span class="hljs-built_in">console</span>.log(<span class="hljs-literal">true</span> == <span class="hljs-number">1</span>); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-literal">true</span> === <span class="hljs-number">1</span>); <span class="hljs-comment">// false</span>
</code></pre>
<p>You should use the strict comparison operators unless you have a specific reason not to.</p>
<h3 id="heading-logical-operators">Logical operators</h3>
<p>The logical operators are used to check whether one or more expressions result in either <code>True</code> or <code>False</code>.</p>
<p>There are three logical operators that JavaScript has:</p>
<p>| Name | Operation example | Meaning | | ----------- | ----------------- | --------------------------------------------------------------- | --- | ---------------------------------------------------------------------- | | Logical AND | <code>x &amp;&amp; y</code> | Returns <code>true</code> if all operands are <code>true</code>, else returns <code>false</code> | | Logical OR | <code>x || y</code> | Returns <code>true</code> if one of the operands is <code>true</code>, else returns <code>false</code> | | Logical NOT | <code>!x</code> | Reverse the result: returns <code>true</code> if <code>false</code> and vice versa |</p>
<p>These operators can only return Boolean values. For example, you can determine whether '7 is greater than 2' and '5 is greater than 4':</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-number">7</span> &gt; <span class="hljs-number">2</span> &amp;&amp; <span class="hljs-number">5</span> &gt; <span class="hljs-number">4</span>); <span class="hljs-comment">// true</span>
</code></pre>
<p>These logical operators follow the laws of mathematical logic:</p>
<ol>
<li><p><code>&amp;&amp;</code> AND operator - if any expression returns <code>false</code>, the result is <code>false</code></p>
</li>
<li><p><code>||</code> OR operator - if any expression returns <code>true</code>, the result is <code>true</code></p>
</li>
<li><p><code>!</code> NOT operator - negates the expression, returning the opposite.</p>
</li>
</ol>
<p>Let's have a little exercise. Try to run these statements on your computer. Can you guess the results?</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-literal">true</span> &amp;&amp; <span class="hljs-literal">false</span>);

<span class="hljs-built_in">console</span>.log(<span class="hljs-literal">false</span> || <span class="hljs-literal">false</span>);

<span class="hljs-built_in">console</span>.log(!<span class="hljs-literal">true</span>);
</code></pre>
<p>These logical operators will come in handy when you need to assert that a specific requirement is fulfilled in your code.</p>
<h3 id="heading-the-typeof-operator">The <code>typeof</code> operator</h3>
<p>JavaScript allows you to check the data type by using the <code>typeof</code> operator. To use the operator, you need to call it before specifying the data:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> x = <span class="hljs-number">5</span>;
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> x) <span class="hljs-comment">//  'number'</span>

<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> <span class="hljs-string">"Nathan"</span>) <span class="hljs-comment">// 'string'</span>

<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> <span class="hljs-literal">true</span>) <span class="hljs-comment">// 'boolean'</span>
</code></pre>
<p>The <code>typeof</code> operator returns the type of the data as a string. The 'number' type represents both integer and float types, the string and boolean represent their respective types.</p>
<h3 id="heading-exercise-3">Exercise #3</h3>
<p>Guess the result of these operators in action:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-number">19</span> % <span class="hljs-number">3</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">10</span> == <span class="hljs-number">3</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">10</span> !== <span class="hljs-string">"10"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">2</span> &lt; <span class="hljs-string">"10"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"5"</span> &gt; <span class="hljs-number">2</span>);
<span class="hljs-built_in">console</span>.log((<span class="hljs-literal">false</span> &amp;&amp; <span class="hljs-literal">true</span>) || <span class="hljs-literal">false</span>);
</code></pre>
<h2 id="heading-10-javascript-arrays">10 - JavaScript Arrays</h2>
<p>An array is an object data type that can be used to hold more than one value. An array can be a list of strings, numbers, booleans, objects, or a mix of them all.</p>
<p>To create an array, you need to use the square brackets <code>[]</code> and separate the items using a comma.</p>
<p>Here's how to create a list of strings:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> birds = [<span class="hljs-string">'Owl'</span>, <span class="hljs-string">'Eagle'</span>, <span class="hljs-string">'Parrot'</span>, <span class="hljs-string">'Falcon'</span>];
</code></pre>
<p>You can think of an array as a list of items, each stored in a locker compartment:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/10-array-as-a-locker-1.png" alt="Array as a locker illustration" width="600" height="400" loading="lazy"></p>
<p>You can also declare an empty array without any value:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> birds = [];
</code></pre>
<p>An array can also have a mix of values like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> mixedArray = [<span class="hljs-string">'Bird'</span>, <span class="hljs-literal">true</span>, <span class="hljs-number">10</span>, <span class="hljs-number">5.17</span>]
</code></pre>
<p>The array above contains a string, a boolean, an integer, and a float.</p>
<h3 id="heading-array-index-position">Array index position</h3>
<p>JavaScript remembers the position of the elements within an array. The position of an element is also called an index number.</p>
<p>Going back to the locker example, you can think of index numbers as the locker numbers. The index number starts from <code>0</code> as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/10-array-index-analogy.png" alt="Array index numbers as locker numbers" width="600" height="400" loading="lazy"></p>
<p>To access or change the value of an array, you need to add the square brackets notation <code>[x]</code> next to the array name, where <code>x</code> is the index number of that element. Here's an example:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Access the first element in the array</span>
myArray[<span class="hljs-number">0</span>];

<span class="hljs-comment">// Access the second element in the array</span>
myArray[<span class="hljs-number">1</span>];
</code></pre>
<p>Suppose you want to print the string 'Owl' from the <code>birds</code> array. Here's how you can do it.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> birds = [<span class="hljs-string">'Owl'</span>, <span class="hljs-string">'Eagle'</span>, <span class="hljs-string">'Parrot'</span>, <span class="hljs-string">'Falcon'</span>];

<span class="hljs-built_in">console</span>.log(birds[<span class="hljs-number">0</span>]); <span class="hljs-comment">// Owl</span>
<span class="hljs-built_in">console</span>.log(birds[<span class="hljs-number">1</span>]); <span class="hljs-comment">// Eagle</span>
</code></pre>
<p>There you go. You need to type the name of the array, followed by the index number wrapped in square brackets.</p>
<p>You can also assign a new value to a specific index using the assignment operator.</p>
<p>Let's replace 'Parrot' with 'Vulture':</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> birds = [<span class="hljs-string">'Owl'</span>, <span class="hljs-string">'Eagle'</span>, <span class="hljs-string">'Parrot'</span>, <span class="hljs-string">'Falcon'</span>];
birds[<span class="hljs-number">2</span>] = <span class="hljs-string">'Vulture'</span>;

<span class="hljs-built_in">console</span>.log(birds);
<span class="hljs-comment">// ['Owl', 'Eagle', 'Vulture', 'Falcon']</span>
</code></pre>
<p>Because the array index starts from zero, the value 'Parrot' is stored at index 2 and not 3.</p>
<h3 id="heading-special-methods-for-array-manipulation">Special methods for array manipulation</h3>
<p>Since array is an object, you can call methods that are provided by JavaScript to manipulate the array values.</p>
<p>For example, you can use the <code>push()</code> method to add an item to the end of the array:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> birds = [<span class="hljs-string">'Owl'</span>, <span class="hljs-string">'Eagle'</span>];

birds.push(<span class="hljs-string">'Sparrow'</span>);

<span class="hljs-built_in">console</span>.log(birds);
<span class="hljs-comment">// ['Owl', 'Eagle', 'Sparrow']</span>
</code></pre>
<p>Another method called <code>pop()</code> can be used to remove an item from the end of an array:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> birds = [<span class="hljs-string">'Owl'</span>, <span class="hljs-string">'Eagle'</span>, <span class="hljs-string">'Sparrow'</span>];

birds.pop();

<span class="hljs-built_in">console</span>.log(birds);
<span class="hljs-comment">// ['Owl', 'Eagle']</span>
</code></pre>
<p>The <code>unshift()</code> method can be used to add an item from the front at index 0:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> fishes = [<span class="hljs-string">'Salmon'</span>, <span class="hljs-string">'Goldfish'</span>, <span class="hljs-string">'Tuna'</span>];

fishes.unshift(<span class="hljs-string">'Sardine'</span>);

<span class="hljs-built_in">console</span>.log(fishes);
<span class="hljs-comment">// ['Sardine', 'Salmon', 'Goldfish', 'Tuna']</span>
</code></pre>
<p>On the other hand, the <code>shift()</code> method can be used to remove an item from index 0:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> fishes = [<span class="hljs-string">'Salmon'</span>, <span class="hljs-string">'Goldfish'</span>, <span class="hljs-string">'Tuna'</span>];

fishes.shift();

<span class="hljs-built_in">console</span>.log(fishes);
<span class="hljs-comment">// ['Goldfish', 'Tuna']</span>
</code></pre>
<p>The <code>indexOf()</code> method can be used to find and return the index of an item in the array.</p>
<p>The method will return <code>-1</code> when the item isn't found inside the array:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> fishes = [<span class="hljs-string">'Salmon'</span>, <span class="hljs-string">'Goldfish'</span>, <span class="hljs-string">'Tuna'</span>];

<span class="hljs-keyword">let</span> pos = fishes.indexOf(<span class="hljs-string">'Tuna'</span>);

<span class="hljs-built_in">console</span>.log(pos); <span class="hljs-comment">// 2</span>
</code></pre>
<p>To get the size of an array, you can access the <code>length</code> property:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> fishes = [<span class="hljs-string">'Salmon'</span>, <span class="hljs-string">'Goldfish'</span>, <span class="hljs-string">'Tuna'</span>];

<span class="hljs-built_in">console</span>.log(fishes.length); <span class="hljs-comment">// 3</span>
</code></pre>
<p>Note that we don't add parentheses next to the <code>length</code> keyword above. This is because <code>length</code> is a property of the array object and not a method.</p>
<p>We'll learn more about objects in the coming tutorials.</p>
<h3 id="heading-exercise-4">Exercise #4</h3>
<p>Create an array named <code>colors</code> that include the 'red', 'green, and 'blue' colors.</p>
<p>First, add a 'black' color after the last index of the array. Then print the array.</p>
<p>Next, remove the value 'red' and swap the position of 'green' and 'blue'. Print the array.</p>
<p>Finally, add the color 'yellow' on the first index of the array, then print the array.</p>
<p>The result output is as follows:</p>
<pre><code class="lang-txt">[ 'red', 'green', 'blue', 'black' ]
[ 'blue', 'green', 'black' ]
[ 'yellow', 'blue', 'green', 'black' ]
</code></pre>
<p>You need to modify the original array using the methods explained in this section.</p>
<h2 id="heading-11-control-flows-conditionals-in-javascript">11 - Control Flows (Conditionals) in JavaScript</h2>
<p>Up until now, the JavaScript code you've written is executed line by line from top to bottom. But what if you want to run some lines of code only when a certain condition is met?</p>
<p>A computer program usually needs to take into account many different conditions that can arise during the program's execution.</p>
<p>This is similar to how a human makes decisions in their life. For example, do you have money to cover the vacation to Japan? If yes, go. If not, then save more money!</p>
<p>This is where control flow comes in. <strong>Control flow</strong> is a feature in a programming language that allows you to selectively run specific code based on the different conditions that may arise.</p>
<p>Using control flows allows you to define multiple paths a program can take based on the conditions present in your program.</p>
<p>There are two types of control flows commonly used in JavaScript: conditionals and loops.</p>
<p>This section will focus on the conditional statements such as:</p>
<ol>
<li><p><code>if...else</code> statement</p>
</li>
<li><p><code>switch...case</code> statement</p>
</li>
</ol>
<p>You'll learn about loop statements in the next section.</p>
<h3 id="heading-the-ifelse-statement">The if...else statement</h3>
<p>The <code>if</code> statement allows you to create a program that runs only if a specific condition is met.</p>
<p>The syntax for the <code>if</code> statement is as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">if</span> (condition) {
  <span class="hljs-comment">// code to execute if condition is true</span>
}
</code></pre>
<p>Let's see an example. Suppose you want to go on a vacation that requires 5000 dollars.</p>
<p>Using the <code>if</code> statement, here's how you check if you have enough balance:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> balance = <span class="hljs-number">7000</span>;

<span class="hljs-keyword">if</span> (balance &gt; <span class="hljs-number">5000</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"You have the money for this trip. Let's go!"</span>);
}
</code></pre>
<p>Run the code above once, and you'll see the string printed on the terminal.</p>
<p>Now change the value of <code>balance</code> to <code>3000</code> and you'll get no response.</p>
<p>This happens because the code inside the <code>if</code> statement is only executed when the condition is <code>true</code>.</p>
<p>After the <code>if</code> statement, you can write another line of code below it as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> balance = <span class="hljs-number">7000</span>;

<span class="hljs-keyword">if</span> (balance &gt; <span class="hljs-number">5000</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"You have the money for this trip. Let's go!"</span>);
}
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The end!"</span>);
</code></pre>
<p>The second <code>console.log()</code> call above will be executed no matter what value you assign to the <code>balance</code> variable.</p>
<p>If you want it to execute only when the <code>if</code> condition is met, then put the line inside the curly brackets as well:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> balance = <span class="hljs-number">7000</span>;

<span class="hljs-keyword">if</span> (balance &gt; <span class="hljs-number">5000</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"You have the money for this trip. Let's go!"</span>);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The end!"</span>);
}
</code></pre>
<p>Next, suppose you need to run some code only when the <code>if</code> statement condition is not fulfilled.</p>
<p>This is where the <code>else</code> statement comes in. The <code>else</code> statement is used to run code only when the <code>if</code> statement is not fulfilled.</p>
<p>Here's an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> balance = <span class="hljs-number">7000</span>;

<span class="hljs-keyword">if</span> (balance &gt; <span class="hljs-number">5000</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"You have the money for this trip. Let's go!"</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Sorry, not enough money. Save more!"</span>);
}
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The end!"</span>);
</code></pre>
<p>Now change the value of <code>balance</code> to be less than <code>5000</code>, and you'll trigger the <code>else</code> block in the example.</p>
<p>JavaScript also has the <code>else if</code> statement which allows you to write another condition to check should the <code>if</code> statement condition isn't met.</p>
<p>Consider the example below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> balance = <span class="hljs-number">7000</span>;

<span class="hljs-keyword">if</span> (balance &gt; <span class="hljs-number">5000</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"You have the money for this trip. Let's go!"</span>);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (balance &gt; <span class="hljs-number">3000</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"You only have enough money for a staycation"</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Sorry, not enough money. Save more!"</span>);
}
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The end!"</span>);
</code></pre>
<p>When the <code>balance</code> amount is less than <code>5000</code>, the <code>else if</code> statement will check if the <code>balance</code> is more than <code>3000</code>. If it does, then the program will proceed to recommend you do a staycation.</p>
<p>You can write as many <code>else if</code> statements as you need, and each one will be executed only if the previous statement isn't met.</p>
<p>Together, the <code>if..else..else if</code> statements allow you to execute different blocks of code depending on the condition the program faced.</p>
<h3 id="heading-the-switchcase-statement">The switch...case statement</h3>
<p>The <code>switch</code> statement is a part of core JavaScript syntax that allows you to control the execution flow of your code.</p>
<p>It's often thought of as an alternative to the <code>if..else</code> statement that gives you more readable code, especially when you have many different conditions to assess.</p>
<p>Here's an example of a working <code>switch</code> statement. I will explain the code below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> age = <span class="hljs-number">15</span>;
<span class="hljs-keyword">switch</span> (age) {
  <span class="hljs-keyword">case</span> <span class="hljs-number">10</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Age is 10"</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-number">20</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Age is 20"</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">default</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Age is neither 10 or 20"</span>);
}
</code></pre>
<p>First, you need to pass an expression to be evaluated by the <code>switch</code> statement into the parentheses. In the example, the <code>age</code> variable is passed as an argument for evaluation.</p>
<p>Then, you need to write the <code>case</code> values that the <code>switch</code> statement will try to match with your expression. The <code>case</code> value is immediately followed by a colon (<code>:</code>) to mark the start of the case block:</p>
<pre><code class="lang-js"><span class="hljs-keyword">case</span> <span class="hljs-string">"apple"</span>:
</code></pre>
<p>Keep in mind the data type of the <code>case</code> value that you want to match with the expression. If you want to match a <code>string</code>, then you need to put a <code>string</code>. <code>switch</code> statements <strong>won't perform type coercion</strong> when you have a <code>number</code> as the argument but put a <code>string</code> for the case:</p>
<pre><code class="lang-js"><span class="hljs-keyword">switch</span> (<span class="hljs-number">1</span>) {
  <span class="hljs-keyword">case</span> <span class="hljs-string">"1"</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World!"</span>);
    <span class="hljs-keyword">break</span>;
}
</code></pre>
<p>The number expression doesn't match the string case value, so JavaScript won't log anything to the console.</p>
<p>The same also happens for boolean values. The number <code>1</code> won't be coerced as <code>true</code> and the number <code>0</code> won't be coerced as <code>false</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">switch</span> (<span class="hljs-number">0</span>) {
  <span class="hljs-keyword">case</span> <span class="hljs-literal">true</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello True!"</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-literal">false</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Bonjour False!"</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">default</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"No matching case"</span>);
}
</code></pre>
<h3 id="heading-the-switch-statement-body">The switch statement body</h3>
<p>The <code>switch</code> statement body is composed of three keywords:</p>
<ul>
<li><p><code>case</code> keyword for starting a case block</p>
</li>
<li><p><code>break</code> keyword for stopping the <code>switch</code> statement from running the next <code>case</code></p>
</li>
<li><p><code>default</code> keyword for running a piece of code when no matching <code>case</code> is found.</p>
</li>
</ul>
<p>When your expression finds a matching <code>case</code>, JavaScript will execute the code following the <code>case</code> statement until it finds the <code>break</code> keyword. If you omit the <code>break</code> keyword, then the code execution will continue to the next block.</p>
<p>Take a look at the following example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">switch</span> (<span class="hljs-number">0</span>) {
  <span class="hljs-keyword">case</span> <span class="hljs-number">1</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Value is one"</span>);
  <span class="hljs-keyword">case</span> <span class="hljs-number">0</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Value is zero"</span>);
  <span class="hljs-keyword">default</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"No matching case"</span>);
}
</code></pre>
<p>When you execute the code above, JavaScript will print the following log:</p>
<pre><code class="lang-shell">&gt; "Value is zero"
&gt; "No matching case"
</code></pre>
<p>This is because without the <code>break</code> keyword, <code>switch</code> will continue to evaluate the expression against the remaining cases even when a matching case is already found.</p>
<p>Your switch evaluation may match more than one case, so the <code>break</code> keyword is commonly used to exit the process once a match is found.</p>
<p>Finally, you can also put expressions as <code>case</code> values:</p>
<pre><code class="lang-js"><span class="hljs-keyword">switch</span> (<span class="hljs-number">20</span>) {
  <span class="hljs-keyword">case</span> <span class="hljs-number">10</span> + <span class="hljs-number">10</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"value is twenty"</span>);
    <span class="hljs-keyword">break</span>;
}
</code></pre>
<p>But you need to keep in mind that the value for a <code>case</code> block <strong>must exactly match</strong> the <code>switch</code> argument.</p>
<p>One of the most common mistakes when using the <code>switch</code> statement is that people think <code>case</code> value gets evaluated as <code>true</code> or <code>false</code>.</p>
<p>The following <code>case</code> blocks won't work in <code>switch</code> statements:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> age = <span class="hljs-number">5</span>;

<span class="hljs-keyword">switch</span> (age) {
  <span class="hljs-keyword">case</span> age &lt; <span class="hljs-number">10</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Value is less than ten"</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> age &lt; <span class="hljs-number">20</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Value is less than twenty"</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">default</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Value is twenty or more"</span>);
}
</code></pre>
<p>You need to remember the differences between the <code>if</code> and <code>case</code> evaluations:</p>
<ul>
<li><p><code>if</code> block will be executed when the test condition <strong>evaluates to</strong> <code>true</code></p>
</li>
<li><p><code>case</code> block will be executed when the test condition <strong>exactly matches</strong> the given <code>switch</code> argument</p>
</li>
</ul>
<h3 id="heading-switch-statement-use-cases">Switch statement use cases</h3>
<p>The rule of thumb when you consider between <code>if</code> and <code>switch</code> is this:</p>
<blockquote>
<p>You only use <code>switch</code> when the code is cumbersome to write using <code>if</code></p>
</blockquote>
<p>For example, let's say you want to write a weekday name based on the weekday number</p>
<p>Here's how you can write it:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> weekdayNumber = <span class="hljs-number">1</span>;

<span class="hljs-keyword">if</span> (weekdayNumber === <span class="hljs-number">0</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Sunday"</span>);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (weekdayNumber === <span class="hljs-number">1</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Monday"</span>);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (weekdayNumber === <span class="hljs-number">2</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Tuesday"</span>);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (weekdayNumber === <span class="hljs-number">3</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Wednesday"</span>);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (weekdayNumber === <span class="hljs-number">4</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Thursday"</span>);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (weekdayNumber === <span class="hljs-number">5</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Friday"</span>);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (weekdayNumber === <span class="hljs-number">6</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Saturday"</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The weekday number is invalid"</span>);
}
</code></pre>
<p>I don't know about you, but the code above sure looks cumbersome to me! Although there's nothing wrong with the code above, you can make it prettier with <code>switch</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> weekdayNumber = <span class="hljs-number">1</span>;

<span class="hljs-keyword">switch</span> (weekdayNumber) {
  <span class="hljs-keyword">case</span> <span class="hljs-number">0</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Sunday"</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-number">1</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Monday"</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-number">2</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Tuesday"</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-number">3</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Wednesday"</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-number">4</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Thursday"</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-number">5</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Friday"</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-number">6</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Saturday"</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">default</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The weekday number is invalid"</span>);
}
</code></pre>
<p>When you have lots of condition to evaluate for the same block, you'd probably combine multiple <code>if</code> conditions using the logical operator <strong>AND (</strong><code>&amp;&amp;</code>) or <strong>OR(</strong><code>||</code>):</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myFood = <span class="hljs-string">"Banana"</span>;

<span class="hljs-keyword">if</span> (myFood === <span class="hljs-string">"Banana"</span> || myFood === <span class="hljs-string">"Apple"</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Eat fruits everyday to keep you healthy."</span>);
}

<span class="hljs-keyword">if</span> (myFood === <span class="hljs-string">"Chocolate Cake"</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Enjoy the sweet treat."</span>);
}
</code></pre>
<p>You can replace the code above using the switch statement. The key is you need to stack multiple <code>cases</code> as one just like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myFood = <span class="hljs-string">"Banana"</span>;

<span class="hljs-keyword">switch</span> (myFood) {
  <span class="hljs-keyword">case</span> <span class="hljs-string">"Banana"</span>:
  <span class="hljs-keyword">case</span> <span class="hljs-string">"Apple"</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Eat fruits everyday to keep you healthy."</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-string">"Chocolate Cake"</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Enjoy the sweet treat."</span>);
    <span class="hljs-keyword">break</span>;
}
</code></pre>
<p>Unfortunately, <code>switch</code> can't replace multiple <code>if</code> conditions that use the <code>&amp;&amp;</code> operator because of the way the <code>case</code> evaluation works. You need to use the <code>if</code> statement for that.</p>
<h3 id="heading-exercise-5">Exercise #5</h3>
<p>A primary school is giving different rewards based on the student's grade:</p>
<ul>
<li><p>Students that got an A will get a Chocolate</p>
</li>
<li><p>Students that got a B will get a Cookie</p>
</li>
<li><p>Students that got a C will get a Candy</p>
</li>
<li><p>For any other value, print "No reward to give."</p>
</li>
</ul>
<p>Create a variable named <code>grade</code> that will store the student's grade.</p>
<p>Example output:</p>
<pre><code class="lang-txt">You got an A, so here's a Chocolate for you!
You got a B, here's a Cookie for you!
You got a C, there's room for improvement and here's your Candy!
</code></pre>
<p>You can use either the <code>if...else</code> or the <code>switch...case</code> statement.</p>
<h2 id="heading-12-control-flows-loops-in-javascript">12 - Control Flows (Loops) in JavaScript</h2>
<p>As you program an application in JavaScript, you'll often need to write a piece of code that needs to be executed repeatedly.</p>
<p>Let's say you want to write a program that prints the numbers 1 to 10 in the console. You can do it by calling <code>console.log</code> 10 times like this:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-number">1</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">2</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">3</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">4</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">5</span>);

<span class="hljs-comment">// and so on..</span>
</code></pre>
<p>This works, but there's a better way to write this kind of repetitive task.</p>
<p>A <strong>Loop statement</strong> is another category of control flow statement used to execute a block of code multiple times until a certain condition is met.</p>
<p>There are two loop statements used in JavaScript:</p>
<ul>
<li><p>The <code>for</code> statement</p>
</li>
<li><p>The <code>while</code> statement</p>
</li>
</ul>
<p>Let's learn how to use these statements in practice.</p>
<h3 id="heading-the-for-statement">The for statement</h3>
<p>Instead of repeating yourself 10 times to print the numbers 1 to 10, you can use the <code>for</code> statement and write just a single line of code as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> x = <span class="hljs-number">0</span>; x &lt; <span class="hljs-number">10</span>; x++) {
  <span class="hljs-built_in">console</span>.log(x);
}
</code></pre>
<p>There you go! The <code>for</code> statement is followed by parentheses (<code>()</code>) which contain 3 expressions:</p>
<ul>
<li><p>The <code>initialization</code> expression, where you declare a variable to be used as the source of the loop condition. Represented as <code>x = 1</code> in the example.</p>
</li>
<li><p>The <code>condition</code> expression, where the variable in initialization will be evaluated for a specific condition. Represented as <code>x &lt; 11</code> in the example.</p>
</li>
<li><p>The <code>arithmetic</code> expression, where the variable value is either incremented or decremented by the end of each loop.</p>
</li>
</ul>
<p>These expressions are separated by a semicolon (<code>;</code>)</p>
<p>After the expressions, the curly brackets (<code>{}</code>) will be used to create a code block that will be executed by JavaScript as long as the <code>condition</code> expression returns <code>true</code>.</p>
<p>You can identify which expression is which by paying attention to the semicolon (<code>;</code>) which ends the statement.</p>
<pre><code class="lang-js"><span class="hljs-keyword">for</span> ( [initialization]; [condition]; [arithmetic expression]) {
  <span class="hljs-comment">// As long as condition returns true,</span>
  <span class="hljs-comment">// This block will be executed repeatedly</span>
}
</code></pre>
<p>The arithmetic expression can be an increment (<code>++</code>) or a decrement (<code>--</code>) expression. It is run once each time the execution of the code inside the curly brackets end:</p>
<pre><code class="lang-js"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> x = <span class="hljs-number">10</span>; x &gt;= <span class="hljs-number">1</span>; x--) {
  <span class="hljs-built_in">console</span>.log(x);
}
</code></pre>
<p>Or you can also use shorthand arithmetic operators like <code>+=</code> and <code>-=</code> as shown below:</p>
<pre><code class="lang-js"><span class="hljs-comment">// for statement with shorthand arithmetic expression</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> x = <span class="hljs-number">1</span>; x &lt; <span class="hljs-number">20</span>; x += <span class="hljs-number">3</span>) {
  <span class="hljs-built_in">console</span>.log(x);
}
</code></pre>
<p>Here, the x will be incremented by 3 each time the loop is executed.</p>
<p>Once the loop is over, JavaScript will continue to execute any code you write below the <code>for</code> body:</p>
<pre><code class="lang-js"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> x = <span class="hljs-number">1</span>; x &lt; <span class="hljs-number">2</span>; x++) {
  <span class="hljs-built_in">console</span>.log(x);
}
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The for loop has ended"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Continue code execution"</span>);
</code></pre>
<h3 id="heading-when-to-use-a-for-loop">When to use a for loop</h3>
<p>The for loop is useful <strong>when you know how many times</strong> you need to execute a repetitive task.</p>
<p>For example, let's say you're writing a program to flip a coin. You need to find how many times the coin lands on heads when tossed 10 times. You can do it by using the <code>Math.random</code> method:</p>
<ul>
<li><p>When the number is lower than <code>0.5</code> you need to increment the <code>tails</code> counter</p>
</li>
<li><p>When the number is <code>0.5</code> and up you must increment the <code>heads</code> counter</p>
</li>
</ul>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> heads = <span class="hljs-number">0</span>;
<span class="hljs-keyword">let</span> tails = <span class="hljs-number">0</span>;
<span class="hljs-keyword">for</span> (x = <span class="hljs-number">1</span>; x &lt;= <span class="hljs-number">10</span>; x++) {
  <span class="hljs-keyword">if</span> (<span class="hljs-built_in">Math</span>.random() &lt; <span class="hljs-number">0.5</span>) {
    tails++;
  } <span class="hljs-keyword">else</span> {
    heads++;
  }
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Tossed the coin ten times"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Number of heads: <span class="hljs-subst">${heads}</span>`</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Number of tails: <span class="hljs-subst">${tails}</span>`</span>);
</code></pre>
<p>The example above shows where the <code>for</code> loop offers the most effective approach.</p>
<p>Now let's see an alternative exercise about coin flips where the <code>for</code> loop is not effective:</p>
<p><strong><em>Find out how many times you need to flip a coin until it lands on heads.</em></strong></p>
<p>This time, you don't know <strong>how many times</strong> you need to flip the coin. This is where you need to use the <code>while</code> loop statement, which you're going to learn next.</p>
<h3 id="heading-the-while-statement">The while statement</h3>
<p>The <code>while</code> statement or <code>while</code> loop is used to run a block of code as long as the condition evaluates to <code>true</code>.</p>
<p>You can define the condition and the statement for the loop as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">while</span> (condition) {
  statement;
}
</code></pre>
<p>Just like the <code>for</code> loop, the <code>while</code> loop is used to execute a piece of code over and over again until it reaches the desired condition.</p>
<p>In the example below, we will keep executing the <em>statement</em> block until the <em>condition</em> expression returns <code>false</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>;

<span class="hljs-keyword">while</span> (i &lt; <span class="hljs-number">6</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The value of i = <span class="hljs-subst">${i}</span>`</span>);
  i++;
}
</code></pre>
<p>Here, the <code>while</code> loop will repeatedly print the value of <code>i</code> as long as <code>i</code> is less than <code>6</code>. In each iteration, the value of <code>i</code> is incremented by 1 until it reaches 6 and the loop terminates.</p>
<p>Keep in mind that you need to include a piece of code that eventually turns the evaluating condition to <code>false</code> or the <code>while</code> loop will be executed forever. The example below will cause an infinite loop:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>;

<span class="hljs-keyword">while</span> (i &lt; <span class="hljs-number">6</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The value of i = <span class="hljs-subst">${i}</span>`</span>);
}
</code></pre>
<p>Because the value of <code>i</code> never changes, the while loop will go on forever!</p>
<h3 id="heading-when-to-use-a-while-loop">When to use a while loop</h3>
<p>Seeing that both <code>while</code> and <code>for</code> can be used for executing a piece of code repeatedly, when should you use a <code>while</code> loop instead of <code>for</code>?</p>
<p>An easy way to know when you should use <code>while</code> is when <strong>you don't know how many times</strong> you need to execute the code.</p>
<p>Back to the coin toss example, there's one case that's perfect for a <code>while</code> loop:</p>
<p><strong><em>Find out how many times you need to flip a coin until it lands on heads.</em></strong></p>
<p>You also need to <strong>show how many times</strong> you flip the coin until it lands on heads:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> flips = <span class="hljs-number">0</span>;
<span class="hljs-keyword">let</span> isHeads = <span class="hljs-literal">false</span>;

<span class="hljs-keyword">while</span> (!isHeads) {
  flips++;
  isHeads = <span class="hljs-built_in">Math</span>.random() &lt; <span class="hljs-number">0.5</span>;
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`It took <span class="hljs-subst">${flips}</span> flips to land on heads.`</span>);
</code></pre>
<p>Here, the condition <code>isHead = Math.random() &lt; 0.5</code> simulates the flipping of a fair coin. When the result is <code>true</code>, it means the coin landed on heads and the loop will exit.</p>
<p>Because you can't know how many times you need to loop until you get heads, you need to use a <code>while</code> loop instead of a <code>for</code> loop.</p>
<h3 id="heading-exercise-6">Exercise #6</h3>
<p>Write a program that prints a half pyramid using asterisks <code>*</code> as shown below:</p>
<pre><code class="lang-txt">*
**
***
****
*****
</code></pre>
<p>Next, print a reverse half pyramid as follows:</p>
<pre><code class="lang-txt">*****
****
***
**
*
</code></pre>
<h2 id="heading-13-functions-in-javascript">13 - Functions in JavaScript</h2>
<p>A function is simply a section (or a block) of code that's written to perform a specific task.</p>
<p>For example, the type casting function <code>String()</code> is used to convert data of another type to a string.</p>
<p>The <code>console.log()</code> and various array methods we've learned in previous chapters are also functions. But because these functions are called from an object, they are called methods.</p>
<p>You'll learn more about methods later in Chapter 14. For now, just know that a function and a method are essentially the same, except that a method is called from an object.</p>
<p>Besides the built-in functions provided by JavaScript, you can also create your own function.</p>
<h3 id="heading-how-to-create-your-own-function">How to create your own function</h3>
<p>Creating a function starts with typing the <code>function</code> keyword followed by the function name, a pair of round brackets, and then a pair of curly brackets.</p>
<p>Here's an example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// function body here</span>
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello!"</span>);
}
</code></pre>
<p>To call a function, you need to specify the function name followed by parentheses:</p>
<pre><code class="lang-js">greet(); <span class="hljs-comment">// Hello!</span>
</code></pre>
<p>The code inside the function is executed when you call that function.</p>
<h3 id="heading-function-parameters-and-arguments">Function parameters and arguments</h3>
<p>Parameters are variables used to accept inputs given when the function is called.</p>
<p>You can specify parameters in the function header, inside the parentheses.</p>
<p>The following example shows a function that has one parameter called <code>name</code>:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-comment">// function body</span>
}
</code></pre>
<p>How you use that <code>name</code> parameter inside the function is up to you.</p>
<p>You can use the parameter inside the <code>print()</code> function as follows:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Nice weather today, right?"</span>);
}
</code></pre>
<p>Now whenever you need to call the <code>greet()</code> function, you need to pass an input to fill for the <code>name</code> parameter.</p>
<p>The input you passed to fill a parameter is called an argument, and here's how to do it:</p>
<pre><code class="lang-js">greet(<span class="hljs-string">"Peter"</span>);
</code></pre>
<p>The 'Peter' string inside the parentheses when calling the <code>greet()</code> function will be passed as the <code>name</code> parameter.</p>
<p>Run the code to receive this output:</p>
<pre><code class="lang-txt">Hello, Peter!
Nice weather today, right?
</code></pre>
<p>You can have more than one parameter when defining the function, but you need to split each parameter with a comma as follows:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name, weather</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`It's <span class="hljs-subst">${weather}</span> today, right?`</span>);
}

greet(<span class="hljs-string">"Nathan"</span>, <span class="hljs-string">"rainy"</span>);
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-txt">Hello, Nathan!
It's rainy today, right?
</code></pre>
<p>When you specify two parameters in the function header, you need to pass two arguments. If you call the function without passing the arguments then the value will be <code>undefined</code>.</p>
<p>In the next section, you'll learn how to create parameters with default values, which allows you to call the function without having to pass an argument to it.</p>
<p>But for now, I hope you see the convenience of having parameters. They make your functions more adaptable and reusable by taking different input values to cover a variety of scenarios the function might have.</p>
<p>As shown in the example, the <code>name</code> and <code>weather</code> parameters allow you to greet many different people in different weathers.</p>
<p>Whether sunny, rainy, or cloudy, just change the <code>name</code> and <code>weather</code> arguments when you want to greet another person.</p>
<h3 id="heading-default-parameters">Default parameters</h3>
<p>When defining a function, you can set a default value for any parameter in that function.</p>
<p>For example, the <code>name</code> parameter in the function below is a default parameter:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name = <span class="hljs-string">"Nathan"</span></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Nice weather today, right?"</span>);
}
</code></pre>
<p>Here, the default value 'Nathan' will be used when no value or <code>undefined</code> is passed for the <code>name</code> parameter.</p>
<p>You can test this by calling the <code>greet()</code> function without an argument as follows:</p>
<pre><code class="lang-js">greet();
greet(<span class="hljs-string">"Jack"</span>);
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-txt">Hello, Nathan!
Nice weather today, right?

Hello, Jack!
Nice weather today, right?
</code></pre>
<p>Any function you define can have a mix of default and non-default parameters.</p>
<p>Here's another example of a function that has one default parameter called <code>name</code> and one non-default parameter called <code>weather</code>:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">weather, name = <span class="hljs-string">"Nathan"</span></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`It's <span class="hljs-subst">${weather}</span> today, right?`</span>);
}

greet(<span class="hljs-string">"sunny"</span>);
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-txt">Hello, Nathan!
It's sunny today, right?
</code></pre>
<p>Notice that the <code>weather</code> parameter was placed in front of the <code>name</code> parameter. This is for convenience so that you don't need to specify the default parameter.</p>
<p>If you place the non-default parameter after the default parameter, then you need to pass a value to the <code>name</code> parameter to get to the <code>weather</code> parameter.</p>
<p>Consider the example below:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name = <span class="hljs-string">"Nathan"</span>, weather</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`It's <span class="hljs-subst">${weather}</span> today, right?`</span>);
}

greet(<span class="hljs-literal">undefined</span>, <span class="hljs-string">"sunny"</span>);
</code></pre>
<p>To pass an argument to the <code>weather</code> parameter, we need to pass <code>undefined</code> or any value for the <code>name</code> parameter first.</p>
<p>This is why it's better to specify non-default parameters in front of default parameters.</p>
<h3 id="heading-default-parameters-and-null">Default parameters and null</h3>
<p>Back in Chapter 7, recall that we briefly explored the difference between <code>undefined</code> as the "default" empty value and <code>null</code> as the "intentional" empty value.</p>
<p>When you pass <code>undefined</code> to a function that has a default parameter, the default parameter will be used:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name = <span class="hljs-string">"John"</span></span>)</span>{
  <span class="hljs-built_in">console</span>.log(name);
}

greet(<span class="hljs-literal">undefined</span>); <span class="hljs-comment">// John</span>
</code></pre>
<p>As you can see, JavaScript prints the default parameter value <code>John</code> when you pass <code>undefined</code> to the function.</p>
<p>But when you pass <code>null</code> to the function, the default parameter will be ignored:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name = <span class="hljs-string">"John"</span></span>)</span>{
  <span class="hljs-built_in">console</span>.log(name);
}

greet(<span class="hljs-literal">null</span>); <span class="hljs-comment">// null</span>
</code></pre>
<p>This is one of the common mistakes that beginners make when learning JavaScript. When you use the value <code>null</code>, JavaScript will think you want that value to be empty, so it doesn't replace the value with the default parameter.</p>
<p>When you use <code>undefined</code>, then JavaScript will replace it with the default parameter. You might encounter this issue as you work with JavaScript code in your career, so just keep this in mind.</p>
<h3 id="heading-the-return-statement">The return statement</h3>
<p>A function can also have a <code>return</code> statement inside the code block. A <code>return</code> statement is used to return a value back to the caller.</p>
<p>For example, the following function returns the sum of two values:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-keyword">return</span> a + b;
}

<span class="hljs-keyword">let</span> result = sum(<span class="hljs-number">3</span>, <span class="hljs-number">2</span>);
<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// 5</span>
</code></pre>
<p>The value returned by a function can be assigned to a variable for further operation. You can add the <code>return</code> statement anywhere inside the function.</p>
<p>When JavaScript reaches the <code>return</code> statement, it skips further code written inside the function block and goes back to where you call the function.</p>
<p>The following function has two return statements:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">checkAge</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-string">"You may get a car license"</span>;
  }
  <span class="hljs-keyword">return</span> <span class="hljs-string">"You may not get a car license yet"</span>;
}

<span class="hljs-built_in">console</span>.log(checkAge(<span class="hljs-number">20</span>));
<span class="hljs-built_in">console</span>.log(checkAge(<span class="hljs-number">15</span>));
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-txt">You may get a car license
You may not get a car license yet
</code></pre>
<p>When we call the <code>checkAge()</code> function the first time, the value of <code>age</code> argument is greater than 18, so JavaScript executes the <code>return</code> statement inside the <code>if</code> block.</p>
<p>The second time we called the function, the <code>if</code> condition isn't met, so JavaScript executes the <code>return</code> statement under the <code>if</code> block instead.</p>
<p>You can also stop a function execution and return to the caller by specifying the <code>return</code> statement without any value:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello!"</span>);
  <span class="hljs-keyword">return</span>;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Good bye!"</span>);
}

greet()
</code></pre>
<p>Output:</p>
<pre><code class="lang-txt">Hello!
</code></pre>
<p>Here, the <code>return</code> statement is called between the <code>console.log()</code> calls.</p>
<p>JavaScript executes the first <code>console.log()</code> call, then skips the rest of the code. The 'Good bye!' string isn't printed.</p>
<h3 id="heading-variable-scope">Variable scope</h3>
<p>Now that you're learning about functions, it's a good time to talk about variable scope.</p>
<p>A variable declared inside a function can only be accessed from that function. This is because that variable has a local scope.</p>
<p>On the other hand, a variable declared outside of any block is known as a global variable because of its global scope.</p>
<p>These two scopes are important because when you try to access a local variable outside of its scope, you'll get an error. For example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> myString = <span class="hljs-string">"Hello World!"</span>;
}

greet();
<span class="hljs-built_in">console</span>.log(myString);
</code></pre>
<p>When you run the code above, JavaScript responds with an error:</p>
<pre><code class="lang-txt">ReferenceError: myString is not defined
</code></pre>
<p>This is because the <code>myString</code> variable is declared inside the <code>greet()</code> function, so you can't access that variable outside of it. It doesn't matter even if you called that function before accessing the variable.</p>
<p>Meanwhile, a global variable can be accessed from anywhere, even inside a function:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myString = <span class="hljs-string">"Hello World!"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(myString);
}

greet(); <span class="hljs-comment">// Hello World!</span>
</code></pre>
<p>Here, the <code>greet()</code> function is able to access the <code>myString</code> variable declared outside of it.</p>
<p>Keep in mind that this applies only to variables declared using <code>let</code> and <code>const</code>.</p>
<p>Next, you can also define a local variable with the same name as the global variable without overwriting it.</p>
<p>Here's an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myString = <span class="hljs-string">"Hello World!"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> myString = <span class="hljs-string">"Morning!"</span>;
  <span class="hljs-built_in">console</span>.log(myString);
}

greet();  <span class="hljs-comment">// Morning!</span>
<span class="hljs-built_in">console</span>.log(myString); <span class="hljs-comment">// Hello World!</span>
</code></pre>
<p>When you call the <code>greet()</code> function, a local variable called <code>myString</code> was assigned the string 'Morning!'.</p>
<p>Outside of the function, the global variable that's also called <code>myString</code> still exists, and the value isn't changed.</p>
<p>JavaScript considers the local scope variable to be a different variable. When you declare the same variable inside a function, any code inside the function will always refer to the local variable.</p>
<p>In practice, you rarely need to declare the same variable in different scopes:</p>
<ol>
<li><p>Any variable declared outside a function shouldn't be used inside a function without passing them as parameters.</p>
</li>
<li><p>A variable declared inside a function should never be referred to outside of that function</p>
</li>
</ol>
<p>Keep this in mind when you write JavaScript functions.</p>
<h3 id="heading-the-rest-parameter">The rest parameter</h3>
<p>The rest parameter is a parameter that can accept any number of data as its arguments. The arguments will be stored as an array.</p>
<p>You can define a rest parameter in the function header by adding triple dots <code>...</code> before the parameter name.</p>
<p>Here's an example of creating a function that has a variable length argument:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printArguments</span>(<span class="hljs-params">...args</span>)</span>{
    <span class="hljs-built_in">console</span>.log(args);
}
</code></pre>
<p>When calling the <code>printArguments()</code> function above, you can specify as many arguments as you want:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printArguments</span>(<span class="hljs-params">...args</span>)</span>{
    <span class="hljs-built_in">console</span>.log(args);
}

printArguments(<span class="hljs-string">"A"</span>, <span class="hljs-string">"B"</span>, <span class="hljs-string">"C"</span>); 
<span class="hljs-comment">// [ 'A', 'B', 'C' ]</span>
printArguments(<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-comment">// [ 1, 2, 3, 4, 5 ]</span>
</code></pre>
<p>Keep in mind that a function can only have one rest parameter, and the rest parameter must be the last parameter in the function.</p>
<p>You can use a rest parameter when your function needs to work with an indefinite number of arguments.</p>
<h3 id="heading-arrow-function">Arrow function</h3>
<p>The <strong>JavaScript arrow function syntax</strong> allows you to write a JavaScript function with a shorter, more concise syntax.</p>
<p>When you need to create a function in JavaScript, the primary method is to use the <code>function</code> keyword followed by the function name as shown below:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetings</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>);
}

greetings(<span class="hljs-string">"John"</span>); <span class="hljs-comment">// Hello, John!</span>
</code></pre>
<p>The arrow function syntax allows you to create a function expression that produces the same result as the code above.</p>
<p>Here's the <code>greetings()</code> function using the arrow syntax:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> greetings = <span class="hljs-function">(<span class="hljs-params">name</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>);
};

greetings(<span class="hljs-string">"John"</span>); <span class="hljs-comment">// Hello, John!</span>
</code></pre>
<p>When you create a function using the arrow function syntax, you need to assign the expression to a variable so that the function has a name.</p>
<p>Basically, the arrow function syntax looks as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fun = <span class="hljs-function">(<span class="hljs-params">param1, param2, ...</span>) =&gt;</span> {
  <span class="hljs-comment">// function body</span>
}
</code></pre>
<p>In the code above,</p>
<ul>
<li><p><code>fun</code> is the variable that holds the function. You can call the function as <code>fun()</code> later in your code.</p>
</li>
<li><p><code>(param1, param2, ...)</code> are the function parameters. You can define as many parameters as required by the function.</p>
</li>
<li><p>Then you have the arrow <code>=&gt;</code> to indicate the beginning of the function.</p>
</li>
</ul>
<p>The code above is equal to the following:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fun = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">param1, param2, ...</span>) </span>{
  <span class="hljs-comment">// function body</span>
}
</code></pre>
<p>The arrow function syntax doesn't add any new ability to the JavaScript language.</p>
<p>Instead, it offers improvements to the way you write a function in JavaScript.</p>
<p>At first, it may seem weird as you are used to the <code>function</code> keyword.</p>
<p>But as you start using the arrow syntax, you will see that it's very convenient and easier to write.</p>
<h3 id="heading-single-and-multiline-arrow-functions">Single and multiline arrow functions</h3>
<p>The arrow function provides you a way to write a single line function where the left side of the arrow <code>=&gt;</code> is returned to the right side.</p>
<p>When you use the <code>function</code> keyword, you need to use the curly brackets <code>{}</code> and the <code>return</code> keyword as follows:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">plusTwo</span>(<span class="hljs-params">num</span>) </span>{
  <span class="hljs-keyword">return</span> num + <span class="hljs-number">2</span>;
}
</code></pre>
<p>Using the arrow function, you can omit both the curly brackets and the <code>return</code> keyword, creating a single line function as shown below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> plusTwo = <span class="hljs-function">(<span class="hljs-params">num</span>) =&gt;</span> num + <span class="hljs-number">2</span>;
</code></pre>
<p>Without the curly brackets, JavaScript will evaluate the expression on the right side of the arrow syntax and return it to the caller.</p>
<p>The arrow function syntax also works for a function that doesn't <code>return</code> a value as shown below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> greetings = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World!"</span>);
</code></pre>
<p>When using the arrow function syntax, the curly brackets are required only when you have a multiline function body:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> greetings = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World!"</span>);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"How are you?"</span>);
};
</code></pre>
<h3 id="heading-arrow-function-without-round-brackets">Arrow function without round brackets</h3>
<p>The round brackets <code>()</code> are used in JavaScript functions to indicate the parameters that the function can receive.</p>
<p>When you use the <code>function</code> keyword, the round brackets are always required:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">plusThree</span>(<span class="hljs-params">num</span>) </span>{
  <span class="hljs-keyword">return</span> num + <span class="hljs-number">3</span>;
}
</code></pre>
<p>On the other hand, the arrow function allows you to omit the round brackets when you have <strong>exactly one parameter</strong> for the function:</p>
<p>The following code example is a valid arrow function expression:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> plusThree = <span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num + <span class="hljs-number">3</span>;
</code></pre>
<p>As you can see, you can remove the round and curly brackets as well as the <code>return</code> keyword.</p>
<p>But you still need the round brackets for two conditions:</p>
<ul>
<li><p>When the function has no parameter</p>
</li>
<li><p>When the function has more than one parameter</p>
</li>
</ul>
<p>When you have no parameter, then you need round brackets before the arrow as shown below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> greetings = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World!"</span>);
</code></pre>
<p>The same applies when you have more than one parameter.</p>
<p>The function below has two parameters: <code>name</code> and <code>age</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> greetings = <span class="hljs-function">(<span class="hljs-params">name, age</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World!"</span>);
</code></pre>
<p>The arrow syntax makes the round brackets optional when you have a single parameter function.</p>
<h3 id="heading-arrow-function-doesnt-have-arguments-binding">Arrow function doesn't have arguments binding</h3>
<p>When using the <code>function</code> keyword to define a function, you can access the arguments you pass to the function using the <code>arguments</code> keyword like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> printArgs = <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-built_in">arguments</span>);
};

printArgs(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>);
<span class="hljs-comment">// [Arguments] { '0': 1, '1': 2, '2': 3 }</span>
</code></pre>
<p>The <code>arguments</code> keyword in the code above refers to the object that stores all the arguments you passed into the function.</p>
<p>By contrast, the arrow function doesn't have the <code>arguments</code> object and will throw an error when you try to access it:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> printArgs = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">arguments</span>);

printArgs(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>);
<span class="hljs-comment">//Uncaught ReferenceError: arguments is not defined</span>
</code></pre>
<p>You can use the JavaScript spread syntax to imitate the <code>arguments</code> binding as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> printArgs = <span class="hljs-function">(<span class="hljs-params">...<span class="hljs-built_in">arguments</span></span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">arguments</span>);

printArgs(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>);
<span class="hljs-comment">// [1, 2, 3]</span>
</code></pre>
<p>By using the spread syntax, the arguments you passed to the arrow function will be stored in an array.</p>
<p><strong>Note</strong> that you need the round brackets even though you are passing just one argument to the function.</p>
<p>You can access the given <code>arguments</code> with the array index notation as <code>arguments[0]</code>, <code>arguments[1]</code>, and so on.</p>
<h3 id="heading-how-to-convert-a-normal-function-to-an-arrow-function-easily">How to convert a normal function to an arrow function easily</h3>
<p>You can follow the <strong>three easy steps</strong> below to convert a normal function to an arrow function:</p>
<ol>
<li><p>Replace the <code>function</code> keyword with the variable keyword <code>let</code> or <code>const</code></p>
</li>
<li><p>Add <code>=</code> symbol after the function name and before the round brackets</p>
</li>
<li><p>Add <code>=&gt;</code> symbol after the round brackets</p>
</li>
</ol>
<p>The code below will help you to visualize the steps:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">plusTwo</span>(<span class="hljs-params">num</span>) </span>{
  <span class="hljs-keyword">return</span> num + <span class="hljs-number">2</span>;
}

<span class="hljs-comment">// step 1: replace function with let / const</span>
<span class="hljs-keyword">const</span> plusTwo(num) {
  <span class="hljs-keyword">return</span> num + <span class="hljs-number">2</span>;
}

<span class="hljs-comment">// step 2: add = after the function name</span>
<span class="hljs-keyword">const</span> plusTwo = (num) {
  <span class="hljs-keyword">return</span> num + <span class="hljs-number">2</span>;
}

<span class="hljs-comment">// step 3: add =&gt; after the round brackets</span>
<span class="hljs-keyword">const</span> plusTwo = <span class="hljs-function">(<span class="hljs-params">num</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> num + <span class="hljs-number">2</span>;
}
</code></pre>
<p>The three steps above are enough to convert any old JavaScript function syntax to the new arrow function syntax.</p>
<p>When you have a single line function, there's a fourth optional step to remove the curly brackets and the <code>return</code> keyword as follows:</p>
<pre><code class="lang-js"><span class="hljs-comment">// from this</span>
<span class="hljs-keyword">const</span> plusTwo = <span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> {
  <span class="hljs-keyword">return</span> num + <span class="hljs-number">2</span>;
};

<span class="hljs-comment">// to this</span>
<span class="hljs-keyword">const</span> plusTwo = <span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num + <span class="hljs-number">2</span>;
</code></pre>
<p>When you have exactly one parameter, you can also remove the round brackets:</p>
<pre><code class="lang-js"><span class="hljs-comment">// from this</span>
<span class="hljs-keyword">const</span> plusTwo = <span class="hljs-function">(<span class="hljs-params">num</span>) =&gt;</span> num + <span class="hljs-number">2</span>;

<span class="hljs-comment">// to this</span>
<span class="hljs-keyword">const</span> plusTwo = <span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num + <span class="hljs-number">2</span>;
</code></pre>
<p>But the last two steps are optional. Only the first three steps are required to convert any JavaScript <code>function</code> and use the arrow function syntax.</p>
<h3 id="heading-exercise-7">Exercise #7</h3>
<p>Write a function named <code>calculateSquare()</code> that's used to calculate the area and perimeter of a square shape.</p>
<p>The function accepts one parameter: the <code>side</code> of the square.</p>
<p>The formula to calculate the area is <code>side * side</code>, and the formula to calculate the perimeter is <code>4 * side</code>.</p>
<p>The output shows the size of the size, the area, and the perimeter as follows:</p>
<pre><code class="lang-txt">The square side is 8
The area of the square is 64
The perimeter of the square is 32
</code></pre>
<h2 id="heading-14-objects-in-javascript">14 - Objects in JavaScript</h2>
<p>An object is a special data type that allows you to store more than one value, just like an array.</p>
<p>The difference between an object and an array is that an array stores data as a list of items, while an object stores data in a <code>key:value</code> pair format.</p>
<p>Let's see an example illustrating this difference. Suppose you want to store information about a book in your program.</p>
<p>When you use regular variables, it would look like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> bookTitle = <span class="hljs-string">"JavaScript Introduction"</span>;
<span class="hljs-keyword">let</span> bookAuthor = <span class="hljs-string">"Nathan Sebhastian"</span>;
</code></pre>
<p>While it works fine, it certainly isn't the best way to store related values.</p>
<p>Another way to store the value would be to use an array:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myBook = [<span class="hljs-string">"JavaScript Introduction"</span>, <span class="hljs-string">"Nathan Sebhastian"</span>];
</code></pre>
<p>This is certainly better as you can group related data about the book together, but you have no way to add context to the value.</p>
<p>This is where an object is useful. You can declare a single book object and store the data in <code>key:value</code> format:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myBook = {
  <span class="hljs-attr">title</span>: <span class="hljs-string">"JavaScript Introduction"</span>,
  <span class="hljs-attr">author</span>: <span class="hljs-string">"Nathan Sebhastian"</span>,
};
</code></pre>
<p>An object is declared using the curly brackets <code>{}</code>, and each item inside the brackets is written in the <code>key:value</code> format.</p>
<p>An object item is also known as a property, with the <em>key</em> as property name and <em>value</em> as property value.</p>
<p>Like an array, you need to separate each item inside an object using a comma.</p>
<p>You can assign a string or numbers as the key of an item, and you can assign any type of data as the value, including a function:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myBook = {
  <span class="hljs-attr">title</span>: <span class="hljs-string">"JavaScript Introduction"</span>,
  <span class="hljs-attr">author</span>: <span class="hljs-string">"Nathan Sebhastian"</span>,
  <span class="hljs-attr">describe</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">`Book title: <span class="hljs-subst">${<span class="hljs-built_in">this</span>.title}</span>`</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Book author: <span class="hljs-subst">${<span class="hljs-built_in">this</span>.author}</span>`</span>);
  },
};
</code></pre>
<p>Here, the <code>describe</code> key or property is a function that prints the <code>title</code> and <code>author</code> value from the object.</p>
<p>The <code>this</code> keyword refers to the context of the code, which is the <code>myBook</code> object in this case.</p>
<p>Usually, an object key is something that gives more context to the value it holds. A key must also be unique, so you can't use the same key twice in the same object.</p>
<p>For example, if you have data about a book, you can use object keys such as <code>title</code>, <code>author</code>, and <code>price</code> to help you understand the context of the value stored in each key.</p>
<h3 id="heading-how-to-access-object-values">How to access object values</h3>
<p>To access the value of an object, you can use either the dot notation <code>.</code> or the square brackets <code>[]</code> notation.</p>
<p>Here's an example of using the dot notation to access the object properties:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myBook = {
  <span class="hljs-attr">title</span>: <span class="hljs-string">"JavaScript Introduction"</span>,
  <span class="hljs-attr">author</span>: <span class="hljs-string">"Nathan Sebhastian"</span>,
};

<span class="hljs-built_in">console</span>.log(myBook.title);
<span class="hljs-built_in">console</span>.log(myBook.author);
</code></pre>
<p>And here's how you use the square brackets to access the same properties:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myBook = {
  <span class="hljs-attr">title</span>: <span class="hljs-string">"JavaScript Introduction"</span>,
  <span class="hljs-attr">author</span>: <span class="hljs-string">"Nathan Sebhastian"</span>,
};

<span class="hljs-built_in">console</span>.log(myBook[<span class="hljs-string">"title"</span>]);
<span class="hljs-built_in">console</span>.log(myBook[<span class="hljs-string">"author"</span>]);
</code></pre>
<p>Keep in mind that you need to wrap the property name in quotes like a string, or JavaScript will think you're passing a variable inside the square brackets.</p>
<h3 id="heading-how-to-add-a-new-property-to-the-object">How to add a new property to the object</h3>
<p>You can assign a new property to the object using either the dot notation or the square brackets like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myBook = {
  <span class="hljs-attr">title</span>: <span class="hljs-string">"JavaScript Introduction"</span>,
  <span class="hljs-attr">author</span>: <span class="hljs-string">"Nathan Sebhastian"</span>,
};

<span class="hljs-comment">// add release year property</span>
myBook.year = <span class="hljs-number">2023</span>;

<span class="hljs-comment">// add publisher property</span>
myBook[<span class="hljs-string">"publisher"</span>] = <span class="hljs-string">"CodeWithNathan"</span>;

<span class="hljs-built_in">console</span>.log(myBook);
</code></pre>
<p>When you print the object, here's the result:</p>
<pre><code class="lang-txt">{
  title: 'JavaScript Introduction',
  author: 'Nathan Sebhastian',
  year: 2023,
  publisher: 'CodeWithNathan'
}
</code></pre>
<p>You can add as many properties as you need to the same object.</p>
<h3 id="heading-how-to-modify-object-properties">How to modify object properties</h3>
<p>To modify an existing property, you need to specify an existing object property using either the dot or square brackets notation followed by the assignment operator as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myBook = {
  <span class="hljs-attr">title</span>: <span class="hljs-string">"JavaScript Introduction"</span>,
  <span class="hljs-attr">author</span>: <span class="hljs-string">"Nathan Sebhastian"</span>,
};

<span class="hljs-comment">// change the author property</span>
myBook.author = <span class="hljs-string">"John Doe"</span>;

<span class="hljs-built_in">console</span>.log(myBook);
</code></pre>
<p>Output:</p>
<pre><code class="lang-txt">{
  title: 'JavaScript Introduction',
  author: 'John Doe'
}
</code></pre>
<p>As you can see, the <code>author</code> property value has been changed.</p>
<h3 id="heading-how-to-delete-object-properties">How to delete object properties</h3>
<p>To delete a property from your object, you need to use the <code>delete</code> operator as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myBook = {
  <span class="hljs-attr">title</span>: <span class="hljs-string">"JavaScript Introduction"</span>,
  <span class="hljs-attr">author</span>: <span class="hljs-string">"Nathan Sebhastian"</span>,
};

<span class="hljs-keyword">delete</span> myBook.author;

<span class="hljs-built_in">console</span>.log(myBook);
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-txt">{ title: 'JavaScript Introduction' }
</code></pre>
<p>When you try to access the deleted property, you will get the <code>undefined</code> value.</p>
<h3 id="heading-how-to-check-if-a-property-exists-in-an-object">How to check if a property exists in an object</h3>
<p>To check if a certain property exists in your object, you can use the <code>in</code> operator like this:</p>
<pre><code class="lang-js">propertyName <span class="hljs-keyword">in</span> myObject
</code></pre>
<p>The <code>in</code> operator returns <code>true</code> if the <code>propertyName</code> exists in your object.</p>
<p>See the example below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> person = {
  <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Nathan"</span>,
  <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Sebhastian"</span>
}

<span class="hljs-comment">// check if firstName exists</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'firstName'</span> <span class="hljs-keyword">in</span> person); <span class="hljs-comment">// true</span>

<span class="hljs-comment">// check if age exists</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'age'</span> <span class="hljs-keyword">in</span> person); <span class="hljs-comment">// false</span>
</code></pre>
<p>Now you know how to manipulate a JavaScript object.</p>
<h3 id="heading-exercise-8">Exercise #8</h3>
<p>Create a <code>person</code> object with the following properties:</p>
<ul>
<li><p><code>name</code> - the person's name</p>
</li>
<li><p><code>age</code> - the person's age</p>
</li>
<li><p><code>greet()</code> - a function to greet another person</p>
</li>
</ul>
<p>Inside the <code>greet()</code> function, introduce the person, specifying the name and the age.</p>
<p>Here's an example output:</p>
<pre><code class="lang-txt">person.greet();

Hello! My name is Alex and I'm 22 years old.
</code></pre>
<h2 id="heading-final-exercise-build-a-cash-register-machine">Final Exercise: Build a Cash Register Machine</h2>
<p>Let's build a cash register machine that can add items to a shopping cart, calculate total price, calculate discounts, and accept payment by cash.</p>
<p>The currency is assumed in USD, so you don't need to add it to the program.</p>
<p>The cash register has 3 items for sale:</p>
<ul>
<li><p>Phone for 300</p>
</li>
<li><p>Smart TV for 220</p>
</li>
<li><p>Gaming Console for 150</p>
</li>
</ul>
<p>There's a 10% discount when the total price is higher than 400.</p>
<p>The cash register should have a shopping cart that starts empty.</p>
<p>The cash register should provide a method called <code>addItem</code> that takes the name of an item as a parameter. When called, it should check if the item is available for sale. If it is, the item should be added to the shopping cart. If it is not available, show a message saying we don't sell that item.</p>
<p>The cash register should provide a method called <code>calculateTotalPrice</code> that calculates the total price of all the items in the shopping cart. It should iterate over the items in the shopping cart and sum up their prices.</p>
<p>The cash register should provide a method called <code>pay</code> that takes the payment amount as a parameter.</p>
<p>It should calculate the total price of the items in the shopping cart using the <code>calculateTotalPrice</code> method. If the total price is higher than 400, a 10% discount should be applied.</p>
<p>The method should then compare the payment amount with the total price (after applying the discount) and display an appropriate message:</p>
<ul>
<li><p>If the payment amount is equal to or greater than the total price, it should display a message thanking the customer for the purchase. If there is any change, it should also display the amount of change to be given.</p>
</li>
<li><p>If the payment amount is less than the total price, it should display a message indicating that the customer does not have enough money to purchase the items.</p>
</li>
<li><p>The program should include appropriate <code>console.log()</code> statements to display messages for adding items to the shopping cart, displaying the total price, and processing the payment.</p>
</li>
</ul>
<p>The program should handle scenarios where the customer's payment amount is exactly equal to the total price, as well as cases where the payment amount is greater or less than the total price.</p>
<p>To build the program, you need to use what you've learned about objects, arrays, conditionals, and loops.</p>
<p>I recommend that you try building the program yourself first. If you get stuck, then see the provided solution below. Good luck!</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Congratulations on finishing this handbook! We have gone through quite a lot of concepts together to learn how to code using JavaScript.</p>
<p>I hope you enjoyed the process as much as I enjoy writing it. I would love to get your feedback, learning what you liked and didn't so I can improve the tutorial.</p>
<p>If you want to learn more about JavaScript, I'm creating a course that helps you use JavaScript to build web applications. It's currently in a pre-order period so you can get the course at a lower price and support my work in creating more tutorials. You can <a target="_blank" href="https://codewithnathan.com/js-course">check it out here</a>.</p>
<p><a target="_blank" href="https://codewithnathan.com/js-course"><img src="https://www.freecodecamp.org/news/content/images/2023/07/nathan-js-tutorial.jpg" alt="The JavaScript Tutorial by Nathan Sebhastian" width="600" height="400" loading="lazy"></a></p>
<h2 id="heading-solutions">Solutions</h2>
<h3 id="heading-exercise-1-1">Exercise #1</h3>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Your name here"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Your age here"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Your occupation here"</span>);
</code></pre>
<h3 id="heading-exercise-2-1">Exercise #2</h3>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> name = <span class="hljs-string">"Your name here"</span>;
<span class="hljs-keyword">let</span> age = <span class="hljs-string">"Your age here"</span>;
<span class="hljs-keyword">let</span> occupation = <span class="hljs-string">"Your occupation here"</span>;

<span class="hljs-built_in">console</span>.log(name);
<span class="hljs-built_in">console</span>.log(age);
<span class="hljs-built_in">console</span>.log(occupation);
</code></pre>
<h3 id="heading-exercise-3-1">Exercise #3</h3>
<pre><code class="lang-txt">1
false
true
true
true
false
</code></pre>
<h3 id="heading-exercise-4-1">Exercise #4</h3>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> colors = [<span class="hljs-string">"red"</span>, <span class="hljs-string">"green"</span>, <span class="hljs-string">"blue"</span>];

colors.push(<span class="hljs-string">"black"</span>);
<span class="hljs-built_in">console</span>.log(colors);

colors.shift();
colors[<span class="hljs-number">0</span>] = <span class="hljs-string">"blue"</span>;
colors[<span class="hljs-number">1</span>] = <span class="hljs-string">"green"</span>;
<span class="hljs-built_in">console</span>.log(colors);

colors.unshift(<span class="hljs-string">"yellow"</span>);
<span class="hljs-built_in">console</span>.log(colors);
</code></pre>
<h3 id="heading-exercise-5-1">Exercise #5</h3>
<p>Using <code>if...else</code> statement:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> grade = <span class="hljs-string">"A"</span>;

<span class="hljs-keyword">if</span> (grade === <span class="hljs-string">"A"</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"You got an A, so here's a Chocolate for you!"</span>);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (grade === <span class="hljs-string">"B"</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"You got a B, here's a Cookie for you!"</span>);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (grade === <span class="hljs-string">"C"</span>) {
  <span class="hljs-built_in">console</span>.log(
    <span class="hljs-string">"You got a C, there's room for improvement and here's your Candy!"</span>
  );
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"No reward to give."</span>);
}
</code></pre>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> grade = <span class="hljs-string">"A"</span>;
<span class="hljs-keyword">switch</span> (grade) {
  <span class="hljs-keyword">case</span> <span class="hljs-string">"A"</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"You got an A, so here's a Chocolate for you!"</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-string">"B"</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"You got a B, here's a Cookie for you!"</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-string">"C"</span>:
    <span class="hljs-built_in">console</span>.log(
      <span class="hljs-string">"You got a C, there's room for improvement and here's your Candy!"</span>
    );
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">default</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"No reward to give."</span>);
}
</code></pre>
<p>Using <code>switch...case</code> statement:</p>
<h3 id="heading-exercise-6-1">Exercise #6</h3>
<p>Half pyramid pattern:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> pattern;

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">1</span>; i &lt;= <span class="hljs-number">5</span>; i++) {
  pattern = <span class="hljs-string">""</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> j = <span class="hljs-number">1</span>; j &lt;= i; j++) {
    pattern += <span class="hljs-string">"*"</span>;
  }
  <span class="hljs-built_in">console</span>.log(pattern);
}
</code></pre>
<p>Inverse half pyramid pattern:</p>
<pre><code class="lang-js"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">4</span>; i &gt;= <span class="hljs-number">0</span>; i--) {
  pattern = <span class="hljs-string">""</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> j = <span class="hljs-number">0</span>; j &lt;= i; j++) {
    pattern += <span class="hljs-string">"*"</span>;
  }
  <span class="hljs-built_in">console</span>.log(pattern);
}
</code></pre>
<h3 id="heading-exercise-7-1">Exercise #7</h3>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateSquare</span>(<span class="hljs-params">side</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The square side is <span class="hljs-subst">${side}</span>`</span>);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The area of the square is <span class="hljs-subst">${side * side}</span>`</span>);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The perimeter of the square is <span class="hljs-subst">${<span class="hljs-number">4</span> * side}</span>`</span>);
}

calculateSquare(<span class="hljs-number">7</span>);
</code></pre>
<h3 id="heading-exercise-8-1">Exercise #8</h3>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> person = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"Alex"</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">22</span>,
  <span class="hljs-attr">greet</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">`Hello! My name is <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> and I'm <span class="hljs-subst">${<span class="hljs-built_in">this</span>.age}</span> years old.`</span>
    );
  },
};

person.greet();
</code></pre>
<h3 id="heading-final-exercise">Final Exercise</h3>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> cashRegister = {
  <span class="hljs-attr">itemsForSale</span>: [
    { <span class="hljs-attr">name</span>: <span class="hljs-string">"Phone"</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">300</span> },
    { <span class="hljs-attr">name</span>: <span class="hljs-string">"Smart TV"</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">220</span> },
    { <span class="hljs-attr">name</span>: <span class="hljs-string">"Gaming Console"</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">150</span> },
  ],
  <span class="hljs-attr">shoppingCart</span>: [],
  <span class="hljs-attr">addItem</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">name</span>) </span>{
    <span class="hljs-keyword">let</span> foundItem = <span class="hljs-built_in">this</span>.itemsForSale.find(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">item</span>) </span>{
      <span class="hljs-keyword">return</span> item.name === name;
    });
    <span class="hljs-keyword">if</span> (foundItem) {
      <span class="hljs-built_in">this</span>.shoppingCart.push(foundItem);
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Adding <span class="hljs-subst">${name}</span> to your shopping cart`</span>);
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Sorry, we don't sell <span class="hljs-subst">${name}</span> here!`</span>);
    }
  },
  <span class="hljs-attr">calculateTotalPrice</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> totalPriceAmount = <span class="hljs-number">0</span>;
    <span class="hljs-built_in">this</span>.shoppingCart.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">purchasedItem</span>) </span>{
      totalPriceAmount += purchasedItem.price;
    });
    <span class="hljs-keyword">return</span> totalPriceAmount;
  },
  <span class="hljs-attr">pay</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">amount</span>) </span>{
    <span class="hljs-keyword">let</span> totalPriceAmount = <span class="hljs-built_in">this</span>.calculateTotalPrice();
    <span class="hljs-keyword">if</span> (totalPriceAmount &gt; <span class="hljs-number">500</span>) {
      totalPriceAmount -= totalPriceAmount * <span class="hljs-number">0.1</span>;
      <span class="hljs-built_in">console</span>.log(
        <span class="hljs-string">`You get a 10% discount and your total price is <span class="hljs-subst">${totalPriceAmount}</span>`</span>
      );
    }
    <span class="hljs-keyword">if</span> (amount &gt;= totalPriceAmount) {
      <span class="hljs-keyword">if</span> (amount - totalPriceAmount &gt; <span class="hljs-number">0</span>) {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Here's your <span class="hljs-subst">${amount - totalPriceAmount}</span> change`</span>);
      }
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Thanks for your purchase! Hope you come again`</span>);
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-built_in">console</span>.log(
        <span class="hljs-string">"Sorry, but you don't have enough money to purchase your items"</span>
      );
    }
  },
};
</code></pre>
<p>To test the object, run the code below:</p>
<pre><code class="lang-js">cashRegister.addItem(<span class="hljs-string">"Phone"</span>);
cashRegister.addItem(<span class="hljs-string">"Smart TV"</span>);
<span class="hljs-built_in">console</span>.log(cashRegister.calculateTotalPrice());
cashRegister.pay(<span class="hljs-number">700</span>);
</code></pre>
<p>Output:</p>
<pre><code class="lang-txt">Adding Phone to your shopping cart
Adding Smart TV to your shopping cart
520
You get a 10% discount and your total price is 468
Here's your 232 change
Thanks for your purchase! Hope you come again
</code></pre>
<p>Thanks for reading!</p>
<p>If you enjoyed this handbook and want to take your JavaScript skills to the next level, I recommend you check out my new book <em>Beginning Modern JavaScript</em> <a target="_blank" href="https://www.amazon.com/dp/B0CQXHMF8G">here</a>.</p>
<p><a target="_blank" href="https://www.amazon.com/dp/B0CQXHMF8G"><img src="https://www.freecodecamp.org/news/content/images/2024/01/beginning-js-cover.png" alt="beginning-js-cover" width="600" height="400" loading="lazy"></a></p>
<p>The book is designed to be easy to understand and accessible to anyone looking to learn JavaScript. It provides a step-by-step gentle guide that will help you understand how to use JavaScript to create a dynamic application.</p>
<p>Here's my promise: <em>You will actually feel like you understand what you're doing with JavaScript.</em></p>
<p>Until next time!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Java Data Types And Variables – Explained for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ By Jacob Isah  As a beginner learning Java, one of the fundamental topics you'll need to understand is data types.  Every day in the life of every software engineer is about how to manipulate data, how to get data from users, the format of the data, ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/java-data-types-and-variables/</link>
                <guid isPermaLink="false">66d45f3af855545810e93466</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 27 Jun 2023 16:59:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/06/data-types-and-variables.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Jacob Isah </p>
<p>As a beginner learning Java, one of the fundamental topics you'll need to understand is data types. </p>
<p>Every day in the life of every software engineer is about how to manipulate data, how to get data from users, the format of the data, and how this data is stored and managed.</p>
<p>Java is a popular programming language known for its strong typing system, which means that every variable must have a declared type. Java provides a wide range of data types to accommodate various kinds of data and operations. </p>
<p>In this article, I will walk you through Java's data types and explain how they work.</p>
<p>There are two types of data types in Java – primitive data types and reference data types. Let's dive in and learn more about each.</p>
<h2 id="heading-differences-between-primitive-data-types-and-reference-data-types">Differences Between Primitive Data Types and Reference Data Types</h2>
<p>In Java, there are important differences between reference data types and primitive data types.</p>
<p>Primitive data types store the actual value directly in memory, while reference data types store references or memory addresses that point to the location where the object is stored.</p>
<p>Primitive data types have default values if not explicitly initialized, while reference data types default to <code>null</code>.</p>
<p>Primitive data types have fixed sizes defined by the language, while reference data types have a fixed size, regardless of the object they reference.</p>
<p>Operations on primitive data types can be performed directly, while operations on reference data types can only be performed through the methods provided by the object.</p>
<p>Primitive data types have corresponding wrapper classes, while reference data types do not.</p>
<p>When passing a primitive data type as a method argument, a copy of the value is passed, while passing a reference data type passes the reference by value.</p>
<p>These differences shows how important storage, default values, size, operations, and pass-by-value semantics between reference data types and primitive data types work in Java.</p>
<h3 id="heading-primitive-data-types-in-java">Primitive Data Types in Java</h3>
<p>Java has eight primitive data types, which are the most basic building blocks for storing data. These types serve as the building blocks of data manipulation in Java. </p>
<p>Primitive data types serve only one purpose — containing pure, simple values of a certain kind. They are reserved keywords in Java. Because they are keywords, they cannot be used as variable names. They include the following:</p>
<h4 id="heading-byte">Byte</h4>
<p>Imagine that you have a small box that can hold numbers. This box can hold numbers from -128 to 127. It's like a toy box that can only fit a certain range of toys, from -128 to 127. You can put any number from this range inside the box.</p>
<p>The <code>byte</code> data type is an 8-bit signed integer that can hold values from -128 to 127. It is commonly used when memory space is a concern. Let’s create a variable of type <code>byte</code>:</p>
<pre><code class="lang-java"><span class="hljs-keyword">byte</span> myByte = <span class="hljs-number">100</span>;
System.out.println(<span class="hljs-string">"byte: "</span> + myByte);
</code></pre>
<pre><code class="lang-java">Output
<span class="hljs-keyword">byte</span>: <span class="hljs-number">100</span>
</code></pre>
<h4 id="heading-short">Short</h4>
<p>Now, imagine you have a bigger box. This box can hold the <code>short</code> data type that is a 16-bit signed integer that can hold values from -32,768 to 32,767. It is useful for storing larger integer values than the <code>byte</code> data type.</p>
<pre><code class="lang-java"><span class="hljs-keyword">short</span> myShort = <span class="hljs-number">30000</span>;
System.out.println(<span class="hljs-string">"short: "</span> + myShort);
</code></pre>
<pre><code class="lang-java">Output:
<span class="hljs-keyword">short</span>: <span class="hljs-number">30000</span>
</code></pre>
<h4 id="heading-int">Int</h4>
<p>Now, let's think of a bigger storage container. The box is an <code>int</code> data type that is a 32-bit signed integer that can hold numbers from -2,147,483,648 to 2,147,483,647. It's like a big treasure box that can hold a wide range of numbers, both positive and negative. It is the most commonly used data type for representing whole numbers in Java.</p>
<pre><code class="lang-java"><span class="hljs-keyword">int</span> myInt = <span class="hljs-number">2000000000</span>;
System.out.println(<span class="hljs-string">"int: "</span> + myInt);
</code></pre>
<pre><code class="lang-java">Output::
<span class="hljs-keyword">int</span>: <span class="hljs-number">2000000000</span>
</code></pre>
<h4 id="heading-long">Long</h4>
<p>Okay, now we have a huge storage room. This room can hold numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. It's like having a massive warehouse that can store a gigantic range of numbers. It is used when a wider range of integer values is required.</p>
<pre><code class="lang-java"><span class="hljs-keyword">long</span> myLong = <span class="hljs-number">9</span>,<span class="hljs-number">223</span>,<span class="hljs-number">372</span>,<span class="hljs-number">036</span>,<span class="hljs-number">854</span>,<span class="hljs-number">775</span>,<span class="hljs-number">807</span>;
System.out.println(<span class="hljs-string">"long: "</span> + myLong);
</code></pre>
<pre><code class="lang-java">Output::
<span class="hljs-keyword">long</span>: <span class="hljs-number">9</span>,<span class="hljs-number">223</span>,<span class="hljs-number">372</span>,<span class="hljs-number">036</span>,<span class="hljs-number">854</span>,<span class="hljs-number">775</span>,<span class="hljs-number">807</span>
</code></pre>
<h4 id="heading-float">Float</h4>
<p>Imagine you have a special box that can hold decimal numbers. This box can hold decimal numbers with moderate precision. It's like a container that can hold water with a reasonable amount of accuracy. </p>
<p>The <code>float</code> data type is a single-precision 32-bit floating-point number. It is useful for representing decimal numbers with moderate precision.</p>
<pre><code class="lang-java"><span class="hljs-keyword">float</span> myFloat = <span class="hljs-number">9</span>,<span class="hljs-number">223</span>,<span class="hljs-number">372</span>,<span class="hljs-number">036</span>,<span class="hljs-number">854</span>,<span class="hljs-number">775</span>,<span class="hljs-number">807</span>;
System.out.println(<span class="hljs-string">"float: "</span> + myFloat);
</code></pre>
<pre><code class="lang-java">Output::
<span class="hljs-keyword">float</span>: <span class="hljs-number">9</span>,<span class="hljs-number">223</span>,<span class="hljs-number">372</span>,<span class="hljs-number">036</span>,<span class="hljs-number">854</span>,<span class="hljs-number">775</span>,<span class="hljs-number">807</span>
</code></pre>
<h4 id="heading-double">Double</h4>
<p>The <code>double</code> data type is a double-precision 64-bit floating-point number. It provides higher precision than float and is commonly used for calculations involving decimal numbers.</p>
<pre><code class="lang-java"><span class="hljs-keyword">double</span> myDouble = <span class="hljs-number">129.7</span>;
System.out.println(<span class="hljs-string">"double: "</span> + mydouble);
</code></pre>
<pre><code class="lang-java">Output::
<span class="hljs-keyword">double</span>: <span class="hljs-number">129.7</span>
</code></pre>
<h4 id="heading-boolean">Boolean</h4>
<p>The <code>boolean</code> data type represents a <code>boolean</code> value, which can be either true or false. It is used for logical operations and control flow.</p>
<pre><code class="lang-java"><span class="hljs-keyword">boolean</span> isJavaFun = <span class="hljs-keyword">true</span>;
<span class="hljs-keyword">boolean</span> isProgrammingFun = <span class="hljs-keyword">false</span>;

System.out.println(isJavaFun);     
System.out.println(isProgrammingFun);
</code></pre>
<pre><code class="lang-java">Output::
<span class="hljs-keyword">true</span>
<span class="hljs-keyword">false</span>
</code></pre>
<h4 id="heading-char">Char</h4>
<p>The <code>char</code> data type represents a single Unicode character and is 16 bits in size. It can store any character from the Unicode character set.</p>
<pre><code class="lang-java"><span class="hljs-keyword">char</span> johnGrade = <span class="hljs-string">'B'</span>;
System.out.println(johnGrade);
</code></pre>
<pre><code class="lang-java">Output::
B
</code></pre>
<h3 id="heading-reference-data-types-in-java">Reference Data Types in Java</h3>
<p>In addition to primitive data types, reference data types are used to store references or memory addresses that point to objects stored in memory. </p>
<p>These data types do not actually store the data itself but rather a reference to the memory location where the data is stored. Let's look at a few popular types of reference data now.</p>
<h4 id="heading-strings">Strings</h4>
<p>The <code>String</code> class represents a sequence of characters. It is widely used for manipulating and storing textual data.</p>
<pre><code class="lang-java">String name = <span class="hljs-string">"John Doe"</span>;
System.out.println(<span class="hljs-string">"Name: "</span> + name);
</code></pre>
<pre><code class="lang-java">Output::
Name: John Doe
</code></pre>
<h4 id="heading-arrays">Arrays</h4>
<p><code>Arrays</code> are used to store a collection of elements of the same type. They provide a convenient way to work with groups of related values.</p>
<pre><code class="lang-java"><span class="hljs-keyword">int</span>[] 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>};
System.out.println(<span class="hljs-string">"Numbers: "</span> + java.util.Arrays.toString(numbers));
</code></pre>
<pre><code class="lang-java">Output::
Numbers: <span class="hljs-number">12345</span>
</code></pre>
<h4 id="heading-classes">Classes</h4>
<p>The <code>class</code> data type represents a <code>class</code> in Java. It is used to create objects and define their behavior.</p>
<p>To understand how classes works in Java, we will create a class example and implement the class in the main class.</p>
<p>In the following example, we will create a <code>Car</code> class  that represents a car with color and speed attributes. We will have a constructor to initialize the color and the speed will be set to 0 by default. The class also will includes methods to accelerate the car, and brake the car.</p>
<p>Here's an example:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ClassCarExample</span> </span>{
    <span class="hljs-comment">// Instance variables or fields</span>
    String color;
    <span class="hljs-keyword">int</span> speed;

    <span class="hljs-comment">//Method start that gets the car started</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">start</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"The car has started."</span>);
    }

    <span class="hljs-comment">//Method accelerate that increases the speed of the car by 10 km/h</span>
      <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">accelerate</span><span class="hljs-params">()</span> </span>{
        speed += <span class="hljs-number">10</span>;
        System.out.println(<span class="hljs-string">"The car is accelerating. Current speed: "</span> +         speed + <span class="hljs-string">" km/h"</span>);
    }

    <span class="hljs-comment">//Method brake that reduces the speed of the car by 5 each time the          method is called</span>

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">brake</span><span class="hljs-params">()</span> </span>{
        speed -= <span class="hljs-number">5</span>;
        System.out.println(<span class="hljs-string">"The car is braking. Current speed: "</span> +             speed + <span class="hljs-string">" km/h"</span>);
    }
}
</code></pre>
<p>We will now create the main method where we will run our class and get our car moving, accelerating, and braking.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-comment">// Create an instance of ClassCarExample</span>
        ClassCarExample car = <span class="hljs-keyword">new</span> ClassCarExample();

        <span class="hljs-comment">// Start the car</span>
        car.start();


        <span class="hljs-comment">// Accelerate the car</span>
        car.accelerate();


        <span class="hljs-comment">// Brake the car</span>
        car.brake();
        }
    }
}
</code></pre>
<pre><code class="lang-java">Output:
The car has started.
The car is accelerating. Current speed: <span class="hljs-number">10</span> km/h
The car is braking. Current speed: <span class="hljs-number">5</span> km/h
</code></pre>
<h4 id="heading-interfaces">Interfaces</h4>
<p>The <code>interface</code> keyword is used to declare an <code>interface</code> .Total abstraction (hiding) is offered, which means that all methods in an <code>interface</code> are declared with an empty body and that all fields are by default <code>public</code>, <code>static</code>, and <code>final</code>. </p>
<p>All of the methods declared in an <code>interface</code> must be implemented by a <code>class</code> that implements the <code>interface</code>.   </p>
<p>To better understand how interface works, we will create an interface class called <code>MyInterfaceClass</code> that declares three methods: <code>methodExampleOne()</code>  <code>methodExampleTwo()</code>, and <code>methodExampleThree()</code>:</p>
<pre><code class="lang-java"><span class="hljs-comment">// The interface class</span>
<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">MyInterfaceClass</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">methodExampleOne</span><span class="hljs-params">()</span></span>;
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">methodExampleTwo</span><span class="hljs-params">()</span></span>;
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">methodExampleThree</span><span class="hljs-params">()</span></span>;
}
</code></pre>
<p>Now we need a class that implement the interface class. We will create a <code>MyClass</code> class that implements <code>MyInterfaceClass</code> interface and provides the implementation for all three methods created above.</p>
<pre><code class="lang-java"><span class="hljs-comment">// Implement the interface in a class</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">MyInterfaceClass</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">methodExampleOne</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Implementing methodExampleOne"</span>);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">methodExampleTwo</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Implementing methodExampleTwo"</span>);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">methodExampleThree</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Implementing methodExampleThree"</span>);
    }
}
</code></pre>
<p>To better drive this home, let's create a main method where we can create an object of our <code>myClass</code> and call our methods on the <code>myObj</code> object we will create and run our Java program.</p>
<pre><code class="lang-java"><span class="hljs-comment">// Main class to test the implementation</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{

        <span class="hljs-comment">//create myObj from MyClass</span>
        MyClass myObj = <span class="hljs-keyword">new</span> MyClass();

        <span class="hljs-comment">// Call the implemented methods on the object we created.</span>
        myObj.methodExampleOne();
        myObj.methodExampleTwo();
        myObj.methodExampleThree();
    }
}
</code></pre>
<p>When we run the <code>Main</code> class, we will see the following output:</p>
<pre><code class="lang-java">Output:
Implementing methodExampleOne
Implementing methodExampleTwo
Implementing methodExampleThree
</code></pre>
<h4 id="heading-enums">Enums</h4>
<p>The <code>Enum</code> data type represents an enumeration (list) type. It is used to define a fixed set of named values, such as days of the week or colors.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">EnumClassExample</span> </span>{  
    <span class="hljs-comment">//defining the enum inside the class  </span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Weekdays</span> </span>{ 
    SUNDAY,MONDAY,TUESDAY,WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
  }  
    <span class="hljs-comment">//main method  </span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{  

    <span class="hljs-comment">//loop throught the enum  </span>

    <span class="hljs-keyword">for</span> (Weekdays w : Weekdays.values())  
    System.out.println(w);  
    }
}
</code></pre>
<pre><code class="lang-java">Output::
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
</code></pre>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>Understanding Java data types is crucial for effective programming in Java. Whether it's the primitive data types for basic value storage or the reference data types for complex objects and behaviors, each data type serves a specific purpose. </p>
<p>By leveraging the appropriate data types, software engineers can write more efficient, reliable, and maintainable code in Java.</p>
<p>Your feedback is highly appreciated. You can follow me on <a target="_blank" href="https://twitter.com/IsahJakub">Twitter</a> and <a target="_blank" href="https://www.linkedin.com/in/isahejacob/">LinkedIn</a>.  </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What Exactly is Node.js? A Guide for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ By Amazing Enyichi Agu If you're thinking about doing back-end development using JavaScript, you will hear the term ‘Node.js’. Node is often associated with developing powerful web servers. But what exactly is Node.js? Is it a JavaScript framework ju... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-exactly-is-node-guide-for-beginners/</link>
                <guid isPermaLink="false">66d45e434a7504b7409c3390</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node js ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 25 May 2023 23:08:59 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/revised_node.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Amazing Enyichi Agu</p>
<p>If you're thinking about doing back-end development using JavaScript, you will hear the term ‘Node.js’. Node is often associated with developing powerful web servers.</p>
<p>But what exactly is Node.js? Is it a JavaScript framework just like <a target="_blank" href="https://angular.io/">Angular</a>? Is it a programming language? Is it a JavaScript Library? Is it an umbrella term for a group of technologies? Or is it just another word for JavaScript?</p>
<p>In this article, we will dive into the world of Node.js, learning what it is, why it was created, and what it is used for. This isn't a project-based tutorial – it aims to introduce beginners to Node and how it works.</p>
<p>Here are the topics we will cover:</p>
<ol>
<li>History of Node.js</li>
<li>What is Node.js?</li>
<li>How does Node.js work?</li>
<li>Modules in Node.js</li>
<li>Node.js looking forward</li>
</ol>
<p>If learning about software tools and how they work is something you enjoy, then you'll enjoy reading this article. On that note, let's begin.</p>
<h2 id="heading-history-of-nodejs">History of Node.js</h2>
<p><a target="_blank" href="https://en.wikipedia.org/wiki/Brendan_Eich">Brendan Eich</a>, who worked for Netscape, invented JavaScript in 1995. But it was a programming language that could only run on a browser. </p>
<p>Web pages initially only displayed static information. The invention of JavaScript filled the need for more interactive behavior within web pages. With this invention, developers could build more dynamic web pages.</p>
<p>After Brendan Eich invented JavaScript, companies made attempts to use the language to run web servers as well (<a target="_blank" href="https://en.wikipedia.org/wiki/Server-side_scripting">server-side scripting</a>). These attempts included <a target="_blank" href="https://dev.to/macargnelutti/server-side-javascript-a-decade-before-node-js-with-netscape-livewire-l72#the-dawn-of-serverside-javascript">Netscape’s Livewire and Microsoft’s Active Server Pages</a>. </p>
<p>But this never became a way of developing web servers, even though JavaScript continued to gain popularity when used in the browser.</p>
<p>In 2008, <a target="_blank" href="https://en.wikipedia.org/wiki/Google">Google</a> announced a new Web Browser called <a target="_blank" href="https://en.wikipedia.org/wiki/Google_Chrome">Chrome</a>. This browser when released revolutionized the world of internet browsing. It's an optimized browser that executes JavaScript fast and has improved the user experience on the web.</p>
<p>The reason Google Chrome could execute JavaScript code so fast was that a JavaScript engine called <a target="_blank" href="https://v8.dev">V8</a> ran inside Chrome. That engine was responsible for accepting JavaScript code, optimizing the code, then executing it on the computer. </p>
<p>The engine was a proper solution for client-side JavaScript. Google Chrome became the leading Web Browser.</p>
<p>In 2009, a software engineer named Ryan Dahl criticized the popular way back-end servers were run at the time. The most popular software for building Web Servers was the <a target="_blank" href="https://httpd.apache.org/">Apache HTTP Server</a>. Dahl argued that it was limited, in that it could not handle a large number of real-time user connections (10,000 +) effectively.</p>
<p>This was one of the main reasons that <a target="_blank" href="https://www.youtube.com/watch?v=EeYvFl7li9E">Ryan Dahl developed Node.js</a>, a tool he built. Node.js used Google’s V8 engine to understand and execute JavaScript code outside the browser. It was a program whose purpose was to run Web Servers. </p>
<p>Node.js was a great alternative to the traditional Apache HTTP server and slowly gained acceptance among the developer community.</p>
<p>Today, <a target="_blank" href="https://www.simform.com/blog/companies-using-nodejs/">a lot of big organizations</a> like Netflix, NASA, LinkedIn, Paypal, and many more use Node.js. These companies leverage Node.js’s capabilities to build robust applications for their users.</p>
<p>Also, in the most recent <a target="_blank" href="https://survey.stackoverflow.co/2022/">StackOverflow Developer Survey</a> at the time of writing this article, Node.js ranked as the most popular technology in the "Web Frameworks and Technology" category. This goes on to show just how popular Node.js is now.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-105.png" alt="Most popular Web Frameworks and Technologies" width="600" height="400" loading="lazy">
<em>Source: <a target="_blank" href="https://survey.stackoverflow.co/2022/#technology-most-popular-technologies">https://survey.stackoverflow.co/2022/#technology-most-popular-technologies</a></em></p>
<p>This article will go in-depth to look at what makes Node.js stand out, and how it works. But before that, we need to define exactly what it is.</p>
<h2 id="heading-what-is-nodejs">What is Node.js?</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-106.png" alt="The Node.js Official Website" width="600" height="400" loading="lazy">
<em>Source: <a target="_blank" href="https://nodejs.org">https://nodejs.org</a></em></p>
<p>From the <a target="_blank" href="https://nodejs.org">Node.js official Website</a>, it states that:</p>
<blockquote>
<p>Node.js is an open-source, cross-platform JavaScript Runtime Environment.</p>
</blockquote>
<p>For us to define Node.js, we need to break the definition into parts. The terms we'll define are:</p>
<ul>
<li>open-source</li>
<li>cross-platform</li>
<li>Runtime Environment</li>
</ul>
<h3 id="heading-what-does-open-source-mean">What does open source mean?</h3>
<p>Open source is generally used to describe software where the public can examine and edit its source code. This means anybody can inspect the code that makes the program work the way it does. </p>
<p>An advantage of this is that the users of the program get to understand it and its capabilities more. Also, if a person spots a bug, they can contribute and fix the bug.</p>
<p>You can find Node's <a target="_blank" href="https://github.com/nodejs/node/">Source Code</a> on GitHub—the most popular website for displaying Open Source code. Node.js also has a lot of contributors—people who add features and fix bugs— on GitHub. Everyone has access to the source code of Node.js, and can even make their customized version of the program if they want to.</p>
<h3 id="heading-what-does-cross-platform-mean">What does cross-platform mean?</h3>
<p>If a program is cross-platform, it means that the program is not limited to a single Operating System or hardware architecture. </p>
<p>A cross-platform program can run on multiple platforms. Node.js runs on Windows, Linux, Unix, and MacOS among other platforms. Developers can use Node.js on a lot of operating systems.</p>
<h3 id="heading-what-is-a-runtime-environment">What is a runtime environment?</h3>
<p>The Runtime Environment of a programming language is any environment where a user can execute code written in that language. That environment provides all the tools and resources necessary for running the code. Node.js is a JavaScript runtime environment.</p>
<p>Apart from Node.js, another example of a JavaScript runtime environment is a Web Browser. A browser usually has all the necessary resources to execute <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools">client-side</a> JavaScript code. </p>
<p>In the browser, we can use JavaScript to interact with the markup elements and tweak the style. The browser promptly runs the code, as it is a runtime environment.</p>
<p>From the three terms defined above, you can see that Node.js is not a JavaScript framework like Angular. Node.js is not a programming language, it is not a JavaScript library, nor is it an umbrella name for a group of technologies. It is also not another name for JavaScript.</p>
<p>Node.js is a software program that can execute JavaScript code. Put more properly, Node.js is a JavaScript runtime environment. It is an environment developed to make it possible to use JavaScript code for server-side scripting.</p>
<h2 id="heading-how-does-nodejs-work">How Does Node.js Work?</h2>
<p>Node.js was written mostly with C/C++. As a program that is supposed to run web servers, Node.js needs to constantly interact with a device's operating system. </p>
<p>Building Node.js with a low-level language like C made it easy for the software to access the operating system’s resources and use them to execute instructions.</p>
<p>But there are many more intricacies involved in how Node.js works. Node.js runs fast and efficient web servers but how exactly does it do that? This section explains the process Node.js uses to achieve its efficiency.</p>
<p>There are three main components we must understand to see how Node.js works. These components are:</p>
<ul>
<li>V8 Engine</li>
<li>Libuv</li>
<li>Event Loop</li>
</ul>
<p>We'll dive into detail and explain each of these components, and how they make up Node.js.</p>
<h3 id="heading-what-is-the-v8-engine">What is the V8 Engine?</h3>
<p>The V8 Engine is the JavaScript engine that interprets and runs JavaScript code in the Chrome browser. Some other browsers use a different engine, for example, <a target="_blank" href="https://spidermonkey.dev/">Firefox uses SpiderMonkey</a>, and <a target="_blank" href="https://developer.apple.com/documentation/javascriptcore">Safari uses JavaScriptCore</a>. Without the JavaScript engine, a computer can not understand JavaScript.</p>
<p>The V8 engine contains a memory heap and call stack. They are the building blocks for the V8 engine. They help manage the execution of JavaScript code.</p>
<p>The memory heap is the data store of the V8 engine. Whenever we create a variable that holds an object or function in JavaScript, the engine saves that value in the memory heap. To keep things simple, it is similar to a backpack that stores supplies for a hiker. </p>
<p>Whenever the engine is executing code and comes across any of those variables, it looks up the actual value from the memory heap – just like whenever a hiker is feeling cold and wants to start a fire, they can look into their backpack for a lighter.</p>
<p>There is a lot more depth to understanding the memory heap. Memory management in JavaScript is a topic that takes more time to explain because the real process is highly intricate. To learn more about the memory heap, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_management">check out this resource</a>.</p>
<p>The call stack is another building block in the V8 engine. It is a data structure that manages the order of functions to be executed. Whenever the program invokes a function, the function is placed on the call stack and can only leave the stack when the engine has handled that function.</p>
<p>JavaScript is a single-threaded language, which means that it can only execute one instruction at a time. Since the call stack contains the order of instructions to be executed, it means that the JavaScript engine has just one order, one call stack. Read more about <a target="_blank" href="https://www.geeksforgeeks.org/why-javascript-is-a-single-thread-language-that-can-be-non-blocking/">single threading and the call stack here</a>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/v8.png" alt="Illustration of the V8 Engine" width="600" height="400" loading="lazy">
<em>Illustration of the V8 Engine</em></p>
<h3 id="heading-what-is-libuv">What is Libuv?</h3>
<p>Apart from the V8 engine, another very important component of Node.js is <a target="_blank" href="https://libuv.org/">Libuv</a>. Libuv is a C library used for performing <strong>Input/output (I/O)</strong> operations. </p>
<p>I/O operations have to do with sending requests to the computer and receiving responses. These operations include reading and writing files, making network requests, and so on.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-107.png" alt="The Libuv Website" width="600" height="400" loading="lazy">
<em>Source: <a target="_blank" href="https://libuv.org">https://libuv.org</a></em></p>
<p>From Libuv’s official website, they state that:</p>
<blockquote>
<p>Libuv is a multi-platform support Library with a focus on asynchronous I/O.</p>
</blockquote>
<p>This means that Libuv is cross-platform (can run on any operating system) and has a focus on Asynchronous I/O. </p>
<p>The computer tends to take time to process I/O instructions, but Libuv—the library Node.js uses to interface with the computer— is focused on Asynchronous I/O. It can handle more than one I/O operation at once.</p>
<p>This is what makes Node.js process I/O instructions efficiently despite being single-threaded. It is all because of Libuv. Libuv knows how to handle requests asynchronously, thereby minimizing delay. But how exactly does the JavaScript engine make use of Libuv?</p>
<p>Whenever we pass a script to Node.js, the engine parses the code and starts processing it. The call stack holds the invoked functions and keeps track of the program. If the V8 engine comes across an I/O operation, it passes that operation over to Libuv. Libuv then executes the I/O operation.</p>
<p>Note that Libuv is a C Library. How do we use JavaScript code to run C instructions? There are <strong>bindings</strong> that connect JavaScript functions to their actual implementation in Libuv. These bindings make it possible to use JavaScript code for I/O instructions. </p>
<p>Node.js uses Libuv for the actual implementation but exposes <a target="_blank" href="https://www.freecodecamp.org/news/apis-for-beginners/">Application Programming Interfaces (APIs)</a>. So, we can now use a Node.js API (which looks like a JavaScript function) to initiate an I/O operation.</p>
<p>One interesting thing to note is that it is true that JavaScript is a single-threaded language, but Libuv—the low-level library Node.js uses— can make use of a thread pool (multiple threads) when executing instructions in the operating system. </p>
<p>Now, you don’t have to worry about these threads when using Node.js. Libuv knows how to manage them effectively. You just have to make use of the provided Node.js APIs to write the instructions.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/node.js.png" alt="Illustration of Node.js Runtime" width="600" height="400" loading="lazy">
<em>Illustration of Node.js Runtime</em></p>
<p>Libuv was originally created for Node.js, but different programming languages now have bindings for it. <a target="_blank" href="https://julialang.org/">Julia</a> and <a target="_blank" href="https://luvit.io/">Luvit (Lua-based Runtime Environment)</a> have the bindings built in just like Node.js, but other languages have libraries that provide those bindings. An example is <a target="_blank" href="https://pypi.org/project/uvloop/">uvloop in Python</a>, among <a target="_blank" href="https://github.com/libuv/libuv/blob/v1.x/LINKS.md">others</a>.</p>
<h3 id="heading-what-is-an-event-loop">What is an Event Loop?</h3>
<p><a target="_blank" href="https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick">The Event Loop in Node.js</a> is a very important part of the process. From the name, we can see it is a loop. The loop starts running as Node.js begins executing a program. In this section, we'll examine what the event loop does.</p>
<p>When we run our JavaScript program that contains some asynchronous code (like I/O instructions or timer-based actions), Node.js handles them using the Node.js APIs. Asynchronous functions usually have instructions to be executed after the function has finished processing. Those instructions are placed in a <strong>Callback Queue</strong>.</p>
<p>The Callback Queue works with the <strong>First In First Out (FIFO)</strong> approach. That means the first instruction (callback) to enter the queue is the first to be invoked.</p>
<p>As the event loop runs, it checks if the call stack is empty. If the call stack is not empty, it allows the ongoing process to continue. But if the call stack is empty, it sends the first instruction on the callback queue to the JavaScript engine. The engine then places that instruction (function) on the call stack and executes it. This is very similar to <a target="_blank" href="https://www.freecodecamp.org/news/javascript-asynchronous-operations-in-the-browser/#event-loops">how the event loop works in the browser</a>.</p>
<p>So, the event loop executes callbacks from asynchronous instructions using the JavaScript V8 engine in Node.js. And it is a loop, which means every time it runs, it checks the call stack to know if it will remove the foremost callback and send it to the JavaScript engine.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/node.js--1-.png" alt="Complete Illustration of the Node.js Runtime" width="600" height="400" loading="lazy">
<em>Complete Illustration of the Node.js Runtime</em></p>
<p>Node.js is said to have an event-driven architecture. This means Node.js is built around listening to events and reacting to them promptly when they happen. These events can be timer events, network events, and so on. </p>
<p>Node.js responds to those events by using an event loop to load event callbacks to the engine after something triggers an event. It is for this reason that Node.js is excellent for real-time data transfer in applications.</p>
<h2 id="heading-modules-in-nodejs">Modules in Node.js</h2>
<p>A lot of the functionality of Node.js is housed in modules that come with the software. These modules are meant to split the building blocks of programs into manageable chunks like Lego blocks. With this in place, we only have to import the modules we need for our programs.</p>
<p>For example, the piece of code below imports a built-in module called <code>fs</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>)
</code></pre>
<p>But there are other ways we can use modules in Node.js. Apart from the built-in modules, we can also use modules (or packages) other developers built.</p>
<p><strong><a target="_blank" href="https://www.npmjs.com/">Node Package Manager (NPM)</a></strong> is a software application that comes together with Node.js. It manages all the third-party modules that are available in Node.js. Whenever you need a third-party package, you install it from NPM using the <code>npm install</code> command.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/npm.jpg" alt="Homepage of the NPM Website" width="600" height="400" loading="lazy">
<em>Source: https://npmjs.com</em></p>
<p>To import a module you installed from NPM would look something like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> newModule = <span class="hljs-built_in">require</span>(<span class="hljs-string">'newModule'</span>)
</code></pre>
<h2 id="heading-nodejs-looking-forward">Node.js Looking Forward</h2>
<p>Node.js has a large community of developers now. It has thousands of <a target="_blank" href="https://github.com/nodejs/node/graphs/contributors">contributors on GitHub</a> and is used by some of the biggest companies today. But what does the future look like for Node.js?</p>
<p>Node.js has evolved well since it came into existence in 2009. It was originally made for back-end development, but it can do so much more now. You can use Node.js to develop desktop applications, front-end web applications, mobile applications, and command-line tools. Developers will continue to use it for more and more of these applications.</p>
<p>Ryan Dahl —the inventor of Node.js— <a target="_blank" href="https://en.wikipedia.org/wiki/Deno_(software)#History">announced a new JavaScript Runtime</a> in 2018 called <a target="_blank" href="https://deno.com">Deno.</a> He unveiled this Runtime he co-created in a talk titled “10 Things I Regret about Node.js”. </p>
<p>Deno is a JavaScript Runtime Environment based on Google Chrome’s V8 engine but written in Rust. Deno is not only a Runtime environment for JavaScript but also <a target="_blank" href="https://www.typescriptlang.org/">TypeScript</a>.</p>
<p>Ryan Dahl created Deno because he decided he had made some wrong decisions concerning the original blueprint of Node.js. He wanted to make better architectural decisions for a JavaScript Runtime environment for Web Servers. The result was Deno.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-112.png" alt="Homepage of the Deno Website" width="600" height="400" loading="lazy">
<em>Source: <a target="_blank" href="https://deno.com">https://deno.com</a></em></p>
<p>But Deno is yet to see massive adoption in the Developer Community. It is still a relatively new technology and needs more time to gain ground.</p>
<p>Also, the <a target="_blank" href="https://openjsf.org/">OpenJS Foundation</a> which is the organization actively managing, developing, and maintaining Node.js has been fixing some of the bugs and the ultimate efficiency of Node.js. More projects are built on top of the Node.js architecture, and that will likely continue to be the case for the foreseeable future.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you have learned a lot and can now confidently answer the question “What exactly is Node.js?”.</p>
<p>We started by going over the history of Node.js, then properly defined Node.js. After that we elaborated on how Node.js works, explaining components such as the V8 Engine, Libuv, and Event Loop. </p>
<p>After that, we talked about modules in Node.js and NPM. Finally, we looked at what the future could hold for Node.js, and we concluded it will likely only power even more applications.</p>
<p>If you want to learn how to use Node.js to build applications, freeCodeCamp has an entire <a target="_blank" href="https://www.youtube.com/playlist?list=PLWKjhJtqVAbmGQoa3vFjeRbRADAOC9drk">playlist of tutorials</a> dedicated to it. There is an abundance of resources to learn the technology on the internet, and more are to come.</p>
<p>Good luck building your next application, and see you next time.</p>
<p>PS: Follow me on <a target="_blank" href="https://twitter.com/enyichiA">Twitter</a> and <a target="_blank" href="https://linkedin.com/in/enyichiaagu">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
