<?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[ Conditionals - 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[ Conditionals - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Mon, 18 May 2026 10:47:49 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/conditionals/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use Conditional Statements in C#: If, Switch, and More Explained with Example Code ]]>
                </title>
                <description>
                    <![CDATA[ Being able to update variables, call particular branches of code, or simply output different code based on a certain condition is a vital part of programming in any language. C# (C Sharp) offers multiple ways to do these things, and I’m about to show... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/conditional-statements-in-csharp-if-switch-and-more/</link>
                <guid isPermaLink="false">67169d1456af142bfd7fe418</guid>
                
                    <category>
                        <![CDATA[ Conditionals ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C# ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Tutorial ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Grant Riordan ]]>
                </dc:creator>
                <pubDate>Mon, 21 Oct 2024 18:27:32 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1729432206658/e802fcca-bf0c-424f-9915-b02fd847bdcc.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Being able to update variables, call particular branches of code, or simply output different code based on a certain condition is a vital part of programming in any language.</p>
<p>C# (C Sharp) offers multiple ways to do these things, and I’m about to show you some of the most common ones. We’ll discuss the pros and cons of each method, and which ones are more suited for particular scenarios.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-you-will-learn-in-this-article">What You Will Learn In This Article</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-if-else-if-else-statements">If / Else if / Else Statements</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-replacing-if-else-with-ternary-operator">Replacing If / Else with Ternary Operator</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-switch-case-statements">Switch Case Statements</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-switch-statements-expression-syntax">Switch Statements - Expression Syntax</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-performance-summary">Performance Summary</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-what-you-will-learn-in-this-article">What You Will Learn In This Article</h2>
<p>I will teach you all about the following conditional coding mechanisms within C#.</p>
<ul>
<li><p>If / Else If / Else statements</p>
</li>
<li><p>Ternary statements</p>
</li>
<li><p>Switch-Case statements</p>
</li>
<li><p>Analysing performance of conditional coding options</p>
</li>
</ul>
<p><strong>Pre-requisites:</strong></p>
<ul>
<li><p>Very basic knowledge of the C# coding language</p>
</li>
<li><p>Coding IDE (to code along if you wish)</p>
</li>
</ul>
<h2 id="heading-if-else-if-else-statements">If / Else if / Else Statements</h2>
<p>When first learning a new programming language, the <code>If</code> statement is a staple in any developer’s learning syllabus. It’s the easiest way in which you can conditionally route the flow of your code’s execution.</p>
<p>Let’s take a look at building up the complexity of the the <code>If</code> statement syntax. In its most basic form, you can use it as a simple <code>if</code> clause, meaning the code within the <code>if</code> block will only be executed if a condition is met.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-csharp"><span class="hljs-comment">// For the demo we're using a hard coded age.</span>
<span class="hljs-keyword">int</span> age = <span class="hljs-number">22</span>;

<span class="hljs-comment">//check person is of legal age in the UK</span>
<span class="hljs-keyword">if</span> (!<span class="hljs-keyword">string</span>.IsNullOrEmpty(age) &amp;&amp; age &gt;= <span class="hljs-number">18</span>)
{
   <span class="hljs-comment">// If true, run the following code</span>
   AllowAccessToNightClub();
}
</code></pre>
<p>Going one step further, if we wanted to carry out some code where the statement results in <code>false</code>, we can do that using an <code>if / else</code> statement like so:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> ageLimit = <span class="hljs-number">18</span>;
<span class="hljs-keyword">var</span> customersAge = <span class="hljs-number">17</span>

<span class="hljs-keyword">if</span>(customersAge &gt;= ageLimit){
{   
    AllowAccessToTheClub();
} <span class="hljs-keyword">else</span>{
    <span class="hljs-comment">// Deny Access</span>
    DenyAccess();
    <span class="hljs-comment">// we can also nest if statements</span>
    <span class="hljs-comment">// if the customer doesn't leave call the Police!</span>
    <span class="hljs-keyword">if</span>(!CustomerLeaves()){
        CallThePolice();
    };
}
</code></pre>
<p>The above example illustrates how you can use <code>if / else</code> statements to control your flow of code. You’ve seen how you can handle specific scenarios with nested statements, allowing you to check future outcomes.</p>
<p>In the above code, we are checking if <code>CustomerLeaves()</code> returns a true or false value, and depending on the outcome, we see whether we need to <code>CallThePolice()</code> or not.</p>
<p>For situations where you want to check more than one condition before defaulting to <code>else</code>, you can use the <code>if / else if / else</code> syntax. Let's see how it works:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span> age = <span class="hljs-number">17</span>;

<span class="hljs-keyword">if</span>(age &gt;= <span class="hljs-number">18</span>){
    Console.WriteLine(<span class="hljs-string">"You can drink alcohol in the UK"</span>);
    Console.WriteLine(<span class="hljs-string">"You can vote in the UK"</span>);
    Console.WriteLine(<span class="hljs-string">"You can get a tattoo"</span>);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(age &gt;= <span class="hljs-number">16</span> &amp;&amp; age &lt; <span class="hljs-number">18</span>){
    Console.WriteLine(<span class="hljs-string">"You can join the royal forces in the UK"</span>);
} <span class="hljs-keyword">else</span>{
   Console.WriteLine(<span class="hljs-string">"Stay in School!"</span>);
}
</code></pre>
<p>The example above uses <code>if / else if / else</code> to display different text based on which condition is met. Only one block will ever run, as you can only match a single condition with this syntax.</p>
<p>Let’s say you wanted to build a stringup based on multiple conditions, but you wanted all conditions to be checked individually. In that case, you could utilise multiple <code>if statements</code> to accomplish this. Be aware, though, that this can make your code less performant and harder to read.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> System.Text;

<span class="hljs-keyword">int</span> age = <span class="hljs-number">20</span>;
<span class="hljs-keyword">bool</span> hasDrivingLicense = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">bool</span> hasVoterID = <span class="hljs-literal">false</span>;

<span class="hljs-keyword">var</span> builder = <span class="hljs-keyword">new</span> StringBuilder();

<span class="hljs-comment">// Multiple independent if statements</span>
<span class="hljs-keyword">if</span> (age &gt;= <span class="hljs-number">18</span>)
{
    builder.Append(<span class="hljs-string">"You are an adult."</span>);
}

<span class="hljs-keyword">if</span> (hasDrivingLicense)
{
    builder.Append(<span class="hljs-string">"You can drive."</span>);
}

<span class="hljs-keyword">if</span> (hasVoterID)
{
    builder.Append(<span class="hljs-string">"You are eligible to vote."</span>);
}

Console.WriteLine(builder.ToString());
Console.WriteLine(builder.ToString());
<span class="hljs-comment">/* Output
You are an adult.You can drive.
*/</span>
</code></pre>
<p>The above code demonstrates using multiple <code>if</code> statements instead of <code>if</code>, <code>else if</code>, <code>else</code>. This allows multiple conditions to be checked independently, so multiple code blocks can run if the conditions are met. This is useful when wanting to assign values to an object’s properties based on different criteria or independent conditions.</p>
<h2 id="heading-replacing-if-else-with-ternary-operator">Replacing If / Else with Ternary Operator</h2>
<p><code>If / Else</code> statements are very useful, but sometimes they can take up a lot of space for really simple assignment code. The <strong>ternary operator</strong> is perfect for these situations. Its syntax uses <code>?</code> and <code>:</code> to represent what happens if the condition is true or false, eliminating the need for brackets.</p>
<p>Here’s an example:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> backgroundColor = isDarkMode ? <span class="hljs-string">"black"</span> : <span class="hljs-string">"white"</span>;
</code></pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>backgroundColor</code>: The variable being assigned.</li>
</ul>
<ul>
<li><p><code>isDarkMode</code>: A boolean condition being evaluated.</p>
</li>
<li><p><code>?</code>: Marks the start of the ternary operator. If <code>isDarkMode</code> is <code>true</code>, the value after <code>?</code> ("black") is assigned.</p>
</li>
<li><p><code>:</code>: Separates the true case from the false case. If <code>isDarkMode</code> is <code>false</code>, the value after <code>:</code> ("white") is assigned.</p>
</li>
</ul>
<p>The ternary statement is shorthand for simple conditional assignments, making your code more compact. I would recommend using it for simple variable assignment or simple binary calling of functions (like call A or call B).</p>
<p>Here’s an example:</p>
<pre><code class="lang-csharp">isLoggedIn ? ShowWelcomeMessage() : PromptLogin();

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">ShowWelcomeMessage</span>(<span class="hljs-params"></span>)</span>
{
    Console.WriteLine(<span class="hljs-string">"Welcome back, user!"</span>);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">PromptLogin</span>(<span class="hljs-params"></span>)</span>
{
    Console.WriteLine(<span class="hljs-string">"Please log in to continue."</span>);
}
</code></pre>
<p>Ternary operations can be nested also like so:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> isDarkMode = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">var</span> isAccessibilityActive = <span class="hljs-literal">true</span>;

<span class="hljs-keyword">var</span> backgroundColor = isDarkMode ? isAccessibilityActive ? <span class="hljs-string">"green"</span> : <span class="hljs-string">"black"</span> : <span class="hljs-string">"white"</span>;

Console.WriteLine(backgroundColor);
</code></pre>
<p>The above example uses nested ternary operators to replace a nested if / else statement. Just keep in mind that the flow is different from a regular ternary operation. It would read like this:</p>
<pre><code class="lang-csharp">IF isDarkMode <span class="hljs-keyword">is</span> <span class="hljs-literal">true</span>, then check <span class="hljs-keyword">if</span> isAccessibilityActive <span class="hljs-keyword">is</span> <span class="hljs-literal">true</span>

IF isAccessibility <span class="hljs-keyword">is</span> <span class="hljs-literal">true</span>, <span class="hljs-keyword">set</span> the <span class="hljs-keyword">value</span> to “green” otherwise <span class="hljs-keyword">return</span> “black”

IF isDarkMode <span class="hljs-keyword">is</span> <span class="hljs-literal">false</span> it will skip the inner checks, and <span class="hljs-keyword">return</span> “white”;
</code></pre>
<p>I’d avoid using nested ternary operators where you can, as they’re messy and can be difficult to read.</p>
<h2 id="heading-switch-case-statements">Switch Case Statements</h2>
<p>Switch case statements work by testing a variable (<em>switch</em>) against multiple possibilities (<em>case</em>).</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span> userRole = <span class="hljs-string">"Admin"</span>;

<span class="hljs-comment">// check the user role against following criteria.</span>
<span class="hljs-keyword">switch</span> (userRole)
{
    <span class="hljs-keyword">case</span> <span class="hljs-string">"Admin"</span>:
        Console.WriteLine(<span class="hljs-string">"You have full access."</span>);
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-string">"Moderator"</span>:
        Console.WriteLine(<span class="hljs-string">"You can moderate content."</span>);
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-string">"User"</span>:
        Console.WriteLine(<span class="hljs-string">"You have limited access."</span>);
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">default</span>:
        Console.WriteLine(<span class="hljs-string">"Role not recognised."</span>);
        <span class="hljs-keyword">break</span>;
}
</code></pre>
<p><strong>Note:</strong> <em>the value and type of variable being evaluated must match.</em> For example, you can’t compare a string with a integer (without casting / parsing first)<em>.</em> If none of the cases match, the <code>default</code> block is executed, similar to the <code>else</code> in an <code>if/else</code> structure, usually used for a fallback case.</p>
<h3 id="heading-why-use-switch-case-over-if-statement">Why Use Switch-Case Over If Statement?</h3>
<p><strong>Readability</strong>: When handling <strong>multiple distinct values</strong> (like roles, commands, or enum types), <code>switch</code> is easier to read and maintain because it organises conditions more cleanly, without multiple <code>if</code> and <code>else if</code> blocks.</p>
<p><strong>Performance</strong>: In some cases, <strong>switch</strong> statements can be more efficient than multiple <code>if / else if</code> blocks, especially when dealing with multiple possible values of a single variable. Some compilers optimise <code>switch</code> statements into lookup tables, improving performance</p>
<p><strong>Scalability</strong>: When managing a long list of distinct options or conditions, a <code>switch</code> case scales better. Adding new cases is simpler and doesn't involve updating long chains of <code>if / else if</code>.</p>
<p><strong>Clean Defaults</strong>: The <code>default</code> case provides a clear way to handle unrecognised or unexpected scenarios, similar to the <code>else</code> block in an <code>if / else if</code> statement, but it feels more naturally integrated with the <code>switch</code> structure. This can be handy for throwing exceptions, logging, and so on.</p>
<h3 id="heading-switch-statements-expression-syntax">Switch Statements - Expression Syntax</h3>
<p>There are times where you need slightly more complex conditions to be evaluated yet still wish to utilise the <code>switch</code> syntax. In this scenario you can utilise the <code>switch expression</code> syntax which was introduced in C# 8.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span> userType = <span class="hljs-string">"VIP"</span>;
<span class="hljs-keyword">decimal</span> purchaseAmount = <span class="hljs-number">500</span>m;

<span class="hljs-keyword">decimal</span> discount = userType <span class="hljs-keyword">switch</span>
{
    <span class="hljs-string">"Regular"</span> <span class="hljs-keyword">when</span> purchaseAmount &lt; <span class="hljs-number">100</span> =&gt; <span class="hljs-number">0.05</span>m,  
    <span class="hljs-string">"Regular"</span> =&gt; <span class="hljs-number">0.10</span>m,  
    <span class="hljs-string">"VIP"</span> <span class="hljs-keyword">when</span> purchaseAmount &lt; <span class="hljs-number">500</span> =&gt; <span class="hljs-number">0.15</span>m,  
    <span class="hljs-string">"VIP"</span> =&gt; <span class="hljs-number">0.20</span>m,  
    <span class="hljs-string">"Employee"</span> =&gt; <span class="hljs-number">0.25</span>m,  
    _ =&gt; <span class="hljs-number">0</span>m 
};

Console.WriteLine(<span class="hljs-string">$"Your discount is: <span class="hljs-subst">{discount * <span class="hljs-number">100</span>}</span>%"</span>);
</code></pre>
<p>This syntax is great when needing to assign a value to the outcome of the case.</p>
<ul>
<li><p><code>userType switch { ... }</code>: a <strong>switch expression</strong> that returns a value (in this case, the discount) based on the <code>userType</code> and optional conditions (like <code>purchaseAmount</code>).</p>
</li>
<li><p>The <code>when</code> clause allows for more complex conditions, such as checking the <code>purchaseAmount</code> in addition to the <code>userType</code> to alter the discount amount.</p>
</li>
</ul>
<p><strong>Default Case / Fallback</strong></p>
<p>The default case in this syntax uses the <code>_</code> character. In our example, if none of the above cases are met, the default case is met and we return <code>0m</code> (no discount).</p>
<h3 id="heading-benefits-of-switch-expressions-over-conventional-switch-statements">Benefits of Switch Expressions Over Conventional <code>switch</code> Statements:</h3>
<p><strong>Concise and Readable:</strong> The switch expression is more <strong>compact</strong> and <strong>readable</strong>, especially when returning values directly based on conditions, without needing to declare variables or use <code>break</code> statements.</p>
<p><strong>Pattern Matching:</strong> It supports <strong>pattern matching</strong> (<code>when</code>), making it easier to add complex conditions to each case, something that would require more verbose <code>if</code> checks in a traditional switch statement.</p>
<p><strong>Returns a Value</strong>: The switch expression is an <strong>expression</strong> that directly returns a value, making it ideal for assignments or inline use, reducing boilerplate code. Below, you’ll find an example using a switch expression as the return value in a method without assigning it to a variable.</p>
<p><strong>Simplifies Complex Logic</strong>: It's excellent for scenarios like this one, where multiple conditions affect the outcome, handling them concisely without deeply nested <code>if / else if</code> blocks.</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">decimal</span> <span class="hljs-title">CalculateDiscount</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> userType, <span class="hljs-keyword">decimal</span> purchaseAmount</span>)</span> =&gt;
    userType <span class="hljs-keyword">switch</span>
    {
        <span class="hljs-string">"Regular"</span> <span class="hljs-keyword">when</span> purchaseAmount &lt; <span class="hljs-number">100</span> =&gt; <span class="hljs-number">0.05</span>m,
        <span class="hljs-string">"Regular"</span> =&gt; <span class="hljs-number">0.10</span>m,
        <span class="hljs-string">"VIP"</span> <span class="hljs-keyword">when</span> purchaseAmount &lt; <span class="hljs-number">500</span> =&gt; <span class="hljs-number">0.15</span>m,
        <span class="hljs-string">"VIP"</span> =&gt; <span class="hljs-number">0.20</span>m,
        <span class="hljs-string">"Employee"</span> =&gt; <span class="hljs-number">0.25</span>m,
        _ =&gt; <span class="hljs-number">0</span>m
    };

<span class="hljs-comment">// Usage</span>
<span class="hljs-keyword">decimal</span> discount = CalculateDiscount(<span class="hljs-string">"VIP"</span>, <span class="hljs-number">500</span>m);
Console.WriteLine(<span class="hljs-string">$"Your discount is: <span class="hljs-subst">{discount * <span class="hljs-number">100</span>}</span>%"</span>);
</code></pre>
<h2 id="heading-performance-summary">Performance Summary</h2>
<p>To help you decide, here are is a quick Benchmarking project (using BenchmarkDotNet package, which you can install with <code>dotnet add package BenchmarkDotnet</code>):</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> BenchmarkDotNet.Attributes;
<span class="hljs-keyword">using</span> BenchmarkDotNet.Order;
<span class="hljs-keyword">using</span> System.Collections.Generic;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">Csharp_Console_Playground</span>
{
    [<span class="hljs-meta">MemoryDiagnoser</span>]
    [<span class="hljs-meta">Orderer(SummaryOrderPolicy.FastestToSlowest)</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">BenchMarkRunner</span>
    {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">readonly</span> Dictionary&lt;<span class="hljs-keyword">int</span>, <span class="hljs-keyword">string</span>&gt; RankingMessages = <span class="hljs-keyword">new</span>()
        {
            { <span class="hljs-number">0</span>, <span class="hljs-string">"Do not stay in this hotel"</span> },
            { <span class="hljs-number">1</span>, <span class="hljs-string">"It's cheap and cheerful"</span> },
            { <span class="hljs-number">2</span>, <span class="hljs-string">"It's clean and tidy"</span> },
            { <span class="hljs-number">3</span>, <span class="hljs-string">"In the middle hotel, good service and great amenities"</span> },
            { <span class="hljs-number">4</span>, <span class="hljs-string">"It's a nice hotel, but the price is not too high"</span> },
            { <span class="hljs-number">5</span>, <span class="hljs-string">"It's the best hotel in the area"</span> }
        };

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

        [<span class="hljs-meta">Benchmark</span>]
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> <span class="hljs-title">BenchMarkIfElse</span>(<span class="hljs-params"></span>)</span>
        {
            <span class="hljs-keyword">var</span> winningMessage = <span class="hljs-string">""</span>;

            <span class="hljs-keyword">if</span> (ranking == <span class="hljs-number">0</span>)
            {
                winningMessage = <span class="hljs-string">"Do not stay in this hotel"</span>;
            }
            <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (ranking == <span class="hljs-number">1</span>)
            {
                winningMessage = <span class="hljs-string">"It's cheap and cheerful"</span>;
            }
            <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (ranking == <span class="hljs-number">2</span>)
            {
                winningMessage = <span class="hljs-string">"It's clean and tidy"</span>;
            }
            <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (ranking == <span class="hljs-number">3</span>)
            {
                winningMessage = <span class="hljs-string">"In the middle hotel, good service and great amenities"</span>;
            }
            <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (ranking == <span class="hljs-number">4</span>)
            {
                winningMessage = <span class="hljs-string">"It's a nice hotel, but the price is not too high"</span>;
            }
            <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (ranking == <span class="hljs-number">5</span>)
            {
                winningMessage = <span class="hljs-string">"It's the best hotel in the area"</span>;
            }

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

        [<span class="hljs-meta">Benchmark</span>]
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> <span class="hljs-title">BenchMarkSwitchCaseExpression</span>(<span class="hljs-params"></span>)</span>
        {
            <span class="hljs-keyword">var</span> winningMessage = ranking <span class="hljs-keyword">switch</span>
            {
                <span class="hljs-number">0</span> =&gt; <span class="hljs-string">"Do not stay in this hotel"</span>,
                <span class="hljs-number">1</span> =&gt; <span class="hljs-string">"It's cheap and cheerful"</span>,
                <span class="hljs-number">2</span> =&gt; <span class="hljs-string">"It's clean and tidy"</span>,
                <span class="hljs-number">3</span> =&gt; <span class="hljs-string">"In the middle hotel, good service and great amenities"</span>,
                <span class="hljs-number">4</span> =&gt; <span class="hljs-string">"It's a nice hotel, but the price is not too high"</span>,
                <span class="hljs-number">5</span> =&gt; <span class="hljs-string">"It's the best hotel in the area"</span>,
                _ =&gt; <span class="hljs-string">""</span>
            };

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

        [<span class="hljs-meta">Benchmark</span>]
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> <span class="hljs-title">BenchMarkSwitchCase</span>(<span class="hljs-params"></span>)</span>
        {
            <span class="hljs-keyword">var</span> winningMessage = <span class="hljs-string">""</span>;
            <span class="hljs-keyword">switch</span> (ranking)
            {
                <span class="hljs-keyword">case</span> <span class="hljs-number">0</span>:
                    winningMessage = <span class="hljs-string">"Do not stay in this hotel"</span>;
                    <span class="hljs-keyword">break</span>;
                <span class="hljs-keyword">case</span> <span class="hljs-number">1</span>:
                    winningMessage = <span class="hljs-string">"It's cheap and cheerful"</span>;
                    <span class="hljs-keyword">break</span>;
                <span class="hljs-keyword">case</span> <span class="hljs-number">2</span>:
                    winningMessage = <span class="hljs-string">"It's clean and tidy"</span>;
                    <span class="hljs-keyword">break</span>;
                <span class="hljs-keyword">case</span> <span class="hljs-number">3</span>:
                    winningMessage = <span class="hljs-string">"In the middle hotel, good service and great amenities"</span>;
                    <span class="hljs-keyword">break</span>;
                <span class="hljs-keyword">case</span> <span class="hljs-number">4</span>:
                    winningMessage = <span class="hljs-string">"It's a nice hotel, but the price is not too high"</span>;
                    <span class="hljs-keyword">break</span>;
                <span class="hljs-keyword">case</span> <span class="hljs-number">5</span>:
                    winningMessage = <span class="hljs-string">"It's the best hotel in the area"</span>;
                    <span class="hljs-keyword">break</span>;
                <span class="hljs-keyword">default</span>:
                    winningMessage = <span class="hljs-string">"Invalid ranking"</span>;
                    <span class="hljs-keyword">break</span>;
            }

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

        [<span class="hljs-meta">Benchmark</span>]
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span>? BenchMarkDictionary()
        {
            <span class="hljs-keyword">return</span> RankingMessages.TryGetValue(ranking, <span class="hljs-keyword">out</span> <span class="hljs-keyword">var</span> rankingMessage) ? rankingMessage : <span class="hljs-literal">null</span>;
        }
    }
}
</code></pre>
<p>You can then run these tests in your <code>Program.cs</code>:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> BenchmarkDotNet.Running;
<span class="hljs-keyword">using</span> Csharp_Console_Playground;

BenchmarkRunner.Run&lt;BenchMarkRunner&gt;();
</code></pre>
<p>Make sure you use your <code>Release</code> build profile in order to run the benchmarks.</p>
<pre><code class="lang-csharp"> dotnet build -c Release
</code></pre>
<p>then execute <code>dotnet</code> on your build location, for example:</p>
<pre><code class="lang-csharp">dotnet bin/Release/net8<span class="hljs-number">.0</span>/FCC-Conditions.dll
</code></pre>
<p><strong>Results:</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Mean (execution time -</strong> <a target="_blank" href="https://en.wikipedia.org/wiki/Nanosecond"><strong>nano seconds</strong></a><strong>)</strong></td></tr>
</thead>
<tbody>
<tr>
<td>BenchMarkSwitchCaseExpression</td><td>0.0000 ns</td></tr>
<tr>
<td>BenchMarkSwitchCase</td><td>0.0003 ns</td></tr>
<tr>
<td>BenchMarkIfElse</td><td>0.3628 ns</td></tr>
<tr>
<td>BenchMarkDictionary</td><td>2.6356 ns</td></tr>
</tbody>
</table>
</div><p><code>switch</code> statements can be faster than dictionaries because the compiler helps optimise them. When the compiler sees a <code>switch</code>, it can create a special lookup table (jump table, or binary search tree) that allows it to find the right case quickly, especially when the cases are close together (like numbers 1, 2, and 3). This means it can check the value almost instantly.</p>
<p>The reason the dictionary is the slowest is due to memory allocation. Within our bench mark test, we needed to create an in-memory variable for the dictionary to be created and stored (time consuming), and then retrieval also needs to be carried out when doing the lookup.</p>
<h4 id="heading-switch-case-expressions"><strong>Switch-Case Expressions:</strong></h4>
<p><strong>Compile-Time Optimisation</strong>: Switch cases are typically optimised at <strong>compile-time</strong> (when you build your code). The compiler analyses the possible case values and generates efficient machine code to handle them. Depending on the cases, this could be via jump tables, or branching / binary search mechanisms.</p>
<p>Since this is all done during <strong>compilation</strong>, the switch statement has no additional overhead at runtime beyond what the compiler has set up.</p>
<h4 id="heading-dictionaries"><strong>Dictionaries</strong>:</h4>
<p><strong>Runtime Construction</strong>: In contrast, a dictionary (for example, <code>Dictionary&lt;TKey, TValue&gt;</code> in C#) is built at <strong>runtime</strong>. The dictionary uses a <strong>hash table</strong> under the hood, where keys are hashed to generate an index that maps to a value. Here’s the key difference:</p>
<ul>
<li><p><strong>Hash Function</strong>: When you add a key to a dictionary, the hash function is applied to the key to determine where the value should be stored.</p>
</li>
<li><p><strong>Collision Handling</strong>: If two keys happen to have the same hash (a "collision"), the dictionary has to resolve it (usually by chaining or probing), which can introduce some additional overhead.</p>
</li>
</ul>
<p>Since dictionaries are built and modified at runtime, they have to perform these operations dynamically, which adds more overhead compared to the static structure of switch cases.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Understanding how to control the flow of your code through conditional logic is a foundational skill in programming, and C# offers various tools to achieve this. Whether you're using <code>if/else</code> statements for simple conditions, the ternary operator for concise assignments, or switch statements for complex logic, each approach has its strengths and ideal use cases.</p>
<p>Switch statements provide clarity and performance optimisations, especially when handling multiple conditions. On the other hand, dictionaries offer flexibility but come with a runtime overhead. Knowing when to use each method allows you to write more efficient, readable, and maintainable code tailored to specific scenarios.</p>
<p>As always if you want to chat about any of my articles you can follow me on <a target="_blank" href="https://x.com/grantdotdev">Twitter</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What are Falsy Values in JavaScript? Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ In JavaScript, every value has a boolean equivalent. This means it can either be evaluated as true (truthy value) or false (falsy value) when used in a boolean context. But what is a boolean context? It's a situation where a boolean value is expected... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-are-falsey-values-in-javascript/</link>
                <guid isPermaLink="false">66d45defd7a4e35e38434955</guid>
                
                    <category>
                        <![CDATA[ Conditionals ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Benjamin Semah ]]>
                </dc:creator>
                <pubDate>Tue, 30 Jan 2024 15:27:25 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-29-at-12.22.42-AM.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In JavaScript, every value has a boolean equivalent. This means it can either be evaluated as true (truthy value) or false (falsy value) when used in a boolean context.</p>
<p>But what is a boolean context? It's a situation where a boolean value is expected. Examples include if statements, logical operators, and so on. When you use a non-boolean value in a boolean context, JavaScript will convert the value to its boolean equivalent.</p>
<p>In this article, you will learn about falsy values in JavaScript and how to check if a value is falsy. The article also covers some best practices to consider when checking the boolean equivalent of a value.</p>
<p>Let's get started!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#the-six-falsy-values-in-javascript">The Six Falsy Values in JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#how-to-check-if-a-value-is-falsy-in-javascript">How to Check if a Value is Falsy</a></p>
</li>
<li><p><a class="post-section-overview" href="#truthy-values-that-may-appear-as-falsy-values">Truthy Values That May Appear as Falsy Values</a></p>
</li>
<li><p><a class="post-section-overview" href="#best-practices-when-checking-boolean-equivalent">Best Practices When Checking Boolean Equivalent</a></p>
</li>
<li><p><a class="post-section-overview" href="#conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-the-six-falsy-values-in-javascript">The Six Falsy Values in JavaScript</h2>
<p>Falsy values in JavaScript are unique because there are only six of them. Apart from these six, all other values are truthy values.</p>
<p>You can commit these falsy values to memory. That way, when you come across any value that isn't one of the six, you know it's a <code>truthy</code> value.</p>
<p>Here are the six falsy values in JavaScript:</p>
<ul>
<li><p><code>false</code>: The boolean value <code>false</code>.</p>
</li>
<li><p><code>0</code>: The number zero.</p>
</li>
<li><p><code>""</code> or <code>''</code> or ````: An empty string.</p>
</li>
<li><p><code>null</code>: The null keyword, representing the absence of any object value.</p>
</li>
<li><p><code>undefined</code>: The undefined keyword, representing an uninitialized value.</p>
</li>
<li><p><code>NaN</code>: Stands for "Not a Number". It represents a special value returned from an operation that should return a numeric value but doesn't.</p>
</li>
</ul>
<p>Now, let's see some practical examples of these falsys valsues in JavaScript.</p>
<h3 id="heading-example-1-the-boolean-value-false">Example 1 – The boolean value <code>false</code>.</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> isOnline = <span class="hljs-literal">false</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">checkStatus</span>(<span class="hljs-params">status</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">Boolean</span>(status) ? <span class="hljs-string">"ONLINE"</span> : <span class="hljs-string">"OFFLINE"</span>
}

checkStatus(isOnline) <span class="hljs-comment">// "OFFLINE"</span>
</code></pre>
<p>When you pass the <code>isOnline</code> variable to the <code>checkStatus</code> function, it returns the string <code>"OFFLINE"</code>. And this is because the value is <code>false</code> in this context. Here, we are using a tenary operator based on the boolean value of the <code>status</code> argument.</p>
<h3 id="heading-example-2-the-number-zero">Example 2 – The number zero.</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> unreadMessages = <span class="hljs-number">0</span>
<span class="hljs-keyword">let</span> hasUnreadMessages = <span class="hljs-built_in">Boolean</span>(unreadMessages)
<span class="hljs-built_in">console</span>.log(hasUnreadMessages) <span class="hljs-comment">// false</span>
</code></pre>
<p>This examples checks whether a user has unread messages or not. We use the in built <code>Boolean</code> function to get the boolean value of the <code>unreadMessages</code> variable. This means anytime the number of <code>unreadMessages</code> is zero, <code>hasUnreadMessages</code> will be <code>false</code>.</p>
<h3 id="heading-example-3-an-empty-string">Example 3 – An empty string.</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> userInput = <span class="hljs-string">""</span>;
<span class="hljs-keyword">let</span> defaultText = <span class="hljs-string">"No input provided"</span>;

<span class="hljs-keyword">let</span> displayText = <span class="hljs-built_in">Boolean</span>(userInput) || defaultText;

<span class="hljs-built_in">console</span>.log(displayText); <span class="hljs-comment">// No input provided</span>
</code></pre>
<p>This example uses the logical OR operator <code>||</code> to determine the value of the <code>displayText</code>. It will assign the value of <code>userInput</code> to <code>displayText</code> if it's a truthy value. Or it will assign the <code>defaultText</code> to <code>displayText</code> if <code>userInput</code> is a falsy value as it is in this case.</p>
<h3 id="heading-example-4-null">Example 4 – <code>null</code></h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> user = <span class="hljs-literal">null</span>;

<span class="hljs-keyword">if</span> (user &amp;&amp; user.name) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Welcome, "</span> + user.name + <span class="hljs-string">"!"</span>);
} <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Please log in to access the website."</span>);
}
</code></pre>
<p>The following example assumes the <code>user</code> isn't logged in and so the value of <code>user</code> object is <code>null</code>. This means the <code>if</code> statement will evaluate to <code>false</code>. The expected behaviour then will be that the code executes the <code>else</code> block.</p>
<h3 id="heading-example-5-undefined">Example 5 – <code>undefined</code></h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> age;
<span class="hljs-keyword">if</span> (age === <span class="hljs-literal">undefined</span>) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The age is undefined."</span>);
}
</code></pre>
<p>When a variable is declared but not initialized with a value, JavaScript assigns it the value <code>undefined</code> by default. In the code example above, since the <code>age</code> variable is declared but not assigned a value, its value is <code>undefined</code>. This means the code in the <code>if</code> statement will run.</p>
<h3 id="heading-example-6-nan">Example 6 – <code>NaN</code></h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> value1 = <span class="hljs-string">"Ten"</span>
<span class="hljs-keyword">let</span> value2 = <span class="hljs-number">10</span>

<span class="hljs-keyword">let</span> result = value1 / value2

<span class="hljs-keyword">if</span> (<span class="hljs-built_in">isNaN</span>(result)) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The result is not a number."</span>);
} <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(result);
}
</code></pre>
<p>This example divides <code>value1</code> (a string) by <code>value2</code> (a number). This will result in a <code>NaN</code> value because you cannot divide a string by a number. This means the code in the <code>if</code> block will run. And log <code>The result is not a number</code> to the console.</p>
<h2 id="heading-how-to-check-if-a-value-is-falsy-in-javascript">How to Check if a Value is Falsy in JavaScript</h2>
<p>A safe way to check whether a value is falsy or not is to use the <code>Boolean</code> function. The <code>Boolean</code> function returns the boolean value of the value of the argument passed to it.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Boolean</span>(<span class="hljs-literal">false</span>))
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Boolean</span>(<span class="hljs-number">0</span>))
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Boolean</span>(<span class="hljs-string">""</span>))
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Boolean</span>(<span class="hljs-literal">null</span>))
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Boolean</span>(<span class="hljs-literal">undefined</span>))
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Boolean</span>(<span class="hljs-literal">NaN</span>))
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-23-at-6.16.42-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Boolean log results for all six falsy values.</em></p>
<p>Here, we are checking the boolean value of all six falsy values. And as expected, each returns <code>false</code>.</p>
<p>When you pass any other value that's not one of these six falsy values to the Boolean function, it will return <code>true</code>.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Boolean</span>(<span class="hljs-string">'hello'</span>))
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Boolean</span>(<span class="hljs-number">24</span>))
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-23-at-6.24.35-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example boolean log results for truthy values.</em></p>
<h2 id="heading-truthy-values-that-may-appear-as-falsy-values">Truthy Values that May Appear as Falsy Values</h2>
<p>There are some truthy values that, at a glance, may appear to be falsy values but aren't. As already mentioned, only six values in JavaScript are falsy values. Anything else is a truthy value.</p>
<p>The following are some of those values that aren't falsy but may appear as such.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Boolean</span>(<span class="hljs-string">'false'</span>)) <span class="hljs-comment">// An empty object</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Boolean</span>(<span class="hljs-string">' '</span>)) <span class="hljs-comment">// An empty object</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Boolean</span>(<span class="hljs-string">'0'</span>)) <span class="hljs-comment">// An empty object</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Boolean</span>([])) <span class="hljs-comment">// An empty array</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Boolean</span>({})) <span class="hljs-comment">// An empty object</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-24-at-8.09.17-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Log results for truthy values that appear as falsy.</em></p>
<p>The first three strings contains text that may look like falsy values. First is the string with the text <code>"false"</code>, another one with some whitespace, and the third with zero.</p>
<p>Remember that the only string considered a falsy value is an empty string. All non-empty strings in JavaScript are truthy values including strings with only whitespace.</p>
<p>Also, note that unlike strings, both an empty array and an empty object return <code>true</code> in a boolean context.</p>
<h2 id="heading-best-practices-when-checking-boolean-equivalent">Best Practices When Checking Boolean Equivalent</h2>
<p>The following tips will help make your code more readable and easier to maintain.</p>
<h3 id="heading-1-use-the-boolean-function">1. Use the Boolean function</h3>
<p>It's always better to use the built-in <code>Boolean</code> function when you want to check whether a value is truthy or falsy. The function works by coercing any value into its corresponding boolean. It also makes your intention clear to anyone reading the code.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example without the Boolean function</span>
<span class="hljs-keyword">const</span> value = <span class="hljs-string">''</span>; 

<span class="hljs-keyword">if</span> (value) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'It is a TRUTHY value'</span>);
} <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'It is a FALSY value'</span>);
}

<span class="hljs-comment">// Example with the Boolean function</span>
<span class="hljs-keyword">const</span> value = <span class="hljs-string">''</span>

<span class="hljs-keyword">if</span> (<span class="hljs-built_in">Boolean</span>(value)) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'It is a TRUTHY value'</span>);
} <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'It is a FALSY value'</span>);
}
</code></pre>
<p>Both examples do the same thing. But in the second example, it's explicit that you're checking the boolean representation of the given value.</p>
<h3 id="heading-2-use-strict-equality-instead-of-loose-equality">2. Use strict equality <code>===</code> instead of loose equality <code>==</code></h3>
<p>When you're comparing values for truthiness or falsiness, it's recommended to use strict equality (<code>===</code>) over loose equality (<code>==</code>). Strict equality compares both the value and the type. Loose equality performs type coercion before comparing the values, and this can lead to unexpected results.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Strict Equality Example</span>

<span class="hljs-keyword">if</span> (<span class="hljs-number">1</span> === [<span class="hljs-number">1</span>]) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'EQUAL'</span>)
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'NOT EQUAL'</span>)
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-28-at-11.31.28-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Log result for strict equality example.</em></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Loose Equality Example</span>
<span class="hljs-keyword">if</span> (<span class="hljs-number">1</span> == [<span class="hljs-number">1</span>]) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'EQUAL'</span>)
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'NOT EQUAL'</span>)
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-28-at-11.32.20-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Log result for loose equality example.</em></p>
<p>Both examples above compare the same values. But the strict equality example logs "NOT EQUAL". This is because the number 1 is not equal to an array containing the number 1. With the loose equality, it coerces the type of the values to make them of the same type. That is why it logs "EQUAL" to the console.</p>
<h3 id="heading-3-add-comments-to-document-your-code">3. Add comments to document your code</h3>
<p>To make your code more readable and easier to maintain, consider adding comments when necessary to explain your logic when dealing with truthy and falsy values.</p>
<p>Documenting your code is a good practice to help developers on your team (or your future self) understand the intended behaviour of a piece of code.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> selectedUser = USER_OBJ

<span class="hljs-comment">// Check if no user is selected</span>
<span class="hljs-keyword">if</span> (!selectedUser) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Please select a user."</span>);
} <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"User address: "</span> + selectedUser.address);
}
</code></pre>
<p>In the example above, the comment added before the <code>if</code> statement makes it clear that the code is checking if no user has been selected.</p>
<p>Using the logical NOT operator (<code>!</code>) can make it seem like you're checking if a user is selected rather than checking if no user is selected. So a comment in an instance like helps provide clarity.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you have learned about the six falsy values in JavaScript and how they differ from truthy values. You also learned about some truthy values that may appear as falsy, but actually aren't. And you also saw some best practices to consider when working with falsy values.</p>
<p>A good understanding of the concept of falsy and truthy values and how they affect comparisons and conditional statement will come in handy when debugging JavaScript applications.</p>
<p>Thanks for reading. And happy coding! For more in-depth tutorials, feel free to <a target="_blank" href="https://www.youtube.com/@DevAfterHours">subscribe to my YouTube channel</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python Ternary Operator – Conditional Operators in Python ]]>
                </title>
                <description>
                    <![CDATA[ You can use conditional operators in Python to execute code based on a predefined condition(s).  In this article, you'll learn how to use the ternary operator in Python. You'll see its syntax along with some practical examples.  What Is the Ternary O... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-tenary-operator/</link>
                <guid isPermaLink="false">66b0a355b30dd4d00547bbaa</guid>
                
                    <category>
                        <![CDATA[ Conditionals ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Wed, 26 Apr 2023 15:29:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/chris-ried-ieic5Tq8YMk-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>You can use conditional operators in Python to execute code based on a predefined condition(s). </p>
<p>In this article, you'll learn how to use the ternary operator in Python. You'll see its syntax along with some practical examples. </p>
<h2 id="heading-what-is-the-ternary-operator-used-for-in-python">What Is the Ternary Operator Used for in Python?</h2>
<p>The ternary operator in Python is simply a shorter way of writing an <code>if</code> and <code>if...else</code> statements. </p>
<p>Here's what an <code>if...else</code> statement looks like in Python: </p>
<pre><code class="lang-python">user_score = <span class="hljs-number">90</span>

<span class="hljs-keyword">if</span> user_score &gt; <span class="hljs-number">50</span>:
    print(<span class="hljs-string">"Next level"</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"Repeat level"</span>)
</code></pre>
<p>In the code above, we created a variable <code>user_score</code> with a value of 90.</p>
<p>We then printed either of two statements based on a predefined condition — <code>if user_score &gt; 50</code>. </p>
<p>So if the <code>user_score</code> variable is greater than 50, we print "Next level". If it's less than <code>user_score</code>, we print "Repeat level". </p>
<p>You can shorten the <code>if...else</code> statement using the ternary operator syntax. </p>
<h2 id="heading-python-ternary-operator-example">Python Ternary Operator Example</h2>
<p>In the last example, we saw how to use an <code>if...else</code> statement in Python. </p>
<p>You can shorten it using the ternary operator. Here's what the syntax looks like:  </p>
<pre><code class="lang-txt">[option1] if [condition] else [option2]
</code></pre>
<p>In the syntax above, <code>option1</code> will be executed if the <code>condition</code> is true. If the condition is false then <code>option2</code> will be executed. </p>
<p>In other words, the ternary operator is just a shorthand of the <code>if</code> and <code>if...else</code> statements. You can use it in just a single line of code.</p>
<p>Here's a more practical example:</p>
<pre><code class="lang-python">user_score = <span class="hljs-number">90</span>

print(<span class="hljs-string">"Next level"</span>) <span class="hljs-keyword">if</span> user_score &gt; <span class="hljs-number">50</span> <span class="hljs-keyword">else</span> print(<span class="hljs-string">"Repeat level"</span>)
</code></pre>
<p>In the code above, "Next level" will be printed out because the condition is true. </p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we talked about the ternary operator in Python. It's a shorter way of writing <code>if</code> and <code>if...else</code> statements. </p>
<p>You can use ternary operators to execute code based on predefined conditions. </p>
<p>Happy coding! I also write about Python on <a target="_blank" href="https://ihechikara.com/">my blog</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Conditional Statements in Python – Examples of if, else, and elif ]]>
                </title>
                <description>
                    <![CDATA[ Conditional statements are an essential part of programming in Python. They allow you to make decisions based on the values of variables or the result of comparisons. In this article, we'll explore how to use if, else, and elif statements in Python, ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-conditional-statements-if-else-elif-in-python/</link>
                <guid isPermaLink="false">66d460a1ffe6b1f641b5fa5f</guid>
                
                    <category>
                        <![CDATA[ Conditionals ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Jeremiah Oluseye ]]>
                </dc:creator>
                <pubDate>Tue, 07 Mar 2023 16:03:51 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/Conditional.JPG" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Conditional statements are an essential part of programming in Python. They allow you to make decisions based on the values of variables or the result of comparisons.</p>
<p>In this article, we'll explore how to use if, else, and elif statements in Python, along with some examples of how to use them in practice.</p>
<h2 id="heading-how-to-use-the-if-statement-in-python">How to Use the <code>if</code> Statement in Python</h2>
<p>The <code>if</code> statement allows you to execute a block of code if a certain condition is true. Here's the basic syntax:</p>
<pre><code class="lang-python"><span class="hljs-keyword">if</span> condition:
    <span class="hljs-comment"># code to execute if condition is true</span>
</code></pre>
<p>The condition can be any expression that evaluates to a Boolean value (True or False). If the condition is True, the code block indented below the if statement will be executed. If the condition is False, the code block will be skipped.</p>
<p>Here's an example of how to use an <code>if</code> statement to check if a number is positive:</p>
<pre><code class="lang-python">num = <span class="hljs-number">5</span>

<span class="hljs-keyword">if</span> num &gt; <span class="hljs-number">0</span>:
    print(<span class="hljs-string">"The number is positive."</span>)
</code></pre>
<p>Output:</p>
<pre><code class="lang-python">The number <span class="hljs-keyword">is</span> positive.
</code></pre>
<p>In this example, we use the <code>&gt;</code> operator to compare the value of <code>num</code> to 0. If <code>num</code> is greater than 0, the code block indented below the <code>if</code> statement will be executed, and the message "The number is positive." will be printed.</p>
<h2 id="heading-how-to-use-the-else-statement-in-python">How to Use the <code>else</code> Statement in Python</h2>
<p>The <code>else</code> statement allows you to execute a different block of code if the <code>if</code> condition is False. Here's the basic syntax:</p>
<pre><code class="lang-python"><span class="hljs-keyword">if</span> condition:
    <span class="hljs-comment"># code to execute if condition is true</span>
<span class="hljs-keyword">else</span>:
    <span class="hljs-comment"># code to execute if condition is false</span>
</code></pre>
<p>If the condition is True, the code block indented below the <code>if</code> statement will be executed, and the code block indented below the <code>else</code> statement will be skipped.</p>
<p>If the condition is False, the code block indented below the <code>else</code> statement will be executed, and the code block indented below the <code>if</code> statement will be skipped.</p>
<p>Here's an example of how to use an <code>if-else</code> statement to check if a number is positive or negative:</p>
<pre><code class="lang-python">num = <span class="hljs-number">-5</span>

<span class="hljs-keyword">if</span> num &gt; <span class="hljs-number">0</span>:
    print(<span class="hljs-string">"The number is positive."</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"The number is negative."</span>)
</code></pre>
<p>Output:</p>
<pre><code class="lang-python">The number <span class="hljs-keyword">is</span> negative.
</code></pre>
<p>In this example, we use an <code>if-else</code> statement to check if <code>num</code> is greater than 0. If it is, the message "The number is positive." is printed. If it is not (that is, num is negative or zero), the message "The number is negative." is printed.</p>
<h2 id="heading-how-to-use-the-elif-statement-in-python">How to Use the <code>elif</code> Statement in Python</h2>
<p>The <code>elif</code> statement allows you to check multiple conditions in sequence, and execute different code blocks depending on which condition is true. Here's the basic syntax:</p>
<pre><code class="lang-python"><span class="hljs-keyword">if</span> condition1:
    <span class="hljs-comment"># code to execute if condition1 is true</span>
<span class="hljs-keyword">elif</span> condition2:
    <span class="hljs-comment"># code to execute if condition1 is false and condition2 is true</span>
<span class="hljs-keyword">elif</span> condition3:
    <span class="hljs-comment"># code to execute if condition1 and condition2 are false, and condition3 is true</span>
<span class="hljs-keyword">else</span>:
    <span class="hljs-comment"># code to execute if all conditions are false</span>
</code></pre>
<p>The <code>elif</code> statement is short for "else if", and can be used multiple times to check additional conditions.</p>
<p>Here's an example of how to use an <code>if-elif-else</code> statement to check if a number is positive, negative, or zero:</p>
<pre><code class="lang-python">num = <span class="hljs-number">0</span>

<span class="hljs-keyword">if</span> num &gt; <span class="hljs-number">0</span>:
    print(<span class="hljs-string">"The number is positive."</span>)
<span class="hljs-keyword">elif</span> num &lt;
</code></pre>
<h2 id="heading-use-cases-for-conditional-statements">Use Cases For Conditional Statements</h2>
<h3 id="heading-example-1-checking-if-a-number-is-even-or-odd">Example 1: Checking if a number is even or odd.</h3>
<pre><code class="lang-python">num = <span class="hljs-number">4</span>

<span class="hljs-keyword">if</span> num % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>:
    print(<span class="hljs-string">"The number is even."</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"The number is odd."</span>)
</code></pre>
<p>Output:</p>
<pre><code class="lang-python">The number <span class="hljs-keyword">is</span> even.
</code></pre>
<p>In this example, we use the modulus operator (%) to check if <code>num</code> is evenly divisible by 2.</p>
<p>If the remainder of num divided by 2 is 0, the condition num % 2 == 0 is True, and the code block indented below the <code>if</code> statement will be executed. It will print the message "The number is even."</p>
<p>If the remainder is not 0, the condition is False, and the code block indented below the <code>else</code> statement will be executed, printing the message "The number is odd."</p>
<h3 id="heading-example-2-assigning-a-letter-grade-based-on-a-numerical-score">Example 2: Assigning a letter grade based on a numerical score</h3>
<pre><code class="lang-python">score = <span class="hljs-number">85</span>

<span class="hljs-keyword">if</span> score &gt;= <span class="hljs-number">90</span>:
    grade = <span class="hljs-string">"A"</span>
<span class="hljs-keyword">elif</span> score &gt;= <span class="hljs-number">80</span>:
    grade = <span class="hljs-string">"B"</span>
<span class="hljs-keyword">elif</span> score &gt;= <span class="hljs-number">70</span>:
    grade = <span class="hljs-string">"C"</span>
<span class="hljs-keyword">elif</span> score &gt;= <span class="hljs-number">60</span>:
    grade = <span class="hljs-string">"D"</span>
<span class="hljs-keyword">else</span>:
    grade = <span class="hljs-string">"F"</span>

print(<span class="hljs-string">"Your grade is:"</span>, grade)
</code></pre>
<p>Output:</p>
<pre><code class="lang-python">Your grade <span class="hljs-keyword">is</span>: B
</code></pre>
<p>In this example, we use an <code>if-elif-else</code> statement to assign a letter grade based on a numerical score.</p>
<p>The <code>if</code> statement checks if the score is greater than or equal to 90. If it is, the grade is set to "A". If not, the first <code>elif</code> statement checks if the score is greater than or equal to 80. If it is, the grade is set to "B". If not, the second <code>elif</code> statement checks if the score is greater than or equal to 70, and so on. If none of the conditions are met, the <code>else</code> statement assigns the grade "F".</p>
<h3 id="heading-example-3-checking-if-a-year-is-a-leap-year">Example 3: Checking if a year is a leap year</h3>
<pre><code class="lang-python">year = <span class="hljs-number">2000</span>

<span class="hljs-keyword">if</span> year % <span class="hljs-number">4</span> == <span class="hljs-number">0</span>:
    <span class="hljs-keyword">if</span> year % <span class="hljs-number">100</span> == <span class="hljs-number">0</span>:
        <span class="hljs-keyword">if</span> year % <span class="hljs-number">400</span> == <span class="hljs-number">0</span>:
            print(year, <span class="hljs-string">"is a leap year."</span>)
        <span class="hljs-keyword">else</span>:
            print(year, <span class="hljs-string">"is not a leap year."</span>)
    <span class="hljs-keyword">else</span>:
        print(year, <span class="hljs-string">"is a leap year."</span>)
<span class="hljs-keyword">else</span>:
    print(year, <span class="hljs-string">"is not a leap year."</span>)
</code></pre>
<p>Output:</p>
<pre><code class="lang-python"><span class="hljs-number">2000</span> <span class="hljs-keyword">is</span> a leap year.
</code></pre>
<p>In this example, we use nested <code>if</code> statements to check if a year is a leap year. A year is a leap year if it is divisible by 4, except for years that are divisible by 100 but not divisible by 400.</p>
<p>The outer <code>if</code> statement checks if year is divisible by 4. If it is, the inner <code>if</code> statement checks if it is also divisible by 100. If it is, the innermost <code>if</code> statement checks if it is divisible by 400. If it is, the code block indented below that statement will be executed, printing the message "is a leap year."</p>
<p>If it is not, the code block indented below the <code>else</code> statement inside the inner <code>if</code> statement will be executed, printing the message "is not a leap year.".</p>
<p>If the year is not divisible by 4, the code block indented below the <code>else</code> statement of the outer <code>if</code> statement will be executed, printing the message "is not a leap year."</p>
<h3 id="heading-example-4-checking-if-a-string-contains-a-certain-character">Example 4: Checking if a string contains a certain character</h3>
<pre><code class="lang-python">string = <span class="hljs-string">"hello, world"</span>
char = <span class="hljs-string">"w"</span>

<span class="hljs-keyword">if</span> char <span class="hljs-keyword">in</span> string:
    print(<span class="hljs-string">"The string contains the character"</span>, char)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"The string does not contain the character"</span>, char)
</code></pre>
<p><strong>Outcome:</strong></p>
<pre><code class="lang-python">The string contains the character w
</code></pre>
<p>In this example, we use the <code>in</code> operator to check if the character <code>char</code> is present in the string string. If it is, the condition <code>char</code> in string is True, and the code block indented below the <code>if</code> statement will be executed, printing the message "The string contains the character" followed by the character itself.</p>
<p>If <code>char</code> is not present in string, the condition is False, and the code block indented below the <code>else</code> statement will be executed, printing the message "The string does not contain the character" followed by the character itself.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Conditional statements (if, else, and elif) are fundamental programming constructs that allow you to control the flow of your program based on conditions that you specify. They provide a way to make decisions in your program and execute different code based on those decisions.</p>
<p>In this article, we have seen several examples of how to use these statements in Python, including checking if a number is even or odd, assigning a letter grade based on a numerical score, checking if a year is a leap year, and checking if a string contains a certain character.</p>
<p>By mastering these statements, you can create more powerful and versatile programs that can handle a wider range of tasks and scenarios.</p>
<p>It is important to keep in mind that proper indentation is crucial when using conditional statements in Python, as it determines which code block is executed based on the condition.</p>
<p>With practice, you will become proficient in using these statements to create more complex and effective Python programs.</p>
<p>Let’s connect on <a target="_blank" href="https://twitter.com/Olujerry19">Twitter</a> and <a target="_blank" href="https://www.linkedin.com/in/jeremiah-oluseye-58457719a/">Linkedin</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript If-Else and If-Then – JS Conditional Statements ]]>
                </title>
                <description>
                    <![CDATA[ There will be times where you will want to write commands that handle different decisions in your code.  For example, if you are coding a bot, you can have it respond with different messages based on a set of commands it receives.  In this article, I... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-if-else-and-if-then-js-conditional-statements/</link>
                <guid isPermaLink="false">66b8d9d8ce55d3ba4d935999</guid>
                
                    <category>
                        <![CDATA[ Conditionals ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Jessica Wilkins ]]>
                </dc:creator>
                <pubDate>Mon, 09 Aug 2021 23:21:21 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/08/walling-e_MdMMKrgdY-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>There will be times where you will want to write commands that handle different decisions in your code. </p>
<p>For example, if you are coding a bot, you can have it respond with different messages based on a set of commands it receives. </p>
<p>In this article, I will explain what an <code>if...else</code> statement is and provide code examples. We will also look at the conditional (ternary) operator which you can use as a shorthand for the <code>if...else</code> statement. </p>
<h2 id="heading-what-is-an-ifelse-statement-in-javascript">What is an if...else statement in JavaScript?</h2>
<p>The <code>if...else</code> is a type of conditional statement that will execute a block of code when the condition in the <code>if</code> statement is <code>truthy</code>. If the condition is <code>falsy</code>, then the <code>else</code> block will be executed. </p>
<p><code>Truthy</code> and <code>falsy</code> values are converted to <code>true</code> or <code>false</code> in  <code>if</code> statements.</p>
<pre><code class="lang-js"><span class="hljs-keyword">if</span> (condition is <span class="hljs-literal">true</span>) {
   <span class="hljs-comment">// code is executed</span>
} <span class="hljs-keyword">else</span> {
   <span class="hljs-comment">// code is executed</span>
}
</code></pre>
<p>Any value that is not defined as <code>falsy</code> would be considered <code>truthy</code> in JavaScript. </p>
<p>Here is a list of  <code>falsy</code> values:</p>
<ul>
<li>false</li>
<li>0 (zero)</li>
<li>-0 (negative zero)</li>
<li>0n (BigInt zero)</li>
<li><code>""</code>, <code>''</code>, ```` (empty string)</li>
<li>null</li>
<li>undefined</li>
<li>NaN (not a number)</li>
</ul>
<h2 id="heading-examples-of-ifelse-statements-in-javascript">Examples of if...else statements in JavaScript</h2>
<p>In this example, the condition for the <code>if</code> statement is <code>true</code> so the message printed to the console would be "Nick is an adult."</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> age = <span class="hljs-number">18</span>;

<span class="hljs-keyword">if</span> (age &gt;= <span class="hljs-number">18</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Nick is an adult."</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Nick is a child."</span>);
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screen-Shot-2021-08-09-at-3.18.12-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>But if I change the <code>age</code> variable to be less than 18, then the condition would be <code>false</code> and the code would execute the <code>else</code> block instead. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> age = <span class="hljs-number">12</span>;

<span class="hljs-keyword">if</span> (age &gt;= <span class="hljs-number">18</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Nick is an adult."</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Nick is a child."</span>);
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screen-Shot-2021-08-09-at-3.17.07-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-examples-of-multiple-conditions-ifelse-ifelse-statements-in-javascript">Examples of multiple conditions (if...else if...else statements) in JavaScript</h2>
<p>There will be times where you want to test multiple conditions. That is where the <code>else if</code> block comes in. </p>
<pre><code class="lang-js"><span class="hljs-keyword">if</span> (condition <span class="hljs-number">1</span> is <span class="hljs-literal">true</span>) {
   <span class="hljs-comment">// code is executed</span>
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (condition <span class="hljs-number">2</span> is <span class="hljs-literal">true</span>) {
  <span class="hljs-comment">// code is executed</span>
} <span class="hljs-keyword">else</span> {
   <span class="hljs-comment">// code is executed</span>
}
</code></pre>
<p>When the <code>if</code> statement is <code>false</code>, the computer will move onto the <code>else if</code> statement. If that is also <code>false</code>, then it will move onto the <code>else</code> block. </p>
<p>In this example, the <code>else if</code> block would be executed because Alice is between the ages of 18 and 21. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> age = <span class="hljs-number">18</span>;

<span class="hljs-keyword">if</span> (age &lt; <span class="hljs-number">18</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Alice is under 18 years old."</span>);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (age &gt;= <span class="hljs-number">18</span> &amp;&amp; age &lt;= <span class="hljs-number">21</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Alice is between the ages of 18 and 21."</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Alice is over 21 years old."</span>);
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screen-Shot-2021-08-09-at-3.33.33-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-when-to-use-switch-statements-over-ifelse-statements">When to use switch statements over if...else statements?</h2>
<p>There are times in JavaScript where you <a target="_blank" href="https://www.freecodecamp.org/news/javascript-switch-case-js-switch-statement-example/">might consider using a <code>switch</code> statement</a> instead of an <code>if else</code> statement.</p>
<p><code>switch</code> statements can have a cleaner syntax over complicated <code>if else</code> statements.</p>
<p>Take a look at the example below – instead of using this long <code>if else</code> statement, you might choose to go with an easier to read <code>switch</code> statement.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> pet = <span class="hljs-string">"dog"</span>;

<span class="hljs-keyword">if</span> (pet === <span class="hljs-string">"lizard"</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I own a lizard"</span>);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (pet === <span class="hljs-string">"dog"</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I own a dog"</span>);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (pet === <span class="hljs-string">"cat"</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I own a cat"</span>);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (pet === <span class="hljs-string">"snake"</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I own a snake"</span>);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (pet === <span class="hljs-string">"parrot"</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I own a parrot"</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I don't own a pet"</span>);
}
</code></pre>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> pet = <span class="hljs-string">"dog"</span>;

<span class="hljs-keyword">switch</span> (pet) {
  <span class="hljs-keyword">case</span> <span class="hljs-string">"lizard"</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I own a lizard"</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-string">"dog"</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I own a dog"</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-string">"cat"</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I own a cat"</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-string">"snake"</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I own a snake"</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-string">"parrot"</span>:
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I own a parrot"</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">"I don't own a pet"</span>);
    <span class="hljs-keyword">break</span>;
}
</code></pre>
<p><code>switch</code> statements will not be appropriate to use in all situations. But if you feel like the <code>if else</code> statements are long and complicated, then a <code>switch</code> statement could be an alternative option. </p>
<h2 id="heading-the-logical-and-ampamp-operator-and-ifelse-statements-in-javascript">The logical AND (&amp;&amp;) operator and if...else statements in JavaScript</h2>
<p>In the logical AND (<code>&amp;&amp;</code>) operator, if both conditions are <code>true</code>, then the <code>if</code> block will be executed. If one or both of the conditions are <code>false</code>, then the <code>else</code> block will be executed. </p>
<p>In this example, since age is greater than 16 and the <code>ownsCar</code> variable is <code>true</code>, the <code>if</code> block will run. The message printed to the console will be "Jerry is old enough to drive and has his own car."</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> age = <span class="hljs-number">17</span>;
<span class="hljs-keyword">const</span> ownsCar = <span class="hljs-literal">true</span>;

<span class="hljs-keyword">if</span> (age &gt;= <span class="hljs-number">16</span> &amp;&amp; ownsCar) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Jerry is old enough to drive and has his own car."</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Jerry does not drive."</span>);
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screen-Shot-2021-08-09-at-4.22.49-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If I change the <code>age</code> variable to be less than 16, then both conditions are no longer <code>true</code> and the <code>else</code> block would be executed instead. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> age = <span class="hljs-number">13</span>;
<span class="hljs-keyword">const</span> ownsCar = <span class="hljs-literal">true</span>;

<span class="hljs-keyword">if</span> (age &gt;= <span class="hljs-number">16</span> &amp;&amp; ownsCar) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Jerry is old enough to drive and has his own car."</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Jerry does not drive."</span>);
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screen-Shot-2021-08-09-at-4.20.19-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-the-logical-or-operator-and-ifelse-statements-in-javascript">The logical OR (||) operator and if...else statements in JavaScript</h2>
<p>In the logical OR (<code>||</code>) operator, if one or both of the conditions are <code>true</code>, then the code inside the <code>if</code> statement will execute. </p>
<p>In this example, even though the <code>isSale</code> variable is set to <code>false</code>, the code inside the <code>if</code> block will still execute because the <code>boyfriendIsPaying</code> variable is set to <code>true</code>. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> boyfriendIsPaying = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">const</span> isSale = <span class="hljs-literal">false</span>;

<span class="hljs-keyword">if</span> (boyfriendIsPaying || isSale) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Jesse will go shopping."</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Jesse will not go shopping."</span>);
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screen-Shot-2021-08-09-at-4.40.36-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If I were to change the value of the <code>boyfriendIsPaying</code> variable to <code>false</code>, then the <code>else</code> block would execute because both conditions are <code>false</code>. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> boyfriendIsPaying = <span class="hljs-literal">false</span>;
<span class="hljs-keyword">const</span> isSale = <span class="hljs-literal">false</span>;

<span class="hljs-keyword">if</span> (boyfriendIsPaying || isSale) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Jesse will go shopping."</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Jesse will not go shopping."</span>);
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screen-Shot-2021-08-09-at-4.42.12-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-the-logical-not-operator-and-ifelse-statements-in-javascript">The logical NOT (!) operator and if...else statements in JavaScript</h2>
<p>The logical NOT (<code>!</code>) operator will take something that is <code>true</code> and make it <code>false</code>. It will also take something that is <code>false</code> and make it <code>true</code>.</p>
<p>We can modify the example from earlier to use the <code>!</code> operator to make the <code>boyfriendIsPaying</code> variable  <code>false</code>. Since both conditions are <code>false</code>, the <code>else</code> block would be executed. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> boyfriendIsPaying = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">const</span> isSale = <span class="hljs-literal">false</span>;

<span class="hljs-keyword">if</span> (!boyfriendIsPaying || isSale) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Jesse will go shopping."</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Jesse will not go shopping."</span>);
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screen-Shot-2021-08-09-at-5.02.04-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-conditional-ternary-operator-in-javascript">Conditional (ternary) operator in JavaScript</h2>
<p>If you have a short <code>if else</code> statement, then you might choose to go with the ternary operator.  The word ternary means something composed of three parts.</p>
<p>This is the basic syntax for a ternary operator:</p>
<pre><code class="lang-js">condition ? <span class="hljs-keyword">if</span> condition is <span class="hljs-literal">true</span> : <span class="hljs-keyword">if</span> condition is <span class="hljs-literal">false</span>
</code></pre>
<p>The condition goes before the <code>?</code> mark and if it is <code>true</code>, then the code between the <code>?</code> mark and <code>:</code> would execute. If the condition is <code>false</code>, then the code after the  <code>:</code> would execute. </p>
<p>In this example, since age is greater than 18, then the message to the console would be "Can vote". </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> age = <span class="hljs-number">32</span>;
<span class="hljs-keyword">const</span> citizen = age &gt;= <span class="hljs-number">18</span> ? <span class="hljs-string">"Can vote"</span> : <span class="hljs-string">"Cannot vote"</span>;
<span class="hljs-built_in">console</span>.log(citizen);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screen-Shot-2021-08-09-at-5.25.14-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This is what the code would look like using an <code>if else</code> statement:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> age = <span class="hljs-number">32</span>;
<span class="hljs-keyword">let</span> citizen;

<span class="hljs-keyword">if</span> (age &gt;= <span class="hljs-number">18</span>) {
  citizen = <span class="hljs-string">"Can vote"</span>;
} <span class="hljs-keyword">else</span> {
  citizen = <span class="hljs-string">"Cannot vote"</span>;
}

<span class="hljs-built_in">console</span>.log(citizen);
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p><code>if else</code> statements will execute a block of code when the condition in the <code>if</code> statement is <code>truthy</code>. If the condition is <code>falsy</code>, then the <code>else</code> block will be executed. </p>
<p>There will be times where you want to test multiple conditions and you can use an <code>if...else if...else</code> statement. </p>
<p>If you feel like the <code>if else</code> statement is long and complicated, then a <code>switch</code> statement could be an alternative option. </p>
<p>Using logical operators to test multiple conditions can replace nested <code>if else</code> statements. </p>
<p>The ternary operator can be used to write shorter code for a simple <code>if else</code> statement. </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python If Else Statement – Conditional Statements Explained ]]>
                </title>
                <description>
                    <![CDATA[ There are many cases where you don't want all of your code to be executed in your programs. Instead, you might want certain code to run only when a specific condition is met, and a different set of code to run when the condition is not satisified. Th... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-if-else-statement-conditional-statements-explained/</link>
                <guid isPermaLink="false">66b1e4840968943127cc5f1e</guid>
                
                    <category>
                        <![CDATA[ Conditionals ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Dionysia Lemonaki ]]>
                </dc:creator>
                <pubDate>Thu, 29 Jul 2021 15:32:30 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/07/clement-helardot-95YRwf6CNw8-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>There are many cases where you don't want all of your code to be executed in your programs.</p>
<p>Instead, you might want certain code to run only when a specific condition is met, and a different set of code to run when the condition is not satisified.</p>
<p>That's where conditional statements come in handy.</p>
<p>Conditional statements allow you to control the logical flow of programs in a clean and compact way.</p>
<p>They are branches – like forks in the road – that modify how code is executed and handle decision making.</p>
<p>This tutorial goes over the basics of <code>if</code>, <code>if..else</code>, and <code>elif</code>  statements in the Python programming language, using examples along the way.</p>
<p>Let's get started!</p>
<h2 id="heading-the-syntax-of-a-basic-if-statement">The syntax of a basic <code>if</code> statement</h2>
<p>An <code>if</code> statement in Python essentially says:</p>
<p>"If this expression evaluates to True, then run once the code that follows  the exprerssion. If it isn't True, then don't run the block of code that follows."</p>
<p>The general syntax for a basic <code>if</code> statement looks something like this:</p>
<pre><code><span class="hljs-keyword">if</span> condition:
    execute statement
</code></pre><p>An <code>if</code> statement consists of:</p>
<ul>
<li>The <code>if</code> keyword, which starts the <code>if</code> statement.</li>
<li>Then comes a condition. A condition can evaluate to either True or False.   Parentheses (<code>()</code>) surrounding the condition are optional, but they do help improve the readability of the code when more than one condition is present.</li>
<li>A colon <code>:</code> that separates the condition from the executable statement that follows.</li>
<li>A new line.</li>
<li>A level of indentation of <strong>4</strong> spaces, which is a Python convention. The level of indentation is associated with the body of the statement that follows.</li>
<li>Lastly comes the body of the statement. This is the code that will run only if the statement evaluated to True. We can have multiple lines in the body that can be executed, and in that case we need to be careful they all have the same level of indentation. </li>
</ul>
<p>Let's take the following example:</p>
<pre><code class="lang-python">a = <span class="hljs-number">1</span>
b = <span class="hljs-number">2</span>

<span class="hljs-keyword">if</span> b &gt; a:
    print(<span class="hljs-string">" b is in fact bigger than a"</span>)
</code></pre>
<p>Output:</p>
<pre><code>b is <span class="hljs-keyword">in</span> fact bigger than a
</code></pre><p>In the example above, we created two variables, <code>a</code> and <code>b</code>, and assigned them the values <code>1</code> and <code>2</code>, respectively.</p>
<p>The phrase in the print statement does in fact get printed to the console because the condition <code>b &gt; a</code> evaluated to True, so the code that followed it ran. If it wasn't True, nothing would have happend. No code would have run.</p>
<p>If we had instead done this:</p>
<pre><code class="lang-python">a = <span class="hljs-number">1</span>
b = <span class="hljs-number">2</span>

<span class="hljs-keyword">if</span> a &gt; b
    print(<span class="hljs-string">"a is in fact bigger than b"</span>)
</code></pre>
<p>No code would have been executed and nothing would have been printed to the console.</p>
<h2 id="heading-how-do-python-ifelse-statements-work">How do Python <code>if..else</code> statements work?</h2>
<p>An <code>if</code> statement runs code only when a condition is met. Nothing happens otherwise. </p>
<p>What if we also want code to run when the condition is not met? That's where the <code>else</code> part comes in.</p>
<p>The syntax of an <code>if..else</code> statement looks like this:</p>
<pre><code><span class="hljs-keyword">if</span> condition:
    execute statement <span class="hljs-keyword">if</span> condition is True
<span class="hljs-attr">else</span>:
     execute statement <span class="hljs-keyword">if</span> condition is False
</code></pre><p>An <code>if..else</code> statement in Python means: </p>
<p>"When the <code>if</code> expression evaluates to True, then execute the code that follows it. But if it evalates to False, then run the code that follows the <code>else</code> statement"</p>
<p>The <code>else</code> statement is written on a new line after the last line of indented code and it <em>can't</em> be written by itself. An <code>else</code> statement is part of an <code>if</code> statement. </p>
<p>The code following it also needs to be indented with <strong>4</strong> spaces to show it is part of the <code>else</code> clause.</p>
<p>The code following the <code>else</code> statement gets executed <em>if and only if</em> the <code>if</code> statement is False. If your <code>if</code> statement is True and therefore the code ran, then the code in the <code>else</code> block will never run.</p>
<pre><code class="lang-python">a = <span class="hljs-number">1</span>
b = <span class="hljs-number">2</span>

<span class="hljs-keyword">if</span> a &lt; b:
    print(<span class="hljs-string">" b is in fact bigger than a"</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"a is in fact bigger than b"</span>)
</code></pre>
<p>Here, the line of code following the <code>else</code> statement, <code>print("a is in fact bigger than b")</code>, will never run. The <code>if</code> statement that came before it is True so only that code runs instead.</p>
<p>The <code>else</code> block runs when:</p>
<pre><code class="lang-python">a = <span class="hljs-number">1</span>
b = <span class="hljs-number">2</span>

<span class="hljs-keyword">if</span> a &gt; b:
    print(<span class="hljs-string">" a is in fact bigger than b"</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"b is in fact bigger than a"</span>)
</code></pre>
<p>Output:</p>
<pre><code>b is <span class="hljs-keyword">in</span> fact bigger than a
</code></pre><p>Be aware that you can't write any other code between <code>if</code> and <code>else</code>. You'll get a <code>SyntaxError</code> if you do so:</p>
<pre><code class="lang-python"><span class="hljs-keyword">if</span> <span class="hljs-number">1</span> &gt; <span class="hljs-number">2</span>:
   print(<span class="hljs-string">"1 is bigger than 2"</span>)
print(<span class="hljs-string">"hello world"</span>)
<span class="hljs-keyword">else</span>:
   print(<span class="hljs-string">"1 is less than 2"</span>)
</code></pre>
<p>Output:</p>
<pre><code>File <span class="hljs-string">"&lt;stdin&gt;"</span>, line <span class="hljs-number">3</span>
print(<span class="hljs-string">"hello world"</span>)
^
<span class="hljs-built_in">SyntaxError</span>: invalid syntax
</code></pre><h2 id="heading-how-does-elif-work-in-python">How does <code>elif</code> work in Python?</h2>
<p>What if we want to have more than just two options? </p>
<p>Instead of saying: "If the first condition is true do this, otherwise do that instead", now we say "If this isn't True, try this instead, and if all conditions fail to be True, resort to doing this".</p>
<p><code>elif</code> stands for else, if.</p>
<p>The basic syntax looks like this:</p>
<pre><code><span class="hljs-keyword">if</span> first_condition:
    execute statement
elif second_condition:
    execute statement
<span class="hljs-attr">else</span>:
    alternative executable statement <span class="hljs-keyword">if</span> all previous conditions are False
</code></pre><p>We can use more than one <code>elif</code> statement. This gives us more conditions and more options. </p>
<p>For example:</p>
<pre><code class="lang-python">x = <span class="hljs-number">1</span>

<span class="hljs-keyword">if</span> x &gt; <span class="hljs-number">10</span>:
    print(<span class="hljs-string">" x is greater than 10!"</span>)
<span class="hljs-keyword">elif</span> x &lt; <span class="hljs-number">10</span>:
      print(<span class="hljs-string">"x is less than 10!"</span>)
<span class="hljs-keyword">elif</span> x &lt; <span class="hljs-number">20</span> :
      print(<span class="hljs-string">"x is less than 20!"</span>)
<span class="hljs-keyword">else</span>:
     print(<span class="hljs-string">"x is equal to 10"</span>)
</code></pre>
<p>Output:</p>
<pre><code>x is less than <span class="hljs-number">10</span>!
</code></pre><p>In this example, the <code>if</code> statement tests a specific condition, the <code>elif</code> blocks are two alternatives, and the <code>else</code> block is the last solution when  all the previous conditions have not been met.</p>
<p>Be aware of the order in which you write your <code>elif</code> statements.</p>
<p>In the previous example, if you had written:</p>
<pre><code class="lang-python">x = <span class="hljs-number">1</span>

<span class="hljs-keyword">if</span> x &gt; <span class="hljs-number">10</span>:
    print(<span class="hljs-string">" x is greater than 10!"</span>)
<span class="hljs-keyword">elif</span> x &lt; <span class="hljs-number">20</span> :
      print(<span class="hljs-string">"x is less than 20!"</span>)
<span class="hljs-keyword">elif</span> x &lt; <span class="hljs-number">10</span>:
      print(<span class="hljs-string">"x is less than 10!"</span>)
<span class="hljs-keyword">else</span>:
     print(<span class="hljs-string">"x is equal to 10"</span>)
</code></pre>
<p>The line <code>x is less than 20!</code> would have been executed because it came first.</p>
<p>The <code>elif</code> statement makes code easier to write. You can use it instead of keeping track of <code>if..else</code> statements as programs get more complex and  grow in size.</p>
<p>If all the <code>elif</code> statements are not considered and are False, then and only then as the last resort will the code following the <code>else</code> statement run.</p>
<p>For example, here's a case when the <code>else</code> statement would run:</p>
<pre><code class="lang-python">x = <span class="hljs-number">10</span>

<span class="hljs-keyword">if</span> x &gt; <span class="hljs-number">10</span>:
    print(<span class="hljs-string">" x is greater than 10!"</span>)
<span class="hljs-keyword">elif</span> x &lt; <span class="hljs-number">10</span>:
      print(<span class="hljs-string">"x is less than 10!"</span>)
<span class="hljs-keyword">elif</span> x &gt; <span class="hljs-number">20</span> :
      print(<span class="hljs-string">"x is greater than 20!"</span>)
<span class="hljs-keyword">else</span>:
     print(<span class="hljs-string">"x is equal to 10"</span>)
</code></pre>
<p>Output</p>
<pre><code>x is equal to <span class="hljs-number">10</span>
</code></pre><h2 id="heading-conclusion">Conclusion</h2>
<p>And that's it! </p>
<p>Those are the basic principles of <code>if</code>,<code>if..else</code> and <code>elif</code> in Python to get you started with conditional statements.</p>
<p>From here the statements can get more advanced and complex.</p>
<p>Conditional statements can be nested inside of other conditional statements, depending on the problem you're trying to solve and the logic behind the solution. </p>
<p>Thanks for reading and happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Level Up Your React Conditionals ]]>
                </title>
                <description>
                    <![CDATA[ Do you write conditionals correctly within your React applications?  Good conditionals are an essential part of any React application. We use conditionals to show or hide elements or components in our applications.  In short – to be an effective Reac... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-react-conditionals/</link>
                <guid isPermaLink="false">66d037a7c44d0e8a5f41d209</guid>
                
                    <category>
                        <![CDATA[ Conditionals ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Reed ]]>
                </dc:creator>
                <pubDate>Fri, 11 Jun 2021 16:04:46 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/06/5-ways-to-level-up-your-react-conditionals-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Do you write conditionals correctly within your React applications? </p>
<p>Good conditionals are an essential part of any React application. We use conditionals to show or hide elements or components in our applications. </p>
<p>In short – to be an effective React developer, you must know how to write good conditionals.</p>
<p>Let's go over all of the major patterns you need to know to write clean, concise conditionals, plus what anti-patterns you should avoid.</p>
<h3 id="heading-want-your-own-copy">Want Your Own Copy?‬ 📄</h3>
<p><strong><a target="_blank" href="http://bit.ly/react-conditionals-2021">Download the cheatsheet in PDF format here</a></strong> (it takes 5 seconds).</p>
<p>Here are some quick wins from grabbing the downloadable version:</p>
<ul>
<li>Quick reference guide to review however and whenever</li>
<li>Tons of copyable code snippets for easy reuse</li>
<li>Read this massive guide wherever suits you best. On the train, at your desk, standing in line... anywhere.</li>
</ul>
<p>There's a ton of great stuff to cover, so let's get started.</p>
<h2 id="heading-1-use-if-statements-primarily-no-need-for-else-or-else-if">1. Use if-statements primarily. No need for else or else-if.</h2>
<p>Let's start with the most basic type of conditional in React. If we have data, we want to display it. If not, we want to show nothing.</p>
<p>Simple! How would we write that?</p>
<p>Let's say we are fetching an array of posts data from an API. When it is fetching the data, <code>posts</code> has a value of <code>undefined</code>.</p>
<p>We can check for that value with a simple if-statement.</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> { posts } = usePosts(); <span class="hljs-comment">// posts === undefined at first</span>

  <span class="hljs-keyword">if</span> (!posts) <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">PostList</span> <span class="hljs-attr">posts</span>=<span class="hljs-string">{posts}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>The reason this pattern works is that we are returning early. If it meets the condition (if <code>!posts</code> is has a boolean value of <code>true</code>), we display nothing in our component by returning <code>null</code>.</p>
<p>If statements also work when you have multiple conditions that you want to check for. </p>
<p>For example, if you want to check for loading and error states before you display your data:</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> { isLoading, isError, posts } = usePosts();

  <span class="hljs-keyword">if</span> (isLoading) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
  <span class="hljs-keyword">if</span> (isError) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Error!<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">PostList</span> <span class="hljs-attr">posts</span>=<span class="hljs-string">{posts}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>Notice that we can reuse the if-statement and do not have to write if-else or if-else-if, which cuts down on the code that we have to write and is still just as readable.</p>
<h2 id="heading-2-use-the-ternary-operator-to-write-conditionals-in-your-jsx">2. Use the ternary operator to write conditionals in your JSX</h2>
<p>If-statements are great when we want to exit early and display nothing or a totally different component.</p>
<p>However, what if we don't want to write a conditional separate from our returned JSX, but directly within it?</p>
<p>In React, we must include expressions (something that resolves to a value), not statements within our JSX. </p>
<p>This is why we must write conditionals in our JSX only with ternaries and not if-statements.</p>
<p>For example, if we wanted to display one nested component on a mobile-sized screen and another on a larger screen, a ternary would be a perfect choice:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> isMobile = useWindowSize()

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">main</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Header</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Sidebar</span> /&gt;</span>
      {isMobile ? <span class="hljs-tag">&lt;<span class="hljs-name">MobileChat</span> /&gt;</span> : <span class="hljs-tag">&lt;<span class="hljs-name">Chat</span> /&gt;</span>}
    <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span></span>
  )
}
</code></pre>
<p>Most developers think this the only pattern they can leverage when it comes to using ternaries.</p>
<p>In fact, you don't have to clutter your component tree by including all of these ternaries directly in your returned JSX.</p>
<p>Since ternaries resolve to a value, remember that you can assign the result of a ternary to a variable, which you can then use where you like:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> isMobile = useWindowSize();

  <span class="hljs-keyword">const</span> ChatComponent = isMobile ? <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">MobileChat</span> /&gt;</span></span> : <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Chat</span> /&gt;</span></span>;

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">main</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Header</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Sidebar</span> /&gt;</span>
      {ChatComponent}
    <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span></span>
  )
}
</code></pre>
<h2 id="heading-3-no-else-condition-use-the-ampamp-and-operator">3. No else condition? Use the &amp;&amp; (and) operator</h2>
<p>In many cases, you will want to use a ternary in your JSX, but will realize that if that condition is not met, you don't want to display anything.</p>
<p>This ternary would look like the following: <code>condition ? &lt;Component /&gt; : null</code>.</p>
<p>If you don't have an else condition, use the &amp;&amp; operator:</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">PostFeed</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> { posts, hasFinished } = usePosts()

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">PostList</span> <span class="hljs-attr">posts</span>=<span class="hljs-string">{posts}</span> /&gt;</span>
      {hasFinished &amp;&amp; (
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>You have reached the end!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      )}
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<h2 id="heading-4-switch-statements-for-multiple-conditions">4. Switch statements for multiple conditions</h2>
<p>What if we are in a situation where have many different conditions, more than just one or two?</p>
<p>We could certainly write multiple if-statements, but all of these if statements, as we've seen earlier, go above our returned JSX.</p>
<p>Too many if-statements can clutter our components. How do we make our code cleaner?</p>
<p>We can often extract multiple conditions to a separate component which contains a switch statement. </p>
<p>For example, we have a Menu component that we can toggle and display different tabs. </p>
<p>We have tabs that can display user, chat, and room data as you see below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Menu</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [menu, setMenu] = React.useState(<span class="hljs-number">1</span>);

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">toggleMenu</span>(<span class="hljs-params"></span>) </span>{
    setMenu(<span class="hljs-function">(<span class="hljs-params">m</span>) =&gt;</span> {
      <span class="hljs-keyword">if</span> (m === <span class="hljs-number">3</span>) <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
      <span class="hljs-keyword">return</span> m + <span class="hljs-number">1</span>;
    });
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">MenuItem</span> <span class="hljs-attr">menu</span>=<span class="hljs-string">{menu}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{toggleMenu}</span>&gt;</span>Toggle Menu<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MenuItem</span>(<span class="hljs-params">{ menu }</span>) </span>{
  <span class="hljs-keyword">switch</span> (menu) {
    <span class="hljs-keyword">case</span> <span class="hljs-number">1</span>:
      <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Users</span> /&gt;</span></span>;
    <span class="hljs-keyword">case</span> <span class="hljs-number">2</span>:
      <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Chats</span> /&gt;</span></span>;
    <span class="hljs-keyword">case</span> <span class="hljs-number">3</span>:
      <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Rooms</span> /&gt;</span></span>;
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
  }
}
</code></pre>
<p>Since we are using a dedicated MenuItem component with a switch statement, our parent Menu component is not cluttered by conditional logic and we can easily see what component will be displayed given the <code>menu</code> state.</p>
<h2 id="heading-5-want-conditionals-as-components-try-jsx-control-statements">5. Want conditionals as components? Try JSX Control Statements</h2>
<p>It's greatly beneficial to be able to use plain JavaScript within our React components. But if you want even more declarative and straightforward conditionals, check out the React library JSX control statements. </p>
<p>You can bring it into your React projects by running the following command:</p>
<pre><code class="lang-bash">npm install --save-dev babel-plugin-jsx-control-statements
</code></pre>
<p>Additionally, you can list it in your .babelrc file like so:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"plugins"</span>: [<span class="hljs-string">"jsx-control-statements"</span>]
}
</code></pre>
<p>This is a Babel plugin that allows you to use React components directly within your JSX to write very easy to understand conditionals. </p>
<p>The best way to understand the use of such a library is by taking a look at an example. Let's rewrite one of our previous examples with the help of JSX control statements:</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> { isLoading, isError, posts } = usePosts();

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Choose</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">When</span> <span class="hljs-attr">condition</span>=<span class="hljs-string">{isLoading}</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">When</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">When</span> <span class="hljs-attr">condition</span>=<span class="hljs-string">{isError}</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Error!<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">When</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Otherwise</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">PostList</span> <span class="hljs-attr">posts</span>=<span class="hljs-string">{posts}</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">Otherwise</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Choose</span>&gt;</span></span>
  );
}
</code></pre>
<p>You can see that there's no if or ternary statement in sight and we have a very readable component structure. </p>
<p>Give JSX control statements a try in your next React project and see if a library like this is for you.</p>
<h2 id="heading-whats-next"><strong>What's Next</strong></h2>
<p>I hope this guide gave you some helpful patterns to write great React conditionals.</p>
<p>If you want a copy of this cheatsheet to keep for learning purposes, you can <a target="_blank" href="http://bit.ly/react-conditionals-2021">download a complete PDF version of this cheatsheet here.</a></p>
<p>Also check out these ultimate resources, made to take your React skills to the next level, including:</p>
<ul>
<li><a target="_blank" href="https://reactbootcamp.com/react-for-beginners-2021/">React for beginners: The complete guide</a></li>
<li><a target="_blank" href="https://reactbootcamp.com/fetch-data-in-react/">How to fetch data in React from front to back</a></li>
<li><a target="_blank" href="https://reactbootcamp.com/react-app-node-backend/">How to build fullstack apps in React with Node</a></li>
</ul>
<h2 id="heading-become-a-professional-react-developer">Become a Professional React Developer</h2>
<p>React is hard. You shouldn't have to figure it out yourself.</p>
<p>I've put everything I know about React into a single course, to help you reach your goals in record time:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><strong>Introducing: The React Bootcamp</strong></a></p>
<p><strong>It’s the one course I wish I had when I started learning React.</strong></p>
<p>Click below to try the React Bootcamp for yourself:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><img src="https://reedbarger.nyc3.digitaloceanspaces.com/reactbootcamp/react-bootcamp-cta-alt.png" alt="Click to join the React Bootcamp" width="600" height="400" loading="lazy"></a>
<em>Click to get started</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What in the world is a JavaScript conditional? ]]>
                </title>
                <description>
                    <![CDATA[ By Syk Houdeib This article is a beginner's introduction to JavaScript conditionals. It covers why we need them, and how they fit into the front-end context. And why you will end up using them regularly. Introduction I came into development from a no... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-in-the-world-is-a-javascript-conditional-for/</link>
                <guid isPermaLink="false">66d4615136c45a88f96b7d07</guid>
                
                    <category>
                        <![CDATA[ 100DaysOfCode ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Conditionals ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 14 Oct 2019 12:25:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/09/scott-webb-GQD3Av_9A88-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Syk Houdeib</p>
<p>This article is a beginner's introduction to JavaScript conditionals. It covers why we need them, and how they fit into the front-end context. And why you will end up using them regularly.</p>
<h2 id="heading-introduction">Introduction</h2>
<p>I came into development from a non-traditional path. One thing was always particularly hard – to be able to go beyond the syntax of a new concept and place it in a context that made sense.</p>
<p>Conditionals are a little more intuitive than other concepts, but I want to show you the big picture. In this article, I'll explain why we need conditionals and how we can use them as front-end developers.</p>
<p>With the help of a beginner-friendly practical example, you'll see how you can use conditionals to process data in different ways and why they're a fundamental tool in development. Feel free to follow along while reading through this article.</p>
<p>The only prerequisite is a basic understanding of arrays and loops. I've covered those in two previous articles: </p>
<p><strong>Arrays</strong>: <a target="_blank" href="https://www.freecodecamp.org/news/what-in-the-world-is-a-javascript-array/">https://www.freecodecamp.org/news/what-in-the-world-is-a-javascript-array/</a></p>
<p><strong>Loops</strong>: <a target="_blank" href="https://www.freecodecamp.org/news/what-in-the-world-is-a-javascript-loop-for/">https://www.freecodecamp.org/news/what-in-the-world-is-a-javascript-loop-for/</a> </p>
<h3 id="heading-the-setup">The setup</h3>
<p>Let’s imagine that we are working on an online platform that allows us to do our grocery shopping from a website. That's a real-world application of the things we want to talk about here.</p>
<p>Take a look at <a target="_blank" href="https://lolamarket.com/tienda">Lola Market</a>, which is where I work, for an example of what this would look like.</p>
<p>In the example we set up in the previous articles, we took a bunch of products (mushrooms, steak, fish, aubergines, and lentils) and organised them inside an array. We then stored that array as a variable and used a <code>forEach</code> loop to iterate over the list.</p>
<p>We are assuming that this list of products is now displayed on our website. Our task is to add a "(v)" next to vegetarian items on this list. This is just the kind of thing we regularly do on the front end.</p>
<h2 id="heading-conditionals">Conditionals</h2>
<p>Conditionals are essential building blocks of programming. They are a way to do something only <strong>if</strong> certain <strong>conditions</strong> are met. The simplest and most common conditional in JavaScript is the <code>if</code> statement. Take a look at an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">if</span> (product === <span class="hljs-string">'steak'</span>) {
    <span class="hljs-comment">// do stuff</span>
}
</code></pre>
<p>Let’s start by translating this to English: “If the variable called <code>product</code> is exactly the string of characters 'steak' then execute the code within.”</p>
<p>Here’s a closer look</p>
<ul>
<li><code>if</code>: This is the conditional.</li>
<li><code>(product === ‘steak’)</code>: This is our condition. There are a lot of ways you can construct conditions. We don’t need to worry about this yet. For now, bear in mind that whatever we put here will always be evaluated to either <code>true</code> or <code>false</code>.</li>
<li><code>// do stuff</code>: The statement. This is where the code we want to run goes. It will be executed <strong>only</strong> if the result of the evaluation of the condition is <code>true</code>. Otherwise, it will be ignored.</li>
</ul>
<p>This bit of code will work on its own just fine, but we can have much more detailed control by using its friends  <code>else if</code> and <code>else</code>. <code>else if</code> adds another condition to check and executes another separate block of code, while <code>else</code> becomes the default action to take if none of the conditions are met.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/image-214.png" alt="Image" width="600" height="400" loading="lazy">
_Photo by [Unsplash](https://unsplash.com/@jckbck?utm_source=ghost&amp;utm_medium=referral&amp;utm_campaign=api-credit"&gt;Jakub Dziubak / &lt;a href="https://unsplash.com/?utm_source=ghost&amp;utm_medium=referral&amp;utm<em>campaign=api-credit)</em></p>
<h3 id="heading-vegetarian-friendly">Vegetarian Friendly</h3>
<p>Let’s focus back on our original objective, which is to log a “(v)” next to the name of vegetarian items. This is a prime example of when we need to use a conditional. We want code that, <strong>if</strong> the <code>product</code> in the array <strong>is</strong> vegetarian, to print its name and add to it the “(v)”. And if it’s not vegetarian, to only print the name of the <code>product</code>.</p>
<p>First, we need to identify vegetarian items. Normally this information will be included with the data we requested from our database. But since we are using a simplified example, we will do it manually. We know that steak and fish are not vegetarian.</p>
<p>Notice, the condition I’m testing is if a product <strong>is not</strong> vegetarian. This is only because there are more vegetarian products on this list and I want the condition to be simple and the conditional to do the least amount of work. I could have just as easily tested for vegetarian items instead.</p>
<p>There are often many conditions that can be used to achieve the same goal. Writing good conditions that are efficient and readable is a useful skill that comes with practice.</p>
<p>So let’s write the condition that separates vegetarian from non-vegetarian.</p>
<pre><code class="lang-js"><span class="hljs-keyword">if</span> (product === <span class="hljs-string">'steak'</span> || product === <span class="hljs-string">'fish'</span>) {
    <span class="hljs-built_in">console</span>.log(product)
} <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(product + <span class="hljs-string">'(v)'</span>)
}
</code></pre>
<p>Following on from the example in my previous articles (linked above) we want to place the conditional inside the loop. The loop gives us each product in the list to process individually. This conditional block is the code that we are executing for each product in our array of products now.</p>
<p>Refresh the browser to start with a fresh console, then enter the following:</p>
<ul>
<li>The variable <code>product</code> storing our array of products.</li>
<li>The <code>forEach</code> loop iterating over the array.</li>
<li>And our conditional block inside.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/09/conditional.PNG" alt="The dev tools console with our full code now using the conditional inside of the loop" width="600" height="400" loading="lazy">
<em>The conditional block running inside of a loop</em></p>
<h3 id="heading-execution">Execution</h3>
<p>If we read the conditional code in <strong>plain English</strong> it says: “<strong>If</strong> the currently selected <code>product</code> <strong>is</strong> exactly ‘steak’ <strong>or</strong> ‘fish’ then log <code>product</code> to the console. Otherwise, in all other cases log <code>product</code> to the console but also add a string “(v)” to the end of it.”</p>
<p>Quick note, the <code>===</code> operator checks that the left and right expressions are <strong>exactly</strong> the same. and the <code>||</code> operator means <strong>or.</strong> We have two conditions to check here (steak or fish)<strong>.</strong> If <strong>either</strong> of the two conditions is true it will execute the code within.</p>
<p>Hit enter to run the code and see the results.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/09/conditional-result.PNG" alt="The result of executing the code in the console. It prints the vegetarian items with a (v) at the end" width="600" height="400" loading="lazy">
<em>The result of the loop with the conditionals</em></p>
<p>And there it is. Every time the loop runs, it checks the currently selected element <code>product</code> and goes through the conditionals.</p>
<ul>
<li>Is <code>product</code> exactly the string ‘steak’?</li>
<li>No. Check the following condition.</li>
<li>Is <code>product</code> exactly the string ‘fish’?</li>
<li>No. This condition is not met, the code inside will not execute. Go to the default code specified in the <code>else</code> block.</li>
<li>Print <code>product</code> and add <code>(v)</code> to it.</li>
<li>This iteration is finished. Start the next iteration.</li>
</ul>
<p>If it finds ‘steak’ or ‘fish’ it will execute the code within that condition logging the <code>product</code> name without the "(v)". Then the loop finishes that iteration and starts the next, and so on. This process repeats for each element in the array until it’s all completed and the loop has logged the correct message for each one.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>To recap, a <strong>conditional statement</strong> sets certain <strong>conditions.</strong> When met (which means when the condition evaluates to <code>true</code>) the code specified inside the conditional block <strong>executes</strong>. Otherwise, it is ignored and not executed.</p>
<p>In our example, we have only logged messages to the console. But we can use the same idea to manipulate the DOM to display and modify content on a website.</p>
<p>Here are a few things you will need to further expand your knowledge and understand these concepts more in-depth:</p>
<ul>
<li><strong>Conditionals:</strong> The <code>if</code> statement is one of the most commonly-used conditionals. But you will need to learn about others like the <code>while</code> statement, the <code>switch</code> statement, or the very useful <strong>ternary operator</strong>.</li>
<li><strong>Conditions:</strong> Understand how to create conditions and how they are evaluated. For that, you need to become familiar with the concepts of “<strong>truthy</strong>” and “<strong>falsy</strong>”. This is when values that are not explicitly <code>true</code> or <code>false</code> are evaluated as such.  For example, a string like <code>'mushrooms'</code> is considered true whereas an empty string <code>''</code> is always considered false.</li>
<li><strong>Logical operators and comparison operators:</strong> We saw those in our conditions. Logical operators like “<em>and”</em> and “<em>or”</em>, written <code>&amp;&amp;</code> and <code>||</code>. Comparison operators like <em>“equals”</em> and <em>“greater than”</em>, written <code>===</code> and <code>&gt;</code>. These are simple concepts that are the bread and butter of writing code.</li>
</ul>
<h3 id="heading-closure">Closure</h3>
<p>Thanks for reading. I hope you found this useful. And if you enjoyed it, sharing it around would be greatly appreciated. If you have any questions or comments I’m on <a target="_blank" href="https://twitter.com/Syknapse">Twitter</a> <a target="_blank" href="https://twitter.com/Syknapse">@Syknapse</a> and I would love to hear from you.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/08/image-157.png" alt="Image" width="600" height="400" loading="lazy">
<em>Photo by <a target="_blank" href="https://twitter.com/__Santaella">Claudia</a></em></p>
<p>My name is Syk and I’m a front-end developer at <a target="_blank" href="https://twitter.com/Tech_LolaMarket">Lola Market</a> in Madrid. I career-changed into web dev from an unrelated field, so I try to create content for those on a similar journey. My DMs are always open for aspiring web developers in need of some support. You can also read about my transformation in <a target="_blank" href="https://www.freecodecamp.org/news/how-i-switched-careers-and-got-a-developer-job-in-10-months-a-true-story-b8895e855a8b/">this article</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
